Streams LM output tokens from DSPy modules to frontends, APIs, or CLI using dspy.streamify and StreamListener. Useful for real-time chat UIs, SSE endpoints, and progressive responses.
Ships in dspy-api-skills. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description: Claude knows it exists.
SKILL.md joins the conversation and stays.
Read when SKILL.md points to them.
Guide the user through streaming DSPy module outputs token-by-token to frontends, APIs, or CLI interfaces using dspy.streamify() and StreamListener.
dspy.streamify() wraps any DSPy module and returns an async (or sync) generator that yields chunks as the LM produces tokens. StreamListener lets you target specific output fields. The stream yields three chunk types -- StreamResponse (partial tokens), StatusMessage (progress updates), and Prediction (final result).
| Stream when... | Do NOT stream when... |
|---|---|
| Building a chat UI that shows typing | Batch processing many inputs |
| SSE/WebSocket endpoint for real-time display | Running optimization or evaluation |
| Long-form generation where users wait | Output is short (< 50 tokens) |
| ReAct agent loop where you show each step | Pipeline stages that feed into each other |
import dspy
from dspy.streaming import streamify, StreamListener
lm = dspy.LM("openai/gpt-4o-mini") # or "anthropic/claude-sonnet-4-5-20250929", etc.
dspy.configure(lm=lm)
# Your existing module
qa = dspy.ChainOfThought("question -> answer")
# Create a listener for a specific output field
answer_listener = StreamListener(signature_field_name="answer")
# Wrap the module for streaming
streaming_qa = streamify(
qa,
stream_listeners=[answer_listener],
)
# Consume the async generator
async for chunk in streaming_qa(question="What is DSPy?"):
if hasattr(chunk, "answer"):
print(chunk.answer, end="", flush=True)
The stream yields three distinct types:
async for chunk in streaming_qa(question="..."):
if isinstance(chunk, dspy.streaming.StreamResponse):
# Partial tokens for a field -- the main content you display
print(chunk.answer, end="", flush=True)
elif isinstance(chunk, dspy.streaming.StatusMessage):
# Progress updates -- useful for UI status indicators
print(f"[Status: {chunk.message}]")
elif isinstance(chunk, dspy.Prediction):
# Final complete result -- same as non-streaming output
final_answer = chunk.answer
Key behavior:
StreamResponse chunks contain partial text for the field(s) you are listening toStatusMessage appears during tool calls, retries, or multi-step processingPrediction appears last (unless include_final_prediction_in_output_stream=False)Stream multiple output fields simultaneously:
class Summarize(dspy.Signature):
"""Summarize the document and extract key points."""
document: str = dspy.InputField()
summary: str = dspy.OutputField()
key_points: str = dspy.OutputField()
summarizer = dspy.Predict(Summarize)
# Listen to both fields
summary_listener = StreamListener(signature_field_name="summary")
points_listener = StreamListener(signature_field_name="key_points")
streaming_summarizer = streamify(
summarizer,
stream_listeners=[summary_listener, points_listener],
)
async for chunk in streaming_summarizer(document="..."):
if hasattr(chunk, "summary"):
# Tokens for the summary field
display_summary(chunk.summary)
elif hasattr(chunk, "key_points"):
# Tokens for the key_points field
display_points(chunk.key_points)
Note: Fields stream sequentially in declaration order. The LM generates summary fully before starting key_points.
For agents, use allow_reuse=True so the listener captures output across multiple reasoning iterations:
from dspy.streaming import StatusMessageProvider
agent = dspy.ReAct("question -> answer", tools=[search, lookup])
# allow_reuse=True is critical for agents -- the agent generates
# multiple "answer" attempts across iterations
answer_listener = StreamListener(
signature_field_name="answer",
allow_reuse=True,
)
# status_message_provider must be a StatusMessageProvider subclass
# INSTANCE that overrides status hooks -- not a lambda
class AgentStatus(StatusMessageProvider):
def tool_start_status_message(self, instance, inputs):
return f"Calling {instance.name}..."
streaming_agent = streamify(
agent,
stream_listeners=[answer_listener],
status_message_provider=AgentStatus(),
)
async for chunk in streaming_agent(question="..."):
if isinstance(chunk, dspy.streaming.StatusMessage):
show_progress(chunk.message)
elif hasattr(chunk, "answer"):
show_answer_token(chunk.answer)
When a module has multiple predictors with the same output field name, use predict_name to target a specific one:
class Pipeline(dspy.Module):
def __init__(self):
self.draft = dspy.ChainOfThought("topic -> answer")
self.refine = dspy.ChainOfThought("draft_answer -> answer")
def forward(self, topic):
draft = self.draft(topic=topic)
return self.refine(draft_answer=draft.answer)
pipeline = Pipeline()
# Only stream the final refinement step, not the draft
final_listener = StreamListener(
signature_field_name="answer",
predict_name="refine", # matches self.refine attribute name
)
streaming_pipeline = streamify(pipeline, stream_listeners=[final_listener])
from fastapi import FastAPI
from fastapi.responses import StreamingResponse
import dspy
from dspy.streaming import streamify, StreamListener
app = FastAPI()
qa = dspy.ChainOfThought("question -> answer")
answer_listener = StreamListener(signature_field_name="answer")
streaming_qa = streamify(qa, stream_listeners=[answer_listener])
@app.get("/ask")
async def ask(question: str):
async def event_stream():
async for chunk in streaming_qa(question=question):
if hasattr(chunk, "answer"):
yield f"data: {chunk.answer}\n\n"
elif isinstance(chunk, dspy.Prediction):
yield f"data: [DONE]\n\n"
return StreamingResponse(event_stream(), media_type="text/event-stream")
For non-async contexts (scripts, notebooks), set async_streaming=False:
streaming_qa = streamify(
qa,
stream_listeners=[answer_listener],
async_streaming=False, # Returns a sync generator
)
# Use regular for loop instead of async for
for chunk in streaming_qa(question="What is DSPy?"):
if hasattr(chunk, "answer"):
print(chunk.answer, end="", flush=True)
async_streaming=False in non-async code. If you use a regular for loop with an async generator, you get TypeError: 'async_generator' object is not iterable. Always set async_streaming=False for sync contexts.[[ ## field_name ## ]]) before it can emit tokens. First chunk arrives slightly delayed.allow_reuse=True for agents. Without it, StreamListener only captures the first iteration. ReAct and CodeAct agents need allow_reuse=True to stream across multiple reasoning cycles.include_final_prediction_in_output_stream=True is the default. The last item in the stream is always a Prediction object unless you explicitly disable it. Check for both StreamResponse and Prediction types.streamify() already returns a callable that produces a generator. Do not wrap it in another async function -- just call it directly and iterate.Install any skill:
npx skills add lebsral/DSPy-Programming-not-prompting-LMs-skills --skill <name>
/ai-serving-apis/ai-building-chatbots/dspy-react/dspy-async/dspy-utils/ai-do if you do not have it -- it routes any AI problem to the right skill and is the fastest way to work: npx skills add lebsral/DSPy-Programming-not-prompting-LMs-skills --skill ai-doWhat SKILL.md sets; muted values are Claude Code's defaults
Three short reads, in order
dspy-streaming, real-time, server-sent-events, websocket, streaming
/dspy-api-skills:dspy-streamingfrom dspy-api-skills
npx claudepluginhub lebsral/dspy-programming-not-prompting-lms-skills --plugin dspy-api-skills39 skills in this plugin
/dspy-adaptersUse when you need to customize how DSPy formats prompts for a specific provider — switching from chat to completion format, forcing JSON output, or debugging prompt rendering issues. Common scenarios - debugging why your prompt looks wrong when sent to the model, switching from OpenAI to Anthropic and the formatting breaks, forcing the model to return valid JSON instead of markdown, working with completion-style models that do not support chat format, customizing system messages, or handling models that choke on structured output instructions. Related - ai-switching-models, ai-following-rules, ai-parsing-data. Also used for prompt template rendering, how DSPy builds the prompt, custom system message in DSPy, JSON mode not working, model ignores format instructions, switch from chat to completion API, dspy.ChatAdapter, dspy.JSONAdapter, prompt formatting issues, debug what DSPy sends to the model, dspy.XMLAdapter, XML output format./dspy-assertionsLegacy reference for dspy.Assert and dspy.Suggest, both removed in DSPy 3.x - use dspy.Refine or dspy.BestOfN instead. Use when maintaining a legacy DSPy 2.x codebase that uses dspy.Assert or dspy.Suggest, or migrating from Assert/Suggest to DSPy 3.x. Also used for dspy.Assert, dspy.Suggest, runtime validation for LLM output, retry on bad output, backtracking on constraint violation, guard rails in DSPy, migrate from Assert, migrate from Suggest, ImportError cannot import Assert, ImportError cannot import Suggest./dspy-asyncUse when you need to run DSPy modules asynchronously — FastAPI endpoints, concurrent LM calls, non-blocking execution, or integrating DSPy into async web frameworks. Common scenarios - serving DSPy behind FastAPI or Starlette, running multiple LM calls concurrently with asyncio.gather, non-blocking batch processing, combining async with streaming, or building async agent loops. Related - ai-serving-apis, dspy-parallel, dspy-streaming, dspy-utils. Also used for aforward, acall, async DSPy, await dspy, FastAPI with DSPy async, concurrent DSPy calls, asyncio with DSPy, non-blocking DSPy, async batch processing, semaphore concurrency limit, asyncio.gather DSPy, async web framework DSPy, Starlette DSPy, aiohttp DSPy./dspy-best-of-nRuns any DSPy module N times and returns the highest-scoring output via a reward function using dspy.BestOfN. Use when output quality varies across runs and you want to sample multiple completions and pick the best — trading latency for reliability on high-stakes outputs. Common scenarios - generating multiple candidate answers and picking the highest-scoring one, improving reliability on high-stakes classification, reducing variance in creative generation, getting better summaries by sampling several and selecting the best, or trading latency for quality on critical decisions. Related - ai-improving-accuracy, ai-making-consistent, dspy-refine. Also used for sample multiple completions, pick the best of several LLM outputs, majority voting for LLM, self-consistency decoding, reduce LLM output variance, generate and select pattern, best candidate selection, how to make AI more reliable by trying multiple times, brute force better quality, retry and pick best, dspy.BestOfN, quality vs latency tradeoff, n=5 completions pick best./dspy-better-togetherJointly optimize prompts and model weights using dspy.BetterTogether for maximum accuracy. Use when you have already tried prompt-only optimization and want the next level — jointly tuning prompts and model weights for maximum quality. Common scenarios - you have maxed out prompt optimization and need the next level, combining instruction tuning with weight tuning for maximum quality, making a small model match a large model through joint optimization, or squeezing the last few percent of accuracy. Related - ai-fine-tuning, ai-improving-accuracy, ai-cutting-costs. Also used for dspy.BetterTogether, joint prompt and weight optimization, beyond prompt engineering, combine fine-tuning with prompt optimization, maximum possible quality from DSPy, hybrid optimization strategy, prompt optimization hit a ceiling, fine-tune and optimize prompts at the same time, advanced DSPy optimization, best possible accuracy, what to try after MIPROv2, next level AI quality./dspy-bootstrap-few-shotAutomatically generate and select few-shot demonstrations for a DSPy program from labeled data using dspy.BootstrapFewShot - the simplest and fastest optimizer. Use when you have 50+ labeled examples and want a quick accuracy boost as your first optimization step. Common scenarios - your first optimization attempt on a new DSPy program, adding few-shot examples automatically from labeled data, quick accuracy boost before trying heavier optimizers, bootstrapping demonstrations from a teacher model, or getting started with DSPy optimization. Related - ai-improving-accuracy, dspy-labeled-few-shot. Also used for dspy.BootstrapFewShot, simplest DSPy optimizer, first optimizer to try, automatic few-shot example selection, bootstrap demonstrations from labels, quick optimization baseline, add examples to prompt automatically, teacher bootstrapping, labeled data to few-shot demos, starting point for DSPy optimization, easy accuracy improvement, how to optimize DSPy program for the first time.Other plugins' skills for the same job