참고소스 수정본
This commit is contained in:
114
참고/instructor-main/docs/learning/streaming/basics.md
Normal file
114
참고/instructor-main/docs/learning/streaming/basics.md
Normal file
@@ -0,0 +1,114 @@
|
||||
---
|
||||
title: Streaming Basics with Instructor
|
||||
description: Learn how to use streaming to receive partial structured responses from LLMs as they are generated.
|
||||
---
|
||||
|
||||
# Streaming Basics
|
||||
|
||||
Streaming allows you to receive parts of a structured response as they're generated, rather than waiting for the complete response.
|
||||
|
||||
## Why Use Streaming?
|
||||
|
||||
Streaming offers several benefits:
|
||||
|
||||
1. **Faster Perceived Response**: Users see results immediately
|
||||
2. **Progressive UI Updates**: Update your interface as data arrives
|
||||
3. **Processing While Generating**: Start using data before the complete response is ready
|
||||
|
||||
```
|
||||
Without Streaming:
|
||||
┌─────────┐ ┌─────────────────────┐
|
||||
│ Request │─── Wait ───>│ Complete Response │
|
||||
└─────────┘ └─────────────────────┘
|
||||
|
||||
With Streaming:
|
||||
┌─────────┐ ┌───────┐ ┌───────┐ ┌───────┐
|
||||
│ Request │───>│Part 1 │───>│Part 2 │───>│Part 3 │─── ...
|
||||
└─────────┘ └───────┘ └───────┘ └───────┘
|
||||
```
|
||||
|
||||
## Simple Example
|
||||
|
||||
Here's how to stream a structured response:
|
||||
|
||||
```python
|
||||
import instructor
|
||||
from pydantic import BaseModel
|
||||
# Define your data structure
|
||||
class UserProfile(BaseModel):
|
||||
name: str
|
||||
bio: str
|
||||
interests: list[str]
|
||||
|
||||
# Set up client
|
||||
client = instructor.from_provider("openai/gpt-5-nano")
|
||||
|
||||
# Enable streaming
|
||||
for partial in client.create(
|
||||
model="gpt-3.5-turbo",
|
||||
messages=[
|
||||
{"role": "user", "content": "Generate a profile for Alex Chen"}
|
||||
],
|
||||
response_model=UserProfile,
|
||||
stream=True # This enables streaming
|
||||
):
|
||||
# Print each update as it arrives
|
||||
print("\nUpdate received:")
|
||||
|
||||
# Access available fields
|
||||
if hasattr(partial, "name") and partial.name:
|
||||
print(f"Name: {partial.name}")
|
||||
if hasattr(partial, "bio") and partial.bio:
|
||||
print(f"Bio: {partial.bio[:30]}...")
|
||||
if hasattr(partial, "interests") and partial.interests:
|
||||
print(f"Interests: {', '.join(partial.interests)}")
|
||||
```
|
||||
|
||||
## How Streaming Works
|
||||
|
||||
When streaming with Instructor:
|
||||
|
||||
1. Enable streaming with `stream=True`
|
||||
2. The method returns an iterator of partial responses
|
||||
3. Each partial contains fields that have been completed so far
|
||||
4. You check for fields using `hasattr()` since they appear incrementally
|
||||
5. The final iteration contains the complete response
|
||||
|
||||
## Progress Tracking Example
|
||||
|
||||
Here's a simple way to track progress:
|
||||
|
||||
```python
|
||||
import instructor
|
||||
from pydantic import BaseModel
|
||||
client = instructor.from_provider("openai/gpt-5-nano")
|
||||
|
||||
class Report(BaseModel):
|
||||
title: str
|
||||
summary: str
|
||||
conclusion: str
|
||||
|
||||
# Track completed fields
|
||||
completed = set()
|
||||
total_fields = 3 # Number of fields in our model
|
||||
|
||||
for partial in client.create(
|
||||
model="gpt-3.5-turbo",
|
||||
messages=[
|
||||
{"role": "user", "content": "Generate a report on climate change"}
|
||||
],
|
||||
response_model=Report,
|
||||
stream=True
|
||||
):
|
||||
# Check which fields are complete
|
||||
for field in ["title", "summary", "conclusion"]:
|
||||
if hasattr(partial, field) and getattr(partial, field) and field not in completed:
|
||||
completed.add(field)
|
||||
percent = (len(completed) / total_fields) * 100
|
||||
print(f"Received: {field} - {percent:.0f}% complete")
|
||||
```
|
||||
|
||||
## Next Steps
|
||||
|
||||
- Explore [Streaming Lists](lists.md) for handling collections
|
||||
- Learn about [Validation with Streaming](../validation/basics.md)
|
||||
101
참고/instructor-main/docs/learning/streaming/lists.md
Normal file
101
참고/instructor-main/docs/learning/streaming/lists.md
Normal file
@@ -0,0 +1,101 @@
|
||||
---
|
||||
title: Streaming Lists with Instructor
|
||||
description: Learn how to stream lists of structured objects from LLMs, processing collection items as they are generated for better responsiveness.
|
||||
---
|
||||
|
||||
# Streaming Lists
|
||||
|
||||
This guide explains how to stream lists of structured data with Instructor. Streaming lists allows you to process collection items as they're generated, improving responsiveness for larger outputs.
|
||||
|
||||
## Basic List Streaming
|
||||
|
||||
Here's how to stream a list of structured objects:
|
||||
|
||||
```python
|
||||
from typing import Iterable
|
||||
import instructor
|
||||
from pydantic import BaseModel, Field
|
||||
# Initialize the client
|
||||
client = instructor.from_provider("openai/gpt-5-nano")
|
||||
|
||||
class Book(BaseModel):
|
||||
title: str = Field(..., description="Book title")
|
||||
author: str = Field(..., description="Book author")
|
||||
year: int = Field(..., description="Publication year")
|
||||
|
||||
# Stream a list of books
|
||||
for book in client.create(
|
||||
model="gpt-3.5-turbo",
|
||||
messages=[
|
||||
{"role": "user", "content": "List 5 classic science fiction books"}
|
||||
],
|
||||
response_model=Iterable[Book],
|
||||
):
|
||||
print(f"Received: {book.title} by {book.author} ({book.year})")
|
||||
```
|
||||
|
||||
This example shows how to:
|
||||
1. Define a Pydantic model for each list item
|
||||
2. Use Python's typing system to specify a list
|
||||
3. Process each item as it arrives in the stream
|
||||
|
||||
## Real-world Example: Task Generation
|
||||
|
||||
Here's a practical example of streaming a list of tasks with progress tracking:
|
||||
|
||||
```python
|
||||
from typing import Iterable
|
||||
import instructor
|
||||
from pydantic import BaseModel, Field
|
||||
import time
|
||||
client = instructor.from_provider("openai/gpt-5-nano")
|
||||
|
||||
|
||||
class Task(BaseModel):
|
||||
title: str = Field(..., description="Task title")
|
||||
description: str = Field(..., description="Detailed task description")
|
||||
priority: str = Field(..., description="Task priority (High/Medium/Low)")
|
||||
estimated_hours: float = Field(..., description="Estimated hours to complete")
|
||||
|
||||
|
||||
print("Generating project tasks...")
|
||||
start_time = time.time()
|
||||
received_tasks = 0
|
||||
|
||||
for task in client.create(
|
||||
model="gpt-3.5-turbo",
|
||||
messages=[
|
||||
{
|
||||
"role": "user",
|
||||
"content": "Generate a list of 5 tasks for building a personal website",
|
||||
}
|
||||
],
|
||||
response_model=Iterable[Task],
|
||||
stream=True,
|
||||
):
|
||||
received_tasks += 1
|
||||
print(f"\nTask {received_tasks}: {task.title} (Priority: {task.priority})")
|
||||
print(f"Description: {task.description[:100]}...")
|
||||
print(f"Estimated time: {task.estimated_hours} hours")
|
||||
|
||||
# Calculate progress percentage based on expected items
|
||||
progress = (received_tasks / 5) * 100
|
||||
print(f"Progress: {progress:.0f}%")
|
||||
|
||||
elapsed_time = time.time() - start_time
|
||||
print(f"\nAll {received_tasks} tasks generated in {elapsed_time:.2f} seconds")
|
||||
|
||||
```
|
||||
|
||||
## Related Resources
|
||||
|
||||
- [Streaming Basics](./basics.md) - Fundamentals of streaming structured outputs
|
||||
- [List Extraction](../../learning/patterns/list_extraction.md) - Core concepts for working with lists
|
||||
- [Validation Basics](../../learning/validation/basics.md) - Understanding validation for streaming
|
||||
- [Streaming API](../../concepts/partial.md) - Technical details on the streaming implementation
|
||||
|
||||
## Next Steps
|
||||
|
||||
- Learn about [Validation](../../learning/validation/basics.md) to ensure your streamed data is valid
|
||||
- Explore [Field Validation](../../learning/validation/field_level_validation.md) for more control
|
||||
- See [Async Support](../../integrations/index.md) for integrating streaming with your specific provider when writing asynchronous code
|
||||
Reference in New Issue
Block a user