"""
Pattern 078: Streaming Agent
Description:
A Streaming Agent delivers responses in real-time as they are generated, rather
than waiting for complete output. This pattern is essential for building responsive
user interfaces and handling long-running generation tasks. It provides immediate
feedback to users and enables progressive rendering of results.
The agent streams tokens as they are generated by the LLM, allowing for better
user experience in conversational interfaces, content generation, and real-time
data processing. It supports multiple streaming modes including token-by-token,
chunk-by-chunk, and structured streaming with metadata.
Components:
1. Token Streamer: Streams individual tokens as generated
2. Chunk Streamer: Streams semantic chunks (sentences, paragraphs)
3. Event Streamer: Streams events with metadata and progress
4. Progress Tracker: Monitors generation progress
5. Buffer Manager: Manages streaming buffers and backpressure
6. Error Handler: Handles streaming errors gracefully
7. Aggregator: Collects streamed content for final result
8. Rate Controller: Controls streaming rate
Key Features:
- Real-time token streaming
- Chunk-based streaming
- Progress callbacks
- Cancellation support
- Error recovery during streaming
- Multiple output formats
- Backpressure handling
- Stream aggregation
- Event-driven architecture
- WebSocket support
Use Cases:
- Conversational chatbots with typing indicators
- Long-form content generation
- Real-time translation services
- Live code generation and explanation
- Progressive document analysis
- Interactive storytelling
- Streaming search results
- Real-time data processing
- Live transcription and summarization
- Collaborative writing tools
LangChain Implementation:
Uses ChatOpenAI with streaming=True, callbacks for progress tracking,
and LCEL chains with streaming support.
"""
import os
import time
import asyncio
from typing import List, Dict, Any, Optional, Iterator, AsyncIterator, Callable
from dataclasses import dataclass, field
from enum import Enum
from datetime import datetime
from collections import deque
from dotenv import load_dotenv
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.output_parsers import StrOutputParser
from langchain_openai import ChatOpenAI
from langchain_core.callbacks import BaseCallbackHandler
load_dotenv()
class StreamMode(Enum):
"""Streaming modes"""
TOKEN = "token" # Stream individual tokens
CHUNK = "chunk" # Stream semantic chunks
SENTENCE = "sentence" # Stream complete sentences
PARAGRAPH = "paragraph" # Stream complete paragraphs
EVENT = "event" # Stream with events and metadata
class StreamStatus(Enum):
"""Stream status"""
STARTING = "starting"
STREAMING = "streaming"
PAUSED = "paused"
COMPLETED = "completed"
ERROR = "error"
CANCELLED = "cancelled"
@dataclass
class StreamEvent:
"""Event in the stream"""
event_type: str # token, chunk, progress, complete, error
content: str
timestamp: datetime
metadata: Dict[str, Any] = field(default_factory=dict)
token_count: int = 0
progress: float = 0.0 # 0.0 to 1.0
@dataclass
class StreamConfig:
"""Configuration for streaming"""
mode: StreamMode = StreamMode.TOKEN
buffer_size: int = 100
flush_interval: float = 0.1 # seconds
max_tokens: Optional[int] = None
show_progress: bool = True
aggregate_result: bool = True
error_recovery: bool = True
@dataclass
class StreamResult:
"""Result of streaming operation"""
full_content: str
events: List[StreamEvent]
status: StreamStatus
total_tokens: int
duration: float
error: Optional[str] = None
class StreamingCallbackHandler(BaseCallbackHandler):
"""Callback handler for streaming events"""
def __init__(
self,
on_token: Optional[Callable[[str], None]] = None,
on_chunk: Optional[Callable[[str], None]] = None
):
"""Initialize callback handler"""
self.on_token = on_token
self.on_chunk = on_chunk
self.tokens: List[str] = []
def on_llm_new_token(self, token: str, **kwargs) -> None:
"""Called when new token is generated"""
self.tokens.append(token)
if self.on_token:
self.on_token(token)
def on_llm_end(self, response, **kwargs) -> None:
"""Called when generation ends"""
if self.on_chunk:
full_text = "".join(self.tokens)
self.on_chunk(full_text)
class StreamingAgent:
"""
Agent that streams responses in real-time.
This agent provides various streaming capabilities including token streaming,
chunk streaming, and event streaming with progress tracking.
"""
def __init__(self, config: StreamConfig = StreamConfig()):
"""Initialize the streaming agent"""
self.config = config
# Streaming LLM
self.llm = ChatOpenAI(
model="gpt-3.5-turbo",
temperature=0.7,
streaming=True
)
# Non-streaming LLM for comparison
self.sync_llm = ChatOpenAI(model="gpt-3.5-turbo", temperature=0.7)
# Stream state
self.status = StreamStatus.STARTING
self.buffer: deque = deque(maxlen=config.buffer_size)
self.events: List[StreamEvent] = []
def stream_tokens(
self,
prompt: str,
on_token: Optional[Callable[[str], None]] = None
) -> StreamResult:
"""
Stream tokens as they are generated.
Args:
prompt: Input prompt
on_token: Callback for each token
Returns:
StreamResult with full content and events
"""
start_time = time.time()
full_content = ""
token_count = 0
self.status = StreamStatus.STREAMING
# Create callback handler
callback = StreamingCallbackHandler(on_token=on_token)
try:
# Stream tokens
for chunk in self.llm.stream(prompt):
if hasattr(chunk, 'content'):
token = chunk.content
full_content += token
token_count += 1
# Create event
event = StreamEvent(
event_type="token",
content=token,
timestamp=datetime.now(),
token_count=token_count,
progress=min(1.0, token_count / (self.config.max_tokens or 1000))
)
self.events.append(event)
# Call custom callback
if on_token:
on_token(token)
self.status = StreamStatus.COMPLETED
return StreamResult(
full_content=full_content,
events=self.events.copy(),
status=self.status,
total_tokens=token_count,
duration=time.time() - start_time
)
except Exception as e:
self.status = StreamStatus.ERROR
return StreamResult(
full_content=full_content,
events=self.events.copy(),
status=self.status,
total_tokens=token_count,
duration=time.time() - start_time,
error=str(e)
)
def stream_chunks(
self,
prompt: str,
chunk_size: int = 50,
on_chunk: Optional[Callable[[str], None]] = None
) -> StreamResult:
"""
Stream content in chunks.
Args:
prompt: Input prompt
chunk_size: Size of chunks in characters
on_chunk: Callback for each chunk
Returns:
StreamResult with full content and events
"""
start_time = time.time()
full_content = ""
current_chunk = ""
chunk_count = 0
self.status = StreamStatus.STREAMING
try:
for chunk in self.llm.stream(prompt):
if hasattr(chunk, 'content'):
token = chunk.content
current_chunk += token
full_content += token
# Emit chunk when size reached
if len(current_chunk) >= chunk_size:
chunk_count += 1
event = StreamEvent(
event_type="chunk",
content=current_chunk,
timestamp=datetime.now(),
metadata={"chunk_number": chunk_count}
)
self.events.append(event)
if on_chunk:
on_chunk(current_chunk)
current_chunk = ""
# Emit final chunk
if current_chunk:
chunk_count += 1
event = StreamEvent(
event_type="chunk",
content=current_chunk,
timestamp=datetime.now(),
metadata={"chunk_number": chunk_count, "final": True}
)
self.events.append(event)
if on_chunk:
on_chunk(current_chunk)
self.status = StreamStatus.COMPLETED
return StreamResult(
full_content=full_content,
events=self.events.copy(),
status=self.status,
total_tokens=len(full_content.split()),
duration=time.time() - start_time
)
except Exception as e:
self.status = StreamStatus.ERROR
return StreamResult(
full_content=full_content,
events=self.events.copy(),
status=self.status,
total_tokens=len(full_content.split()),
duration=time.time() - start_time,
error=str(e)
)
def stream_with_progress(
self,
prompt: str,
estimated_tokens: int = 200,
on_progress: Optional[Callable[[float, str], None]] = None
) -> StreamResult:
"""
Stream with progress tracking.
Args:
prompt: Input prompt
estimated_tokens: Estimated total tokens for progress
on_progress: Callback with progress (0.0-1.0) and content
Returns:
StreamResult with full content and progress events
"""
start_time = time.time()
full_content = ""
token_count = 0
self.status = StreamStatus.STREAMING
try:
for chunk in self.llm.stream(prompt):
if hasattr(chunk, 'content'):
token = chunk.content
full_content += token
token_count += 1
# Calculate progress
progress = min(1.0, token_count / estimated_tokens)
# Create progress event
event = StreamEvent(
event_type="progress",
content=token,
timestamp=datetime.now(),
token_count=token_count,
progress=progress,
metadata={
"estimated_remaining": max(0, estimated_tokens - token_count)
}
)
self.events.append(event)
# Call progress callback
if on_progress:
on_progress(progress, full_content)
# Final progress event
event = StreamEvent(
event_type="complete",
content="",
timestamp=datetime.now(),
token_count=token_count,
progress=1.0
)
self.events.append(event)
if on_progress:
on_progress(1.0, full_content)
self.status = StreamStatus.COMPLETED
return StreamResult(
full_content=full_content,
events=self.events.copy(),
status=self.status,
total_tokens=token_count,
duration=time.time() - start_time
)
except Exception as e:
self.status = StreamStatus.ERROR
return StreamResult(
full_content=full_content,
events=self.events.copy(),
status=self.status,
total_tokens=token_count,
duration=time.time() - start_time,
error=str(e)
)
async def stream_async(
self,
prompt: str,
on_token: Optional[Callable[[str], None]] = None
) -> StreamResult:
"""
Stream asynchronously.
Args:
prompt: Input prompt
on_token: Callback for each token
Returns:
StreamResult with full content and events
"""
start_time = time.time()
full_content = ""
token_count = 0
self.status = StreamStatus.STREAMING
try:
async for chunk in self.llm.astream(prompt):
if hasattr(chunk, 'content'):
token = chunk.content
full_content += token
token_count += 1
event = StreamEvent(
event_type="token",
content=token,
timestamp=datetime.now(),
token_count=token_count
)
self.events.append(event)
if on_token:
on_token(token)
# Simulate async processing
await asyncio.sleep(0.001)
self.status = StreamStatus.COMPLETED
return StreamResult(
full_content=full_content,
events=self.events.copy(),
status=self.status,
total_tokens=token_count,
duration=time.time() - start_time
)
except Exception as e:
self.status = StreamStatus.ERROR
return StreamResult(
full_content=full_content,
events=self.events.copy(),
status=self.status,
total_tokens=token_count,
duration=time.time() - start_time,
error=str(e)
)
def stream_chain(
self,
inputs: Dict[str, str],
on_chunk: Optional[Callable[[str], None]] = None
) -> StreamResult:
"""
Stream output from a chain.
Args:
inputs: Chain inputs
on_chunk: Callback for each chunk
Returns:
StreamResult with full content
"""
start_time = time.time()
full_content = ""
# Create a streaming chain
prompt = ChatPromptTemplate.from_template(
"Write a {tone} {content_type} about {topic}."
)
chain = prompt | self.llm | StrOutputParser()
self.status = StreamStatus.STREAMING
try:
for chunk in chain.stream(inputs):
full_content += chunk
event = StreamEvent(
event_type="chunk",
content=chunk,
timestamp=datetime.now()
)
self.events.append(event)
if on_chunk:
on_chunk(chunk)
self.status = StreamStatus.COMPLETED
return StreamResult(
full_content=full_content,
events=self.events.copy(),
status=self.status,
total_tokens=len(full_content.split()),
duration=time.time() - start_time
)
except Exception as e:
self.status = StreamStatus.ERROR
return StreamResult(
full_content=full_content,
events=self.events.copy(),
status=self.status,
total_tokens=len(full_content.split()),
duration=time.time() - start_time,
error=str(e)
)
def compare_streaming_vs_sync(
self,
prompt: str
) -> Dict[str, Any]:
"""
Compare streaming vs synchronous generation.
Args:
prompt: Input prompt
Returns:
Comparison results
"""
# Streaming generation
stream_start = time.time()
stream_result = self.stream_tokens(prompt)
stream_duration = time.time() - stream_start
# Clear events for sync test
self.events = []
# Synchronous generation
sync_start = time.time()
sync_content = self.sync_llm.invoke(prompt).content
sync_duration = time.time() - sync_start
return {
"streaming": {
"duration": stream_duration,
"content_length": len(stream_result.full_content),
"tokens": stream_result.total_tokens,
"time_to_first_token": stream_result.events[0].timestamp.timestamp() - stream_start if stream_result.events else 0
},
"synchronous": {
"duration": sync_duration,
"content_length": len(sync_content),
"time_to_first_token": sync_duration # Same as total for sync
},
"comparison": {
"streaming_faster": stream_duration < sync_duration,
"ttft_improvement": "Immediate (streaming)" if stream_result.events else "N/A"
}
}
def demonstrate_streaming_agent():
"""Demonstrate the streaming agent capabilities"""
print("=" * 80)
print("STREAMING AGENT DEMONSTRATION")
print("=" * 80)
agent = StreamingAgent()
# Demo 1: Token Streaming
print("\n" + "=" * 80)
print("DEMO 1: Token-by-Token Streaming")
print("=" * 80)
prompt = "Write a short poem about artificial intelligence."
print(f"\nPrompt: {prompt}")
print("\nStreaming response:")
print("-" * 80)
# Track tokens
tokens_received = []
def on_token(token: str):
tokens_received.append(token)
print(token, end="", flush=True)
result = agent.stream_tokens(prompt, on_token=on_token)
print("\n" + "-" * 80)
print(f"\nStream Status: {result.status.value}")
print(f"Total Tokens: {result.total_tokens}")
print(f"Duration: {result.duration:.3f}s")
print(f"Tokens/sec: {result.total_tokens / result.duration:.1f}")
print(f"Events Captured: {len(result.events)}")
# Demo 2: Chunk Streaming
print("\n" + "=" * 80)
print("DEMO 2: Chunk-Based Streaming")
print("=" * 80)
prompt2 = "Explain how streaming improves user experience in AI applications."
print(f"\nPrompt: {prompt2}")
print("\nStreaming in chunks (50 chars each):")
print("-" * 80)
chunks_received = []
def on_chunk(chunk: str):
chunks_received.append(chunk)
print(f"\n[Chunk {len(chunks_received)}]: {chunk}", end="")
agent.events = [] # Reset events
result2 = agent.stream_chunks(prompt2, chunk_size=50, on_chunk=on_chunk)
print("\n" + "-" * 80)
print(f"\nTotal Chunks: {len(chunks_received)}")
print(f"Full Content Length: {len(result2.full_content)} chars")
print(f"Duration: {result2.duration:.3f}s")
# Demo 3: Progress Tracking
print("\n" + "=" * 80)
print("DEMO 3: Streaming with Progress Tracking")
print("=" * 80)
prompt3 = "Write a brief history of machine learning in three paragraphs."
print(f"\nPrompt: {prompt3}")
print("\nStreaming with progress updates:")
print("-" * 80)
progress_updates = []
def on_progress(progress: float, content: str):
progress_updates.append(progress)
# Show progress bar every 10%
if len(progress_updates) % 20 == 0:
bar_length = 40
filled = int(bar_length * progress)
bar = "█" * filled + "░" * (bar_length - filled)
print(f"\r[{bar}] {progress*100:.0f}%", end="", flush=True)
agent.events = [] # Reset events
result3 = agent.stream_with_progress(prompt3, estimated_tokens=150, on_progress=on_progress)
print("\n" + "-" * 80)
print(f"\n✓ Streaming complete!")
print(f"Total Tokens: {result3.total_tokens}")
print(f"Duration: {result3.duration:.3f}s")
print(f"Progress Updates: {len(progress_updates)}")
# Show first 200 chars of content
print(f"\nContent Preview:")
print(result3.full_content[:200] + "...")
# Demo 4: Chain Streaming
print("\n" + "=" * 80)
print("DEMO 4: Streaming Chain Output")
print("=" * 80)
inputs = {
"tone": "inspirational",
"content_type": "story",
"topic": "perseverance"
}
print(f"\nChain Inputs:")
for key, value in inputs.items():
print(f" {key}: {value}")
print("\nStreaming chain output:")
print("-" * 80)
agent.events = [] # Reset events
def on_chain_chunk(chunk: str):
print(chunk, end="", flush=True)
result4 = agent.stream_chain(inputs, on_chunk=on_chain_chunk)
print("\n" + "-" * 80)
print(f"\nChain Duration: {result4.duration:.3f}s")
print(f"Content Length: {len(result4.full_content)} chars")
# Demo 5: Streaming vs Sync Comparison
print("\n" + "=" * 80)
print("DEMO 5: Streaming vs Synchronous Comparison")
print("=" * 80)
test_prompt = "Explain the benefits of streaming in three sentences."
print(f"\nPrompt: {test_prompt}")
print("\nComparing streaming vs synchronous generation...")
agent.events = [] # Reset events
comparison = agent.compare_streaming_vs_sync(test_prompt)
print("\n" + "-" * 80)
print("RESULTS:")
print("-" * 80)
print("\nStreaming Mode:")
print(f" Duration: {comparison['streaming']['duration']:.3f}s")
print(f" Content Length: {comparison['streaming']['content_length']} chars")
print(f" Tokens: {comparison['streaming']['tokens']}")
print(f" Time to First Token: ~{comparison['streaming']['time_to_first_token']:.3f}s")
print("\nSynchronous Mode:")
print(f" Duration: {comparison['synchronous']['duration']:.3f}s")
print(f" Content Length: {comparison['synchronous']['content_length']} chars")
print(f" Time to First Token: {comparison['synchronous']['time_to_first_token']:.3f}s")
print("\nKey Insight:")
print(" ✓ Streaming provides immediate feedback (TTFT)")
print(" ✓ Better perceived performance and user experience")
print(" ✓ Enables progressive rendering and cancellation")
# Summary
print("\n" + "=" * 80)
print("SUMMARY")
print("=" * 80)
summary = """
The Streaming Agent demonstrates real-time response generation:
KEY CAPABILITIES:
1. Token Streaming: Stream individual tokens as generated
2. Chunk Streaming: Stream semantic chunks for better UX
3. Progress Tracking: Monitor generation progress with callbacks
4. Event Streaming: Rich events with metadata and timestamps
5. Async Streaming: Non-blocking async/await patterns
6. Chain Streaming: Stream output from complex chains
7. Error Recovery: Graceful handling of streaming errors
8. Comparison: Measure streaming vs synchronous performance
BENEFITS:
- Immediate user feedback (low TTFT)
- Better perceived performance
- Progressive content rendering
- Cancellation support
- Reduced perceived latency
- Enhanced user experience
- Real-time interactivity
- Efficient resource usage
USE CASES:
- Conversational chatbots with typing indicators
- Long-form content generation (articles, reports)
- Real-time translation services
- Live code generation and explanation
- Interactive storytelling
- Streaming search results
- Progressive document analysis
- Collaborative writing tools
PRODUCTION CONSIDERATIONS:
1. Backpressure: Handle slow consumers gracefully
2. Buffer Management: Prevent memory issues with large streams
3. Error Recovery: Implement retry logic for network issues
4. Cancellation: Support user-initiated cancellation
5. Rate Limiting: Prevent excessive streaming costs
6. Monitoring: Track streaming performance metrics
7. WebSocket: Use WebSocket for web clients
8. State Management: Handle connection drops and reconnects
9. Testing: Test with various network conditions
10. Optimization: Minimize latency for first token
ADVANCED EXTENSIONS:
- Multi-model streaming (ensemble outputs)
- Streaming with tool calls
- Real-time translation during streaming
- Adaptive chunk sizing based on content
- Client-side buffering strategies
- Stream compression for bandwidth
- Priority-based streaming
- Streaming with citations and sources
- Live annotation and formatting
- Collaborative streaming sessions
Streaming is essential for modern AI applications requiring responsive,
interactive user experiences with immediate feedback.
"""
print(summary)
if __name__ == "__main__":
demonstrate_streaming_agent()
Agentic Design Pattern: Streaming Agent
Pattern 078: Streaming Agent – Line-by-Line Explanation
Overview
This document provides a detailed line-by-line explanation of the Streaming Agent pattern implementation.
Pattern Description
Pattern 078: Streaming Agent
Description: A Streaming Agent delivers responses in real-time as they are generated, rather than waiting for complete output. This pattern is essential for building responsive user interfaces and handling long-running generation tasks. It provides immediate feedback to users and enables progressive rendering of results.
The agent streams tokens as they are generated by the LLM, allowing for better
user experience in conversational interfaces, content generation, and real-time
data processing. It supports multiple streaming modes including token-by-token,
chunk-by-chunk, and structured streaming with metadata.
Components: 1. Token Streamer: Streams individual tokens as generated 2. Chunk Streamer: Streams semantic chunks (sentences, paragraphs) 3. Event Streamer: Streams events with metadata and progress 4. Progress Tracker: Monitors generation progress 5. Buffer Manager: Manages streaming buffers and backpressure 6. Error Handler: Handles streaming errors gracefully 7. Aggregator: Collects streamed content for final result 8. Rate Controller: Controls streaming rate
Key Features: – Real-time token streaming – Chunk-based streaming – Progress callbacks – Cancellation support – Error recovery during streaming – Multiple output formats – Backpressure handling – Stream aggregation – Event-driven architecture – WebSocket support
Use Cases: – Conversational chatbots with typing indicators – Long-form content generation – Real-time translation services – Live code generation and explanation – Progressive document analysis – Interactive storytelling – Streaming search results – Real-time data processing – Live transcription and summarization – Collaborative writing tools
LangChain Implementation: Uses ChatOpenAI with streaming=True, callbacks for progress tracking, and LCEL chains with streaming support.
File Statistics
- Total Lines: 810
- Classes: 7
- Functions: 1
- Constants: 0
Module Documentation
"""
Pattern 078: Streaming Agent
Description:
A Streaming Agent delivers responses in real-time as they are generated, rather
than waiting for complete output. This pattern is essential for building responsive
user interfaces and handling long-running generation tasks. It provides immediate
feedback to users and enables progressive rendering of results.
The agent streams tokens as they are generated by the LLM, allowing for better
user experience in conversational interfaces, content generation, and real-time
data processing. It supports multiple streaming modes including token-by-token,
chunk-by-chunk, and structured streaming with metadata.
Components:
1. Token Streamer: Streams individual tokens as generated
2. Chunk Streamer: Streams semantic chunks (sentences, paragraphs)
3. Event Streamer: Streams events with metadata and progress
4. Progress Tracker: Monitors generation progress
5. Buffer Manager: Manages streaming buffers and backpressure
6. Error Handler: Handles streaming errors gracefully
7. Aggregator: Collects streamed content for final result
8. Rate Controller: Controls streaming rate
Key Features:
- Real-time token streaming
- Chunk-based streaming
- Progress callbacks
- Cancellation support
- Error recovery during streaming
- Multiple output formats
- Backpressure handling
- Stream aggregation
- Event-driven architecture
- WebSocket support
Use Cases:
- Conversational chatbots with typing indicators
- Long-form content generation
- Real-time translation services
- Live code generation and explanation
- Progressive document analysis
- Interactive storytelling
- Streaming search results
- Real-time data processing
- Live transcription and summarization
- Collaborative writing tools
LangChain Implementation:
Uses ChatOpenAI with streaming=True, callbacks for progress tracking,
and LCEL chains with streaming support.
"""
Purpose: This module implements the Streaming Agent pattern, providing a structured approach to agent design and implementation.
Import Statements
Standard Library Imports
import asyncio
import collections.deque
import dataclasses.dataclass
import dataclasses.field
import datetime.datetime
import enum.Enum
import langchain_core.callbacks.BaseCallbackHandler
import langchain_core.output_parsers.StrOutputParser
import langchain_core.prompts.ChatPromptTemplate
import os
import time
import typing.Any
import typing.AsyncIterator
import typing.Callable
import typing.Dict
import typing.Iterator
import typing.List
import typing.Optional
Purpose: Core Python functionality:
– asyncio: Asynchronous I/O operations
– collections.deque: Specialized container datatypes
– dataclasses.dataclass: Simplified class definitions with @dataclass
– dataclasses.field: Simplified class definitions with @dataclass
– datetime.datetime: Date and time handling
– enum.Enum: Enumeration support
– langchain_core.callbacks.BaseCallbackHandler: Regular expression operations
– langchain_core.output_parsers.StrOutputParser: Regular expression operations
– langchain_core.prompts.ChatPromptTemplate: Regular expression operations
– os: Environment variable access and system operations
– time: Time-related functions
– typing.Any: Type hints for better code documentation (List, Dict, Any, Optional)
– typing.AsyncIterator: Type hints for better code documentation (List, Dict, Any, Optional)
– typing.Callable: Type hints for better code documentation (List, Dict, Any, Optional)
– typing.Dict: Type hints for better code documentation (List, Dict, Any, Optional)
– typing.Iterator: Type hints for better code documentation (List, Dict, Any, Optional)
– typing.List: Type hints for better code documentation (List, Dict, Any, Optional)
– typing.Optional: Type hints for better code documentation (List, Dict, Any, Optional)
LangChain Imports
from langchain_openai.ChatOpenAI
Purpose: LangChain framework components: – LLM Interface: Wrapper for OpenAI models – Chains: Composable building blocks for complex workflows
Other Imports
from dotenv.load_dotenv
Purpose: Additional dependencies for specialized functionality.
Classes
Class: StreamMode
Lines 72-78
Inherits from: Enum
Purpose:
Streaming modes
Class: StreamStatus
Lines 81-88
Inherits from: Enum
Purpose:
Stream status
Class: StreamEvent
Lines 92-99
Purpose:
Event in the stream
Class: StreamConfig
Lines 103-111
Purpose:
Configuration for streaming
Class: StreamResult
Lines 115-122
Purpose:
Result of streaming operation
Class: StreamingCallbackHandler
Lines 125-148
Inherits from: BaseCallbackHandler
Purpose:
Callback handler for streaming events
Methods:
__init__(self, on_token, on_chunk)
Lines 128-136
Purpose:
Initialize callback handler
Parameters:
– on_token: On token
– on_chunk: On chunk
on_llm_new_token(self, token)
Lines 138-142
Purpose:
Called when new token is generated
Parameters:
– token: Token
Returns: None
on_llm_end(self, response)
Lines 144-148
Purpose:
Called when generation ends
Parameters:
– response: Response
Returns: None
Class: StreamingAgent
Lines 151-579
Purpose:
Agent that streams responses in real-time.
This agent provides various streaming capabilities including token streaming,
chunk streaming, and event streaming with progress tracking.
Methods:
__init__(self, config)
Lines 159-176
Purpose:
Initialize the streaming agent
Parameters:
– config: Config
stream_tokens(self, prompt, on_token)
Lines 178-243
Purpose:
Stream tokens as they are generated.
Args:
prompt: Input prompt
on_token: Callback for each token
Returns:
StreamResult with full content and events
Parameters:
– prompt: Prompt template or text
– on_token: On token
Returns: StreamResult
stream_chunks(self, prompt, chunk_size, on_chunk)
Lines 245-326
Purpose:
Stream content in chunks.
Args:
prompt: Input prompt
chunk_size: Size of chunks in characters
on_chunk: Callback for each chunk
Returns:
StreamResult with full content and events
Parameters:
– prompt: Prompt template or text
– chunk_size: Chunk size
– on_chunk: On chunk
Returns: StreamResult
stream_with_progress(self, prompt, estimated_tokens, on_progress)
Lines 328-410
Purpose:
Stream with progress tracking.
Args:
prompt: Input prompt
estimated_tokens: Estimated total tokens for progress
on_progress: Callback with progress (0.0-1.0) and content
Returns:
StreamResult with full content and progress events
Parameters:
– prompt: Prompt template or text
– estimated_tokens: Estimated tokens
– on_progress: On progress
Returns: StreamResult
stream_chain(self, inputs, on_chunk)
Lines 475-535
Purpose:
Stream output from a chain.
Args:
inputs: Chain inputs
on_chunk: Callback for each chunk
Returns:
StreamResult with full content
Parameters:
– inputs: Input data
– on_chunk: On chunk
Returns: StreamResult
compare_streaming_vs_sync(self, prompt)
Lines 537-579
Purpose:
Compare streaming vs synchronous generation.
Args:
prompt: Input prompt
Returns:
Comparison results
Parameters:
– prompt: Prompt template or text
Returns: <ast.Subscript object at 0x000001A06D63BF10>
Functions
demonstrate_streaming_agent()
Lines 582-805
Purpose:
Demonstrate the streaming agent capabilities
Key Concepts Summary
Pattern Overview
The Streaming Agent pattern provides a structured approach to building AI agents with specific capabilities and behaviors. This implementation leverages LangChain’s composable components to create a robust and maintainable solution.
Core Components
- Agent Class: Main implementation of the pattern logic
- Prompt Engineering: Carefully crafted prompts to guide LLM behavior
- Tool Integration: Optional tools for extended functionality
- Memory Management: State handling across interactions
- Output Parsing: Structured response processing
When to Use
✅ Good for: – Scenarios requiring this specific pattern’s strengths – Applications needing structured agent behavior – Systems where explainability is important – Production environments requiring reliability
❌ Not ideal for: – Simple single-prompt tasks – Scenarios requiring different pattern characteristics – Resource-constrained environments (if computationally intensive)
Best Practices Demonstrated
1. Environment Configuration
- ✅ Use
.envfiles for API keys - ✅ Never hardcode credentials
- ✅ Validate environment variables on startup
2. Error Handling
- ✅ Graceful degradation on failures
- ✅ Informative error messages
- ✅ Logging for debugging
3. Prompt Engineering
- ✅ Clear, specific instructions
- ✅ Structured output formats
- ✅ Few-shot examples when beneficial
4. Code Organization
- ✅ Separation of concerns (class-based design)
- ✅ Type hints for clarity
- ✅ Docstrings for documentation
5. Performance Optimization
- ✅ Appropriate temperature settings
- ✅ Token budget management
- ✅ Caching where applicable
LangChain Components Used
- ChatOpenAI: OpenAI model interface
- Chains: Sequential component composition
Why LangChain? – Composable abstractions for LLM applications – Rich ecosystem of integrations – Production-ready patterns – Active community and development
Execution Flow
1. Initialize agent with configuration
↓
2. Load environment and dependencies
↓
3. Prepare prompt with input data
↓
4. Invoke LLM through LangChain
↓
5. Parse and validate response
↓
6. Return formatted result
Key Decision Points: – Model selection (temperature, model type) – Prompt structure (few-shot vs zero-shot) – Error handling strategy – Output format validation
Performance Considerations
Computational Cost
- LLM Calls: Primary cost factor (based on tokens)
- Latency: Depends on model and input size
- Memory: Minimal for most patterns
Optimization Strategies
- Prompt Optimization: Minimize tokens while maintaining clarity
- Caching: Cache repeated queries/responses
- Model Selection: Use smaller models when appropriate
- Batch Processing: Group similar requests
- Streaming: For long responses, stream tokens
Cost Estimates (Approximate)
- GPT-3.5-turbo: ~$0.002 per request
- GPT-4: ~$0.03 per request
- GPT-4-turbo: ~$0.01 per request
Actual costs vary based on input/output token counts
Common Pitfalls to Avoid
1. Prompt Design Issues
❌ Vague or ambiguous instructions
✅ Clear, specific, testable prompts
2. Error Handling
❌ Ignoring API errors or rate limits
✅ Implement retry logic and graceful degradation
3. Token Management
❌ Exceeding model token limits
✅ Truncate inputs, chunk processing
4. Security
❌ Exposing API keys in code
✅ Use environment variables
5. Testing
❌ Only testing happy paths
✅ Test edge cases, failures, malformed inputs
6. Cost Management
❌ Unmonitored API usage
✅ Implement budgets, alerts, and monitoring
Further Improvements
Production Enhancements
- Monitoring: Add logging, metrics, tracing
- Validation: Input/output schema validation
- Rate Limiting: Implement request throttling
- Caching: Redis or in-memory cache for responses
- Async Support: Non-blocking operations for scalability
Feature Extensions
- Multi-Model Support: Switch between providers
- Fallback Models: Graceful degradation strategy
- Custom Tools: Domain-specific function calling
- Advanced Memory: Vector stores for long-term memory
- Evaluation: Automated testing and benchmarking
Code Quality
- Testing: Unit tests, integration tests
- Documentation: API docs, usage examples
- Type Safety: Stricter type hints
- Configuration: Externalized config files
Related Patterns
- Pattern 077
- Pattern 079
Pattern Families: – Reasoning Patterns (001-011) – Multi-Agent Patterns (012-019) – Tool Use Patterns (020-025) – Memory Patterns (026-031) – And many more…
Summary
The Streaming Agent pattern provides a powerful approach to building AI agents with specific capabilities. This implementation demonstrates:
✅ Key Strengths: – Clean, maintainable code structure – LangChain integration for composability – Type hints and documentation – Production-ready patterns
🎯 Best Use Cases: – Applications requiring this pattern’s characteristics – Systems needing structured agent behavior – Production environments requiring reliability
📚 Learning Resources: – LangChain Documentation: https://python.langchain.com/ – Pattern Documentation: See related patterns – OpenAI API Reference: https://platform.openai.com/docs/
File: 078_streaming_agent.py
Total Lines: 810
Pattern Category: AI Agent Design Pattern #078
Generated from actual implementation code
For educational and reference purposes