API Reference: Modules
udspy.module
Module package for composable LLM calls.
Classes
ChainOfThought
Bases: Module
Chain of Thought reasoning module.
Automatically adds a reasoning step before generating outputs. This encourages the LLM to think step-by-step, improving answer quality.
Example
class QA(Signature):
'''Answer questions.'''
question: str = InputField()
answer: str = OutputField()
# Creates predictor with automatic reasoning
predictor = ChainOfThought(QA)
result = predictor(question="What is 2+2?")
print(result.reasoning) # "Let's think step by step..."
print(result.answer) # "4"
Source code in src/udspy/module/chain_of_thought.py
14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 | |
Functions
__init__(signature, *, reasoning_description='Step-by-step reasoning process', tools=None, model=None, adapter=None, **kwargs)
Initialize a Chain of Thought module.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
signature
|
type[Signature] | str
|
Signature defining inputs and final outputs, or a string in format "inputs -> outputs" (e.g., "question -> answer") |
required |
reasoning_description
|
str
|
Description for the reasoning field |
'Step-by-step reasoning process'
|
model
|
str | None
|
Model name (overrides global default) |
None
|
tools
|
list[Tool] | None
|
List of Pydantic tool models |
None
|
adapter
|
ChatAdapter | None
|
Custom adapter |
None
|
**kwargs
|
Any
|
Additional arguments for chat completion (including callbacks) |
{}
|
Source code in src/udspy/module/chain_of_thought.py
aexecute(*, stream=False, **inputs)
async
Execute chain of thought prediction.
Delegates to the wrapped Predict module's aexecute method, which will automatically emit streaming events if a queue is active.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
stream
|
bool
|
If True, request streaming from LLM provider |
False
|
**inputs
|
Any
|
Input values matching the signature's input fields |
{}
|
Returns:
| Type | Description |
|---|---|
Prediction
|
Prediction with reasoning and other output fields |
Source code in src/udspy/module/chain_of_thought.py
init_module(tools=None)
Initialize or reinitialize ChainOfThought with new tools.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
tools
|
list[Any] | None
|
New tools to initialize with |
None
|
Source code in src/udspy/module/chain_of_thought.py
ConfirmationRequired
Bases: Exception
Raised when human input is needed to proceed.
This exception pauses execution and allows modules to save state for resumption. It can be raised by: - Tools decorated with @confirm_first - Modules that need user input (e.g., ask_to_user) - Custom code requiring human interaction
Attributes:
| Name | Type | Description |
|---|---|---|
question |
The question being asked to the user |
|
confirmation_id |
Unique ID for this confirmation request |
|
tool_call |
Optional ToolCall information if raised by a tool |
|
context |
General-purpose context dictionary for module state |
Source code in src/udspy/confirmation.py
Functions
__init__(question, *, confirmation_id=None, tool_call=None, context=None)
Initialize ConfirmationRequired exception.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
question
|
str
|
Question to ask the user |
required |
confirmation_id
|
str | None
|
Unique ID for this confirmation (auto-generated if not provided) |
None
|
tool_call
|
Optional[ToolCall]
|
Optional tool call information |
None
|
context
|
dict[str, Any] | None
|
Optional context dictionary for module-specific state |
None
|
Source code in src/udspy/confirmation.py
Module
Base class for all udspy modules.
Modules are composable async-first units. The core method is aexecute()
which handles both streaming and non-streaming execution. Public methods
astream() and aforward() are thin wrappers around aexecute().
Subclasses should implement aexecute() to define their behavior.
Example
# Async streaming (real-time)
async for event in module.astream(question="What is AI?"):
if isinstance(event, OutputStreamChunk):
print(event.delta, end="", flush=True)
elif isinstance(event, Prediction):
result = event
# Async non-streaming
result = await module.aforward(question="What is AI?")
# Sync (for scripts, notebooks)
result = module(question="What is AI?")
result = module.forward(question="What is AI?")
Source code in src/udspy/module/base.py
15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 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 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 | |
Functions
__call__(*, resume_state=None, history=None, **inputs)
Sync convenience method. Calls forward().
Supports resuming from a ConfirmationRequired exception by providing resume_state. This enables loop-based confirmation handling.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
resume_state
|
Any
|
Optional ResumeState containing exception and user response. Can also be a raw ConfirmationRequired exception (will use "yes" as response). |
None
|
history
|
History | None
|
Optional History object for maintaining conversation state. |
None
|
**inputs
|
Any
|
Input values for the module |
{}
|
Returns:
| Type | Description |
|---|---|
Prediction
|
Final Prediction object |
Example
from udspy import ResumeState
# Loop-based confirmation handling
resume_state = None
while True:
try:
result = agent(
question="Delete files",
resume_state=resume_state
)
break
except ConfirmationRequired as e:
user_response = input(f"{e.question} (yes/no): ")
resume_state = ResumeState(e, user_response)
Source code in src/udspy/module/base.py
aexecute(*, stream=False, history=None, **inputs)
async
Core execution method. Must be implemented by subclasses.
This is the single implementation point for both streaming and non-streaming execution. It always returns a Prediction, and optionally emits StreamEvent objects to the active queue (if one exists in the context).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
stream
|
bool
|
If True, request streaming from LLM provider. If False, use non-streaming API calls. |
False
|
history
|
History | None
|
Optional History object for maintaining conversation state |
None
|
**inputs
|
Any
|
Input values for the module |
{}
|
Returns:
| Type | Description |
|---|---|
Prediction
|
Final Prediction object |
Behavior
- Checks for active stream queue via _stream_queue.get()
- If queue exists: emits OutputStreamChunk and Prediction events
- Always returns final Prediction (even in streaming mode)
- This enables composability: nested modules emit events automatically
Raises:
| Type | Description |
|---|---|
NotImplementedError
|
If not implemented by subclass |
Source code in src/udspy/module/base.py
aforward(*, resume_state=None, history=None, **inputs)
async
Async non-streaming method. Returns final result directly.
This method calls aexecute() with streaming disabled. If called from within a streaming context (i.e., another module is streaming), events will still be emitted to the active queue.
Supports resuming from a ConfirmationRequired exception by providing resume_state. This enables loop-based confirmation handling.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
resume_state
|
Any
|
Optional ResumeState containing exception and user response. Can also be a raw ConfirmationRequired exception (will use "yes" as response). |
None
|
history
|
History | None
|
Optional History object for maintaining conversation state. |
None
|
**inputs
|
Any
|
Input values for the module |
{}
|
Returns:
| Type | Description |
|---|---|
Prediction
|
Final Prediction object |
Example
from udspy import ResumeState
# Loop-based confirmation handling
resume_state = None
while True:
try:
result = await agent.aforward(
question="Delete files",
resume_state=resume_state
)
break
except ConfirmationRequired as e:
user_response = input(f"{e.question} (yes/no): ")
resume_state = ResumeState(e, user_response)
Source code in src/udspy/module/base.py
aresume(user_response, saved_state)
async
Async resume execution after user input.
Called to resume execution after a ConfirmationRequired exception. Subclasses must override to implement resumption logic.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
user_response
|
str
|
The user's response. Can be: - "yes"/"y" to approve the action - "no"/"n" to reject the action - "feedback" to provide feedback for LLM re-reasoning - JSON string with "edit" to modify tool arguments |
required |
saved_state
|
Any
|
State returned from asuspend() |
required |
Returns:
| Type | Description |
|---|---|
Prediction
|
Final Prediction object |
Raises:
| Type | Description |
|---|---|
NotImplementedError
|
If not implemented by subclass |
Source code in src/udspy/module/base.py
astream(*, resume_state=None, history=None, **inputs)
async
Async streaming method. Sets up queue and yields events.
This method sets up the stream queue context, calls aexecute() with streaming enabled, and yields all events from the queue.
Supports resuming from a ConfirmationRequired exception by providing resume_state. This enables streaming with confirmation handling.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
resume_state
|
Any
|
Optional ResumeState containing exception and user response. Can also be a raw ConfirmationRequired exception (will use "yes" as response). |
None
|
history
|
History | None
|
Optional History object for maintaining conversation state. |
None
|
**inputs
|
Any
|
Input values for the module |
{}
|
Yields:
| Type | Description |
|---|---|
AsyncGenerator[StreamEvent]
|
StreamEvent objects (OutputStreamChunk, Prediction, and custom events) |
Source code in src/udspy/module/base.py
asuspend(exception)
async
Async suspend execution and save state.
Called when ConfirmationRequired is raised. Subclasses should override to save any module-specific state needed for resumption.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
exception
|
ConfirmationRequired
|
The ConfirmationRequired exception that was raised |
required |
Returns:
| Type | Description |
|---|---|
Any
|
Saved state (can be any type, will be passed to aresume) |
Source code in src/udspy/module/base.py
forward(*, resume_state=None, history=None, **inputs)
Sync non-streaming method. Wraps aforward() with async_to_sync.
This provides sync compatibility for scripts and notebooks. Cannot be called from within an async context (use aforward() instead).
Supports resuming from a ConfirmationRequired exception by providing resume_state. This enables loop-based confirmation handling.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
resume_state
|
Any
|
Optional ResumeState containing exception and user response. Can also be a raw ConfirmationRequired exception (will use "yes" as response). |
None
|
history
|
History | None
|
Optional History object for maintaining conversation state. |
None
|
**inputs
|
Any
|
Input values for the module (includes both input fields and any module-specific parameters like auto_execute_tools) |
{}
|
Returns:
| Type | Description |
|---|---|
Prediction
|
Final Prediction object |
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If called from within an async context |
Example
from udspy import ResumeState
# Loop-based confirmation handling
resume_state = None
while True:
try:
result = agent.forward(
question="Delete files",
resume_state=resume_state
)
break
except ConfirmationRequired as e:
user_response = input(f"{e.question} (yes/no): ")
resume_state = ResumeState(e, user_response)
Source code in src/udspy/module/base.py
init_module(tools=None)
abstractmethod
Initialize or reinitialize the module with new tools.
This method provides a way to completely reinitialize module state, including tools, tool schemas, and signatures. It's designed to be called from module callbacks that need to dynamically modify the module during execution.
When implementing this method, subclasses should: 1. Rebuild the tools dictionary 2. Regenerate tool schemas (if applicable) 3. Rebuild signatures with new tool descriptions (if applicable) 4. Preserve built-in tools (if applicable)
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
tools
|
list[Callable[..., Any]] | None
|
New tools to initialize with. Format depends on subclass: - Can be functions (will be wrapped in Tool) - Can be Tool instances - None means clear all non-built-in tools |
None
|
Example
from udspy import module_callback
@module_callback
def add_tools(context):
# Get current tools
current = list(context.module.tools.values())
# Add new tools
new_tools = [weather_tool, calendar_tool]
# Reinitialize module with all tools
context.module.init_module(tools=current + new_tools)
return "Added weather and calendar tools"
Note
This method is typically called from within a module callback decorated with @module_callback. The callback receives a context object with access to the module instance.
Source code in src/udspy/module/base.py
resume(user_response, saved_state)
Sync resume execution after user input.
Wraps aresume() with async_to_sync.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
user_response
|
str
|
The user's response |
required |
saved_state
|
Any
|
State returned from suspend() |
required |
Returns:
| Type | Description |
|---|---|
Prediction
|
Final Prediction object |
Source code in src/udspy/module/base.py
suspend(exception)
Sync suspend execution and save state.
Wraps asuspend() with async_to_sync.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
exception
|
ConfirmationRequired
|
The ConfirmationRequired exception that was raised |
required |
Returns:
| Type | Description |
|---|---|
Any
|
Saved state (can be any type, will be passed to resume) |
Source code in src/udspy/module/base.py
Predict
Bases: Module
Module for making LLM predictions based on a signature.
This is an async-first module. The core method is astream() which yields
StreamEvent objects. Use aforward() for async non-streaming, or forward()
for sync usage.
Example
from udspy import Predict, Signature, InputField, OutputField
class QA(Signature):
'''Answer questions.'''
question: str = InputField()
answer: str = OutputField()
predictor = Predict(QA)
# Sync usage
result = predictor(question="What is 2+2?")
print(result.answer)
# Async non-streaming
result = await predictor.aforward(question="What is 2+2?")
# Async streaming
from udspy.streaming import OutputStreamChunk
async for event in predictor.astream(question="What is 2+2?"):
if isinstance(event, OutputStreamChunk):
print(event.delta, end="", flush=True)
Source code in src/udspy/module/predict.py
30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 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 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 | |
Attributes
model
property
Get the model name override, or None to use LM's default.
Functions
__init__(signature, *, tools=None, max_turns=10, adapter=None, model=None, **kwargs)
Initialize a Predict module.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
signature
|
type[Signature] | str
|
Signature defining inputs and outputs, or a string in format "inputs -> outputs" (e.g., "question -> answer") |
required |
model
|
str | None
|
Model name (overrides global default) |
None
|
tools
|
list[Tool] | None
|
List of tool functions (decorated with @tool) or Pydantic models |
None
|
max_turns
|
int
|
Maximum number of LLM calls for tool execution loop (default: 10) |
10
|
adapter
|
ChatAdapter | None
|
Custom adapter (defaults to ChatAdapter) |
None
|
**kwargs
|
Any
|
Additional arguments for chat completion (temperature, callbacks, etc.) |
{}
|
Source code in src/udspy/module/predict.py
aexecute(*, stream=False, auto_execute_tools=True, history=None, **inputs)
async
Core execution method - handles both streaming and non-streaming.
This is the single implementation point for LLM interaction. It always returns a Prediction, and emits events to the queue if one is active.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
stream
|
bool
|
If True, request streaming from OpenAI. If False, use regular API. |
False
|
auto_execute_tools
|
bool
|
If True, automatically execute tools and continue. If False, return Prediction with tool_calls for manual handling. |
True
|
history
|
History | None
|
Optional History object for multi-turn conversations. |
None
|
**inputs
|
Any
|
Input values matching the signature's input fields |
{}
|
Returns:
| Type | Description |
|---|---|
Prediction
|
Final Prediction object (after all tool executions if auto_execute_tools=True) |
Source code in src/udspy/module/predict.py
init_module(tools=None)
Initialize or reinitialize Predict with new tools.
This method rebuilds the tools dictionary and regenerates tool schemas. It's designed to be called from module callbacks to dynamically modify available tools during execution.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
tools
|
list[Any] | None
|
New tools to initialize with. Can be: - Functions decorated with @tool - Tool instances - None to clear all tools |
None
|
Example
from udspy import module_callback
@module_callback
def add_specialized_tools(context):
# Get current tools
current_tools = list(context.module.tools.values())
# Add new tools
new_tools = [weather_tool, calendar_tool]
# Reinitialize with all tools
context.module.init_module(tools=current_tools + new_tools)
return "Added weather and calendar tools"
Source code in src/udspy/module/predict.py
PredictContext
Bases: ModuleContext
Context for Predict module callbacks.
Provides access to both the module and the conversation history, allowing callbacks to inspect past interactions.
Attributes:
| Name | Type | Description |
|---|---|---|
module |
The Predict module instance |
|
history |
Conversation history (if provided) |
Source code in src/udspy/module/callbacks.py
Functions
__init__(module, history=None)
Initialize Predict context.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
module
|
Predict
|
The Predict module instance |
required |
history
|
Optional[History]
|
Conversation history (if any) |
None
|
Source code in src/udspy/module/callbacks.py
Prediction
Bases: StreamEvent, dict[str, Any]
Final prediction result with attribute access.
This is both a StreamEvent (can be yielded from astream) and a dict (for convenient attribute access to outputs).
Attributes:
| Name | Type | Description |
|---|---|---|
module |
The module that produced this prediction |
|
native_tool_calls |
Tool calls from native LLM response (if any) |
Example
Source code in src/udspy/streaming.py
Attributes
is_final
property
Whether this is the final prediction (no pending tool calls).
ReAct
Bases: Module
ReAct (Reasoning and Acting) module for tool-using agents.
ReAct iteratively reasons about the current situation and decides whether to call a tool or finish the task. Key features:
- Iterative reasoning with tool execution
- Tool confirmation support for sensitive operations
- Real-time streaming of reasoning and tool usage
Example (Basic Usage):
from udspy import ReAct, Signature, InputField, OutputField, tool
from pydantic import Field
@tool(name="search", description="Search for information")
def search(query: str = Field(...)) -> str:
return f"Results for: {query}"
class QA(Signature):
'''Answer questions using available tools.'''
question: str = InputField()
answer: str = OutputField()
react = ReAct(QA, tools=[search])
result = react(question="What is the weather in Tokyo?")
Example (Streaming):
# Stream the agent's reasoning process in real-time
async for event in react.astream(question="What is Python?"):
if isinstance(event, OutputStreamChunk):
print(event.delta, end="", flush=True)
elif isinstance(event, Prediction):
print(f"Answer: {event.answer}")
See examples/react_streaming.py for a complete streaming example.
Example (Tools with Confirmation):
from udspy import ConfirmationRequired, ConfirmationRejected
@tool(name="delete_file", require_confirmation=True)
def delete_file(path: str = Field(...)) -> str:
return f"Deleted {path}"
react = ReAct(QA, tools=[delete_file])
try:
result = await react.aforward(question="Delete /tmp/test.txt")
except ConfirmationRequired as e:
# User is asked for confirmation
print(f"Confirm: {e.question}")
# Approve: respond_to_confirmation(e.confirmation_id, approved=True)
# Reject: respond_to_confirmation(e.confirmation_id, approved=False, status="rejected")
result = await react.aresume("yes", e)
Source code in src/udspy/module/react.py
38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 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 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 | |
Functions
__init__(signature, tools, *, max_iters=10, **kwargs)
Initialize ReAct module.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
signature
|
type[Signature] | str
|
Signature defining inputs and outputs, or signature string |
required |
tools
|
list[Callable | Tool]
|
List of tool functions (decorated with @tool) or Tool objects |
required |
max_iters
|
int
|
Maximum number of reasoning iterations (default: 10) |
10
|
Source code in src/udspy/module/react.py
aexecute(*, stream=False, _trajectory=None, history=None, **input_args)
async
Execute ReAct loop.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
stream
|
bool
|
Passed to sub-modules |
False
|
_trajectory
|
list[Episode] | None
|
Internal - restored trajectory for resumption (list of completed episodes) |
None
|
history
|
History | None
|
History object for streaming (not used currently) |
None
|
**input_args
|
Any
|
Input values matching signature's input fields |
{}
|
Returns:
| Type | Description |
|---|---|
Prediction
|
Prediction with trajectory and output fields |
Raises:
| Type | Description |
|---|---|
ConfirmationRequired
|
When human input is needed |
Source code in src/udspy/module/react.py
381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 | |
init_module(tools=None)
Initialize or reinitialize ReAct with new tools.
This method rebuilds the tools dictionary and regenerates the react signature with new tool descriptions. Built-in tools are automatically preserved.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
tools
|
list[Any] | None
|
New tools to initialize with. Can be: - Functions decorated with @tool - Tool instances - None to clear all non-built-in tools |
None
|
Example
```python from udspy import module_callback
@module_callback def load_specialized_tools(context): # Get current non-built-in tools current_tools = [ t for t in context.module.tools.values() if t.name not in builtin_tool_names ]
# Add new tools
new_tools = [weather_tool, calendar_tool]
# Reinitialize with all tools
context.module.init_module(tools=current_tools + new_tools)
return f"Added {len(new_tools)} specialized tools"
```
Source code in src/udspy/module/react.py
Functions
is_module_callback(obj)
Check if an object is a module callback.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
obj
|
Any
|
Object to check |
required |
Returns:
| Type | Description |
|---|---|
bool
|
True if obj is a ModuleCallback instance |