-
Notifications
You must be signed in to change notification settings - Fork 2.8k
feat(sdk): add static structured output to subagent response #2437
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
Maahir Sachdev (maahir30)
wants to merge
5
commits into
main
Choose a base branch
from
structured-output-subagents
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+548
−13
Open
Changes from all commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change | ||||||
|---|---|---|---|---|---|---|---|---|
| @@ -1,11 +1,14 @@ | ||||||||
| """Middleware for providing subagents to an agent via a `task` tool.""" | ||||||||
|
|
||||||||
| import dataclasses | ||||||||
| import json | ||||||||
| from collections.abc import Awaitable, Callable, Sequence | ||||||||
| from typing import Any, NotRequired, TypedDict, cast | ||||||||
|
|
||||||||
| from langchain.agents import create_agent | ||||||||
| from langchain.agents.middleware import HumanInTheLoopMiddleware, InterruptOnConfig | ||||||||
| from langchain.agents.middleware.types import AgentMiddleware, ContextT, ModelRequest, ModelResponse, ResponseT | ||||||||
| from langchain.agents.structured_output import ResponseFormat | ||||||||
| from langchain.tools import BaseTool, ToolRuntime | ||||||||
| from langchain_core.language_models import BaseChatModel | ||||||||
| from langchain_core.messages import HumanMessage, ToolMessage | ||||||||
|
|
@@ -76,6 +79,42 @@ class SubAgent(TypedDict): | |||||||
| skills: NotRequired[list[str]] | ||||||||
| """Skill source paths for SkillsMiddleware.""" | ||||||||
|
|
||||||||
| response_format: NotRequired[ResponseFormat[Any] | type | dict[str, Any]] | ||||||||
| """Structured output response format for the subagent. | ||||||||
|
|
||||||||
| When specified, the subagent will produce a `structured_response` conforming to the | ||||||||
| given schema. The structured response is JSON-serialized and returned as the | ||||||||
| ToolMessage content to the parent agent, replacing the default last-message extraction. | ||||||||
|
|
||||||||
| Accepted formats (from `langchain.agents.structured_output`): | ||||||||
|
|
||||||||
| - `ToolStrategy(schema)`: Use tool calling to extract structured output from the model. | ||||||||
| - `ProviderStrategy(schema)`: Use the model provider's native structured output mode. | ||||||||
| - `AutoStrategy(schema)`: Automatically select the best strategy. | ||||||||
| - A bare Python `type`: A Pydantic `BaseModel` subclass, `dataclass`, or `TypedDict` | ||||||||
| class. Equivalent to `AutoStrategy(schema)`. | ||||||||
| - `dict[str, Any]`: A JSON schema dictionary (e.g., | ||||||||
| `{"type": "object", "properties": {...}, "required": [...]}`). | ||||||||
|
|
||||||||
| Example: | ||||||||
| ```python | ||||||||
| from pydantic import BaseModel | ||||||||
|
|
||||||||
| class Findings(BaseModel): | ||||||||
| findings: str | ||||||||
| confidence: float | ||||||||
|
|
||||||||
| analyzer: SubAgent = { | ||||||||
| "name": "analyzer", | ||||||||
| "description": "Analyzes data and returns structured findings", | ||||||||
| "system_prompt": "Analyze the data and return your findings.", | ||||||||
| "model": "openai:gpt-4o", | ||||||||
| "tools": [], | ||||||||
| "response_format": Findings, | ||||||||
| } | ||||||||
| ``` | ||||||||
| """ | ||||||||
|
|
||||||||
|
|
||||||||
| class CompiledSubAgent(TypedDict): | ||||||||
| """A pre-compiled agent spec. | ||||||||
|
|
@@ -295,6 +334,99 @@ class _SubagentSpec(TypedDict): | |||||||
| runnable: Runnable | ||||||||
|
|
||||||||
|
|
||||||||
| def _get_subagents_legacy( | ||||||||
| *, | ||||||||
| default_model: str | BaseChatModel, | ||||||||
| default_tools: Sequence[BaseTool | Callable | dict[str, Any]], | ||||||||
| default_middleware: list[AgentMiddleware] | None, | ||||||||
| default_interrupt_on: dict[str, bool | InterruptOnConfig] | None, | ||||||||
| subagents: Sequence[SubAgent | CompiledSubAgent], | ||||||||
| general_purpose_agent: bool, | ||||||||
| ) -> list[_SubagentSpec]: | ||||||||
| """Create subagent instances from specifications. | ||||||||
|
|
||||||||
| Args: | ||||||||
| default_model: Default model for subagents that don't specify one. | ||||||||
| default_tools: Default tools for subagents that don't specify tools. | ||||||||
| default_middleware: Middleware to apply to all subagents. If `None`, | ||||||||
| no default middleware is applied. | ||||||||
| default_interrupt_on: The tool configs to use for the default general-purpose subagent. These | ||||||||
| are also the fallback for any subagents that don't specify their own tool configs. | ||||||||
| subagents: List of agent specifications or pre-compiled agents. | ||||||||
| general_purpose_agent: Whether to include a general-purpose subagent. | ||||||||
|
|
||||||||
| Returns: | ||||||||
| List of subagent specs containing name, description, and runnable. | ||||||||
| """ | ||||||||
| # Use empty list if None (no default middleware) | ||||||||
| default_subagent_middleware = default_middleware or [] | ||||||||
|
|
||||||||
| specs: list[_SubagentSpec] = [] | ||||||||
|
|
||||||||
| # Create general-purpose agent if enabled | ||||||||
| if general_purpose_agent: | ||||||||
| general_purpose_middleware = [*default_subagent_middleware] | ||||||||
| if default_interrupt_on: | ||||||||
| general_purpose_middleware.append(HumanInTheLoopMiddleware(interrupt_on=default_interrupt_on)) | ||||||||
| general_purpose_subagent = create_agent( | ||||||||
| default_model, | ||||||||
| system_prompt=DEFAULT_SUBAGENT_PROMPT, | ||||||||
| tools=default_tools, | ||||||||
| middleware=general_purpose_middleware, | ||||||||
| name="general-purpose", | ||||||||
| ) | ||||||||
| specs.append( | ||||||||
| { | ||||||||
| "name": "general-purpose", | ||||||||
| "description": DEFAULT_GENERAL_PURPOSE_DESCRIPTION, | ||||||||
| "runnable": general_purpose_subagent, | ||||||||
| } | ||||||||
| ) | ||||||||
|
|
||||||||
| # Process custom subagents | ||||||||
| for agent_ in subagents: | ||||||||
| if "runnable" in agent_: | ||||||||
| custom_agent = cast("CompiledSubAgent", agent_) | ||||||||
| specs.append( | ||||||||
| { | ||||||||
| "name": custom_agent["name"], | ||||||||
| "description": custom_agent["description"], | ||||||||
| "runnable": custom_agent["runnable"], | ||||||||
| } | ||||||||
| ) | ||||||||
| continue | ||||||||
| _tools = agent_.get("tools", list(default_tools)) | ||||||||
|
|
||||||||
| subagent_model = agent_.get("model", default_model) | ||||||||
|
|
||||||||
| _middleware = [*default_subagent_middleware, *agent_["middleware"]] if "middleware" in agent_ else [*default_subagent_middleware] | ||||||||
|
|
||||||||
| interrupt_on = agent_.get("interrupt_on", default_interrupt_on) | ||||||||
| if interrupt_on: | ||||||||
| _middleware.append(HumanInTheLoopMiddleware(interrupt_on=interrupt_on)) | ||||||||
|
|
||||||||
| create_agent_kwargs: dict[str, Any] = {} | ||||||||
| if "response_format" in agent_: | ||||||||
| create_agent_kwargs["response_format"] = agent_["response_format"] | ||||||||
|
|
||||||||
|
Comment on lines
+408
to
+411
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. eh no need to thread this through the legacy API, we'll remove |
||||||||
| specs.append( | ||||||||
| { | ||||||||
| "name": agent_["name"], | ||||||||
| "description": agent_["description"], | ||||||||
| "runnable": create_agent( | ||||||||
| subagent_model, | ||||||||
| system_prompt=agent_["system_prompt"], | ||||||||
| tools=_tools, | ||||||||
| middleware=_middleware, | ||||||||
| name=agent_["name"], | ||||||||
| **create_agent_kwargs, | ||||||||
| ), | ||||||||
| } | ||||||||
| ) | ||||||||
|
|
||||||||
| return specs | ||||||||
|
|
||||||||
|
|
||||||||
| def _build_task_tool( # noqa: C901 | ||||||||
| subagents: list[_SubagentSpec], | ||||||||
| task_description: str | None = None, | ||||||||
|
|
@@ -332,12 +464,23 @@ def _return_command_with_state_update(result: dict, tool_call_id: str) -> Comman | |||||||
| raise ValueError(error_msg) | ||||||||
|
|
||||||||
| state_update = {k: v for k, v in result.items() if k not in _EXCLUDED_STATE_KEYS} | ||||||||
| # Strip trailing whitespace to prevent API errors with Anthropic | ||||||||
| message_text = result["messages"][-1].text.rstrip() if result["messages"][-1].text else "" | ||||||||
|
|
||||||||
| structured = result.get("structured_response") | ||||||||
| if structured is not None: | ||||||||
|
Comment on lines
+468
to
+469
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. little nit
Suggested change
|
||||||||
| if hasattr(structured, "model_dump_json"): | ||||||||
| content: str = structured.model_dump_json() | ||||||||
| elif dataclasses.is_dataclass(structured) and not isinstance(structured, type): | ||||||||
| content = json.dumps(dataclasses.asdict(structured)) | ||||||||
| else: | ||||||||
| content = json.dumps(structured) | ||||||||
| else: | ||||||||
| # Strip trailing whitespace to prevent API errors with Anthropic | ||||||||
| content = result["messages"][-1].text.rstrip() if result["messages"][-1].text else "" | ||||||||
|
|
||||||||
| return Command( | ||||||||
| update={ | ||||||||
| **state_update, | ||||||||
| "messages": [ToolMessage(message_text, tool_call_id=tool_call_id)], | ||||||||
| "messages": [ToolMessage(content, tool_call_id=tool_call_id)], | ||||||||
| } | ||||||||
| ) | ||||||||
|
|
||||||||
|
|
@@ -501,6 +644,10 @@ def _get_subagents(self) -> list[_SubagentSpec]: | |||||||
| if interrupt_on: | ||||||||
| middleware.append(HumanInTheLoopMiddleware(interrupt_on=interrupt_on)) | ||||||||
|
|
||||||||
| create_agent_kwargs: dict[str, Any] = {} | ||||||||
| if "response_format" in spec: | ||||||||
| create_agent_kwargs["response_format"] = spec["response_format"] | ||||||||
|
|
||||||||
| specs.append( | ||||||||
| { | ||||||||
| "name": spec["name"], | ||||||||
|
|
@@ -511,6 +658,7 @@ def _get_subagents(self) -> list[_SubagentSpec]: | |||||||
| tools=spec["tools"], | ||||||||
| middleware=middleware, | ||||||||
| name=spec["name"], | ||||||||
| **create_agent_kwargs, | ||||||||
| ), | ||||||||
| } | ||||||||
| ) | ||||||||
|
|
||||||||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Instead of documenting example usage, could we document what the options are?
What is
type? (i.e., allows pydantic model, dataclass etc)waht is dict? (i think it's json schema)
Given that we allow a dataclass, does this code work b/c there's a json.dumps?