Skip to content

Commit ae163fe

Browse files
committed
docs: custom output extraction
1 parent 5c7c678 commit ae163fe

File tree

1 file changed

+27
-0
lines changed

1 file changed

+27
-0
lines changed

docs/tools.md

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -284,6 +284,33 @@ async def run_my_agent() -> str:
284284
return str(result.final_output)
285285
```
286286

287+
### Custom output extraction
288+
289+
In certain cases, you might want to modify the output of the tool-agents before returning it to the central agent. This may be useful if you want to:
290+
291+
- Extract a specific piece of information (e.g., a JSON payload) from the sub-agent's chat history.
292+
- Convert or reformat the agent’s final answer (e.g., transform Markdown into plain text or CSV).
293+
- Validate the output or provide a fallback value when the agent’s response is missing or malformed.
294+
295+
You can do this by supplying the `custom_output_extractor` argument to the `as_tool` method:
296+
297+
```python
298+
async def extract_json_payload(run_result: RunResult) -> str:
299+
# Scan the agent’s outputs in reverse order until we find a JSON-like message from a tool call.
300+
for item in reversed(run_result.new_items):
301+
if isinstance(item, ToolCallOutputItem) and item.output.strip().startswith("{"):
302+
return item.output.strip()
303+
# Fallback to an empty JSON object if nothing was found
304+
return "{}"
305+
306+
307+
json_tool = data_agent.as_tool(
308+
tool_name="get_data_json",
309+
tool_description="Run the data agent and return only its JSON payload",
310+
custom_output_extractor=extract_json_payload,
311+
)
312+
```
313+
287314
## Handling errors in function tools
288315

289316
When you create a function tool via `@function_tool`, you can pass a `failure_error_function`. This is a function that provides an error response to the LLM in case the tool call crashes.

0 commit comments

Comments
 (0)