dspy.streamify
dspy.streamify(program: Module, status_message_provider: Optional[StatusMessageProvider] = None) -> Callable[[Any, Any], Awaitable[Any]]
Wrap a DSPy program so that it streams its outputs incrementally, rather than returning them all at once. It also provides status messages to the user to indicate the progress of the program, and users can implement their own status message provider to customize the status messages and what module to generate status messages for.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
program
|
Module
|
The DSPy program to wrap with streaming functionality. |
required |
status_message_provider
|
Optional[StatusMessageProvider]
|
A custom status message generator to use instead of the default one. Users can implement their own status message generator to customize the status messages and what module to generate status messages for. |
None
|
Returns:
Type | Description |
---|---|
Callable[[Any, Any], Awaitable[Any]]
|
A function that takes the same arguments as the original program, but returns an async generator that yields the program's outputs incrementally. |
Example:
import asyncio
import dspy
# Create the program and wrap it with streaming functionality
program = dspy.streamify(dspy.Predict("q->a"))
# Use the program with streaming output
async def use_streaming():
output = program(q="Why did a chicken cross the kitchen?")
return_value = None
async for value in output:
if isinstance(value, dspy.Prediction):
return_value = value
else:
print(value)
return return_value
output = asyncio.run(use_streaming())
print(output)
Example with custom status message provider:
import asyncio
import dspy
class MyStatusMessageProvider(StatusMessageProvider):
def module_start_status_message(self, instance, inputs):
return f"Predicting..."
def tool_end_status_message(self, outputs):
return f"Tool calling finished with output: {outputs}!"
# Create the program and wrap it with streaming functionality
program = dspy.streamify(dspy.Predict("q->a"), status_message_provider=MyStatusMessageProvider())
# Use the program with streaming output
async def use_streaming():
output = program(q="Why did a chicken cross the kitchen?")
return_value = None
async for value in output:
if isinstance(value, dspy.Prediction):
return_value = value
else:
print(value)
return return_value
output = asyncio.run(use_streaming())
print(output)
Source code in dspy/utils/streaming.py
188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 |
|