Commit Graph
6210 Commits
Author SHA1 Message Date
Sydney RunkleandGitHub 33ae3d4a8a chore(prebuilt): revert back to create_react_agent (#6017) 2025-08-26 09:18:32 -04:00
cf615a46e6 feat(prebuilt): structured output error handling with configurable retry policy (#6002)
This PR adds error handling and retry mechanisms for create_agent
structured output via a `handle_errors` parameter in `ToolOutput`.

Changes:
* Adds `MultipleStructuredOutputsError` exception for when models
incorrectly call multiple structured output tools simultaneously
* Adds `StructuredOutputParsingError` exception for when tool arguments
fail to parse according to the schema
* Implements automatic error handling logic that re-prompts the model
with a configurable error message when structured output failures occur
via `handle_errors` policy in `ToolOutput`:
```python
class ToolOutput:
    ...
    handle_errors: Union[
        bool,                         # True: retry all, False: no retry
        str,                          # Custom static error message for all errors
        type[Exception],              # Retry only this exception type
        tuple[type[Exception], ...],  # Retry only these exception types
        Callable[[Exception], str],   # Custom callable returning error message
    ]
    """Error handling strategy. Default: True (retry on all error types with default error message)"""
```

Examples:
```python
# Retry all errors
ToolOutput(WeatherReport)

# No retry
ToolOutput(WeatherReport, handle_errors=False)

# Custom message for all errors
ToolOutput(WeatherReport, handle_errors="Please provide valid data")

# Only retry specific error type
ToolOutput(WeatherReport, handle_errors=StructuredOutputParsingError)

# Multiple error types
ToolOutput(WeatherReport, handle_errors=(MultipleStructuredOutputsError, StructuredOutputParsingError))

# Custom logic
ToolOutput(
    Union[WeatherReport, LocationInfo],
    handle_errors=lambda e: "Only one response please" if isinstance(e, MultipleStructuredOutputsError) else "Invalid format"
)
```

---------

Co-authored-by: Sydney Runkle <sydneymarierunkle@gmail.com>
2025-08-26 09:04:23 -04:00
Sydney RunkleandGitHub e269b46b1b feat(prebuilt): update tool error handling in tool node (#6008)
Change how we handle tool errors by default in tool node.

1. If a tool invocation failed due to arg validation, we return an
artificial `ToolMessage` back to the model w/ a request for arg
correction (the same, but we've improved the message)
2. If a tool execution failed for an unknown reason, we raise
(different, we used to automatically return to model)
2025-08-25 16:44:45 -04:00
Caspar BroekhuizenandGitHub 77d98b426b test(prebuilt): standard integration tests for create_agent (#5988)
This PR improves standard integration tests in prebuilt to ensure
logical equivalence between the Python and JavaScript implementations of
`create_agent`.
* Cleans up `test_responses_int` test harness
* Adds new test utils to dynamically load JSON test specs
* Adds `test_return_direct_int` test harness to validate model behavior
when `return_direct` tool property is set
* Adds support for when the user instantiates `ToolOutput` with multiple
JSON schemas unified by the `oneOf` keyword

Failing tests:
* `test_inference_to_native_output`: there is some odd behavior where
the model makes a second call to `get_weather` despite having just
received the tool message, so there are 6 messages instead of the 4
expected.
* `test_responses_integration_matrix[asking for information that does
not fit into the response format]`: `XFAIL`, currently failing due to
undefined behavior when the model cannot conform to any of the
structured response formats.

TODO in future PRs:
* Add exception handling to pass `test_responses_integration_matrix`.
2025-08-22 13:55:09 -04:00
f4cdeea6ad feat(prebuilt): native structured output support w/ all sorts of models (#5961)
* Adds support for `NativeOutput` via a new `NativeOutput` dataclass
* Adds support for structured output specification via the following
(pydantic models already supported)
  * dataclasses
  * typed dicts
  * json schemas 
* Adds mocking support to support native strategies with
`FakeToolCallingModel`
* Add new default tool message when `tool_message_content` not provided
* Smart "selection" of native vs tool output based on provider support,
necessitates profiles down the line
  
Considered questions
* do we want to enforce docstrings? -- decided on no for now
* do we want to enforce names (titles) on json schemas? -- decided no
for now, defaulting to `structured_output`
* do we want to validate that json schemas coming in are valid? --
decided no for now
* do we want to validate model results against a given json schema? we
validate against all other types (typed dict, dataclass, etc) w/
pydantic -- decided no for now

TODO in future PRs:
* Figure out retry policy
* Add standard testing (handed off to @casparb)
* Further privatize certain structures (like the bindings) -- this is
low prio

---------

Co-authored-by: Sydney Runkle <sydneymarierunkle@gmail.com>
Co-authored-by: Sydney Runkle <54324534+sydney-runkle@users.noreply.github.com>
2025-08-21 10:43:50 -04:00
Sydney RunkleandGitHub 1cd1373788 chore(prebuilt): clean up public state (#5973)
precursor to `prepare_call` PR, cleaning up existing logic w/ pre model
hook

* use one combined `AgentState` instead of the one w/ and w/o structured
response
* remove exposed pydantic agent state + loosen bounds on state type
* remove llm input messages pattern, should be made possible with
prepare_call

also
* some remaining test fixes in `langgraph` to adapt to new `model` node
name (used to be `agent`)
2025-08-20 11:23:14 -04:00
Sydney RunkleandGitHub f994d16b49 chore(prebuilt): critical renaming (#5971)
* `create_react_agent` -> `create_agent`
* `agent` node -> `model` node
2025-08-20 09:15:42 -04:00
Sydney RunkleandGitHub 20953b4728 chore(prebuilt): remove config schema deprecation for new version (#5970)
don't need this deprecation warning as we're migrating to langchain
2025-08-20 09:04:11 -04:00
Sydney RunkleandGitHub e670815780 chore(prebuilt): rework structured outputs -- type safety, etc (#5962)
* make `_SchemaSpec` private
* Add ability to customize message used in artificial tool response
2025-08-20 08:52:51 -04:00
Sydney RunkleandGitHub 4151861ca2 chore(prebuilt): remove v1 (#5960) 2025-08-19 14:30:32 -04:00
Sydney RunkleandGitHub 5239184ba6 chore(prebuilt): revert optional multiple nodes for tools (#5959) 2025-08-19 14:19:57 -04:00
Sydney RunkleandGitHub a5aa9ce27d chore(prebuilt): remove support for models that used bind_X (#5958)
Remove support for models w/ `.bind` used to streamline public API +
recommendations
Also cleaning up `typing.py` file as requested :)
2025-08-19 13:56:16 -04:00
Eugene YurtsevandGitHub b58a7fb2fe feat(prebuilt): support ToolOutput response_format (#5915)
* Add support for ToolOutput response format.
* I don't love the name -- it's confusing unless you know that it's parameterizing a strategy.

We should determine if we want to support our old strategy for doing
things -- it has a higher latency (one extra LLM call), but it's a
reasonable built-in strategy as it doesn't do anything awkward with
conversation history. (Wouldn't surprising if it has overall better
performance than tool choice for longer conversations)
2025-08-14 23:34:46 -04:00
Eugene Yurtsev ebae60045f Fix spelling typo 2025-08-14 14:51:13 -04:00
Eugene YurtsevandGitHub 42f9683d73 chore(prebuilt): breaking do not support prebound tools on model (#5912)
Do not support prebound tools on the model. There's reason users should be prebinding tools to the model!

This is a breaking change that might affect some users, but the work-around is simple -- provide tools into the create_react_agent api.
2025-08-14 14:46:11 -04:00
Eugene YurtsevandGitHub 69249e724d chore(prebuilt): Separate prompt from model (#5909)
Quick clean up to simplify the logic by which messages into the model are prepared.
2025-08-14 12:59:09 -04:00
Eugene YurtsevandGitHub e6d71a586d chore(prebuilt): remove structured tool support from ToolNode (#5902)
Remove structured tool support from ToolNode

We'll handle structured tools directly in the call_model nodes.
2025-08-13 22:32:21 -04:00
Eugene YurtsevandGitHub 50601dc02c feat(prebuilt): Add structured output tools to ToolNode (#5899)
* Add structured output tools to ToolNode
* Fix default tool node name to match the actual default ('tools')
* Update doc-strings to explain what inputs/outputs are for the ToolNode.
* Mark internal attributes as private (potentially breaking -- although hopefully users aren't accessing these)


## Decisions points

* OK with two properties? Done since users may be relying on
`tools_by_name` and expanding the return type will break user code.

## Changes in public/private interface

### Marked as public

* Make `tools_by_name` an official public property
* Make `structured_output_tools` a public property

### Marked as private

There should be no reason why users are accessing these attributes

```python
_tool_to_state_args
_tool_to_store_arg
_handle_tool_errors
_messages_key
```


### Usage

```python

    class OutputSchema(BaseModel):
        name: str
        age: int
        location: str

    tool_node = ToolNode([OutputSchema])

    # Test that the structured output tool is registered correctly
    assert "OutputSchema" in tool_node.structured_output_tools

    # Create a tool call that matches the schema
    tool_call = {
        "name": "OutputSchema",
        "args": {"name": "Alice", "age": 30, "location": "NYC"},
        "id": "call_123",
        "type": "tool_call",
    }

    # Test sync execution
    result = tool_node.invoke(
        {"messages": [AIMessage(content="", tool_calls=[tool_call])]}
    )

    # Should return a Command with structured response
    assert isinstance(result, list)
    assert len(result) == 1
    command = result[0]
    assert isinstance(command, Command)

    # Check the update structure
    assert "messages" in command.update
    assert "structured_response" in command.update

    # Check the tool message
    tool_message = command.update["messages"][0]
    assert isinstance(tool_message, ToolMessage)
    assert tool_message.name == "OutputSchema"
    assert tool_message.tool_call_id == "call_123"

    # Check the structured response
    structured_response = command.update["structured_response"]
    assert isinstance(structured_response, OutputSchema)
    assert structured_response.name == "Alice"
    assert structured_response.age == 30
    assert structured_response.location == "NYC"
```
2025-08-13 15:16:53 -04:00
Eugene YurtsevandGitHub 9e174e7e8b chore(prebuilt): move unit tests for ToolNode into the tool node testing code (#5893)
Move unit tests for ToolNode into the tool node testing code
2025-08-13 11:15:10 -04:00
Eugene YurtsevandGitHub 9e9a5d2498 feat(prebuilt): Split tool node to individual tool nodes (#5888)
Add option to split tool node to individual nodes. 

Summary:
* User code (specifically streaming) may break if it's relying on the
name of the `tools` node
* The boolean flag in the interface is likely **temporary** (especially
if there are no major breaking changes)
* We'll need to decide if we can get rid of the version in create react
agent. "v1" is not consistent conceptually with a node per tool.
2025-08-13 09:49:27 -04:00
Eugene Yurtsev 7e257dadd6 x 2025-08-12 21:52:21 -04:00
Eugene Yurtsev 2fed0e4852 Internal refactor of create react-agent 2025-08-12 21:50:19 -04:00
d43eaf1f42 chore(docs): add remaining js translations (#5825)
Related Linear ticket:
https://linear.app/langchain/issue/DOC-51/add-js-translations-for-remaining-pages

---------

Co-authored-by: Brody Klapko <brody@langchain.dev>
2025-08-12 09:47:11 -04:00
Sam CrowderandGitHub 16b363fbb0 feat(langgraph): implement redis node level cache (#5834)
###   Description

Adds Redis as a supported cache backend for LangGraph node-level
caching, enabling distributed caching across multiple processes/servers.
This implementation follows the same patterns as existing InMemoryCache
and SqliteCache.

###  Key changes
  - New RedisCache class implementing the BaseCache interface
  - Support for TTL-based expiration and batch operations
  - Worker-specific cache prefixes for parallel test isolation

###  Dependencies

  - redis package (already included in dev dependencies)

### Test Plan

- Unit tests: Added Redis cache tests covering basic operations, TTL,
batch operations, and error handling
- Integration tests: Redis cache integrated into existing LangGraph test
suite, tested with all checkpointer combinations
2025-08-11 09:19:34 -07:00
Sydney RunkleandGitHub 68a75135b0 release: langgraph + prebuilt 0.6.4 (#5854) prebuilt==0.6.4 0.6.4 2025-08-07 18:12:26 +00:00
Isaac FranciscoandGitHub 5c0c0fb186 fix: mypy issue with conditional edges (#5851)
Send should inherit from hashable, and need to use Sequence since List
is invariant.

https://github.com/langchain-ai/langgraph/issues/5850
2025-08-07 08:46:44 -07:00
4571b708d9 fix(langgraph): support emitting messages from subgraphs when messages mode explicitly requested (#5836)
Reproduces:
https://github.com/langchain-ai/langgraph/issues/5249#issuecomment-3156519635
Caused after this change:
https://github.com/langchain-ai/langgraph/pull/4843

Fix to allow emitting messages from subgraphs if the subgraphs
explicitly used a stream mode "messages".

```python

def node_in_parent(...):
   # subgraph was called as a function.
   # messages are explicitly requested.
   for event in subgraph.stream(..., stream_mode="messages"):
      # something is done with `event`
   return ...

# subgraphs = False!
parent_graph.invoke(..., subgraphs=False)
```

The code above should continue to work correctly regardless of the value
of subgraphs as streaming messages was requested explicitly in the
parent node!

---------

Co-authored-by: Sydney Runkle <54324534+sydney-runkle@users.noreply.github.com>
2025-08-07 10:10:52 -04:00
Sydney RunkleandGitHub e365b2b8bd fix(prebuilt): raise on additional deprecated kwargs (#5848) 2025-08-06 21:08:42 +00:00
Isaac FranciscoandGitHub b5504506a7 fix: add resiliency for task cancellation (#5846) 2025-08-06 13:31:52 -07:00
Nuno CamposandGitHub c6ae8d25b9 perf: Save updated_channels to checkpoint (#5828)
- This makes prepare_next_tasks constant on number of nodes in all
cases, whereas before we were falling back to node iteration when
resuming from an existing checkpoint
2025-08-06 19:09:33 +01:00
Sydney RunkleandGitHub 0bd7dd2c52 chore(langgraph): deprecate MessageGraph (#5843)
`MessageGraph` is deprecated, to be removed in v2.

A `StateGraph` with a `messages` key should be used instead.
Alternatively, folks can use `Annotated[list[AnyMessage], add_messages]` as their state schema.
2025-08-06 14:17:50 +00:00
Sydney RunkleandGitHub 82978a8dd8 chore(prebuilt): revert tool arg injection refactor (#5842)
Reverts https://github.com/langchain-ai/langgraph/pull/5562

I anticipate that we want to do another pass at a refactor here in the
short term, but this makes it easier to adapt to new langchain core
message types for v0.4 support in the short term.
2025-08-06 10:12:08 -04:00
Kathryn MayandGitHub 925150a35d docs: Update redirects for deployment option renaming (#5823)
Updates the URLs for the new site deployment options after a rename.
2025-08-04 15:32:11 -04:00
Sydney RunkleandGitHub 2920a9dd19 fix(langgraph): Tidy up AgentState (#5801)
Fixes https://github.com/langchain-ai/langgraph/issues/5784

* Removes usage of `is_last_step`, no longer needed with
`remaining_steps`
* Make `remaining_steps` `NotRequired` so that json schema doesn't
suggest need for user input
* Move `PregelScratchpad` to shared utils file to prevent circular
import issue (it's used from `channels/managed` and other pregel files).
* Ensures that managed values wrapped in `NotRequired` or `Required` are
still recognized!
0.6.3 prebuilt==0.6.3
2025-08-03 07:12:53 -04:00
Eugene YurtsevandGitHub db8ed4e9e4 fix(docs): update agents.md (#5800)
fix comment in tip
2025-08-02 06:09:09 -04:00
Lauren Hirata SinghandGitHub b16fcc8468 docs: remove broken links (#5803) 2025-08-01 15:41:21 -04:00
Sydney RunkleandGitHub a2fe4df89b release: langgraph + prebuilt 0.6.3 (#5799) 2025-08-01 14:52:38 -04:00
open-swe[bot]GitHubopen-swe[bot] <open-swe@users.noreply.github.com>Sydney Runkle
69dd20e523 fix(langgraph): Add warning for incorrect node signature with mistyped config param (#5798)
Fixes: #5787

Ensures that if `config` is not typed as one of `RunanbleConfig` or
`Optional[RunnableConfig]` a warning is raised to help developers avoid
unexpected results at invocation time.

---------

Co-authored-by: open-swe[bot] <open-swe@users.noreply.github.com>
Co-authored-by: Sydney Runkle <sydneymarierunkle@gmail.com>
2025-08-01 17:25:14 +00:00
open-swe[bot]GitHubopen-swe[bot] <open-swe@users.noreply.github.com>
5152a96fce fix(docs): Correct import statement for InMemorySaver in conceptual docs (#5797)
Fixes #5781

Fixes the incorrect import statement in the Python documentation
tutorial.

- Changed import from `MemorySaver` to `InMemorySaver`
- Ensures consistency between import statement and class instantiation
- Verified through formatting and linting checks

The documentation now correctly reflects the proper import for the
InMemorySaver class.

---------

Co-authored-by: open-swe[bot] <open-swe@users.noreply.github.com>
2025-08-01 14:54:30 +00:00
Sydney RunkleandGitHub 220314b53a fix(langgraph): fix up deprecation warnings (#5796)
Fixes https://github.com/langchain-ai/langgraph/issues/5795

* Must use `category=None` on decorator so that we get type checking
support but no dupe warning
* Fixed tuple on `confix_type` warning causing false warning
2025-08-01 14:33:46 +00:00
38bbd92e01 feat(langgraph): add durability mode for invoke and ainvoke (#5771)
Fixes https://github.com/langchain-ai/langgraph/issues/5741

Follow up to https://github.com/langchain-ai/langgraph/pull/5432

Plus clean up deprecation logic for `checkpoint_during` and add tests.

---------

Co-authored-by: Eugene Yurtsev <eyurtsev@gmail.com>
Co-authored-by: Lauren Hirata Singh <lauren@langchain.dev>
2025-08-01 10:30:24 -04:00
Eugene YurtsevandGitHub e3cb2dd23b chore(docs): fix more admonitions (#5792)
Fix more admonitions
2025-07-31 22:57:44 -04:00
Eugene YurtsevandGitHub 2f23d1a30d chore(docs): fix js build (#5793)
Fix js build
2025-07-31 22:57:32 -04:00
Eugene YurtsevandGitHub 88e195bb78 chore(docs): fix admonitions in graph api page (#5791)
fix many admonitions in the graph API page
2025-07-31 21:50:27 -04:00
41a4f993b1 docs: Update link maps for reference docs (#5745)
Update link maps

---------

Co-authored-by: Hunter Lovell <hunter@hntrl.io>
2025-07-31 18:06:35 -04:00
b8f3f48da9 fix(docs): Add missing imports to make examples runnable (#5477)
I suppose that the code snippets are intended to run each on its own. To
guarantee this the snippet for the example:
"Write long-temr memory from tools"
needs to include `RunnableConfig`
Same also for the second commit of this pull request.

The other commits are about similar issues, where imports are missing to
make a snippet executable on its own.

---------

Signed-off-by: Kai Wendel <kai.wendel@iws.uni-stuttgart.de>
Co-authored-by: Eugene Yurtsev <eugene@langchain.dev>
Co-authored-by: Lauren Hirata Singh <lauren@langchain.dev>
2025-07-31 20:04:52 +00:00
94f7f0632d docs(docs): fix image in "Run graph nodes in parallel" section of N Graph API how-to (#5527)
**Description:**
Replaced the outdated image in the "Run graph nodes in parallel" section
of the N Graph API how-to guide to correctly show parallel node
execution.

**Twitter handle:** @MichaelLoukeris

Co-authored-by: Lauren Hirata Singh <lauren@langchain.dev>
2025-07-31 20:02:33 +00:00
Xin JinandGitHub b3e0582255 docs: clarify draw_mermaid_png only works in jupyter (#5609)
Nit, without comments I thought image would somehow show in terminal,
but that's not true you'd only get image to show if in jupyter notebook.
Don't have to merge, i'm just seeing this particular as not a pleasure
DevX.

<img width="848" height="440" alt="Screenshot 2025-07-21 at 12 26 04 PM"
src="https://github.com/user-attachments/assets/50261b35-f09d-4516-86f4-14e8bf53f8e2"
/>
2025-07-31 15:54:45 -04:00
24c7a8db3f Remove duplicated pretty_print_messages helper in Multi‑agent supervisor tutorial (#5617)
**Description:**  
Closes #___

Removed the redundant `pretty_print_message`/`pretty_print_messages`
helper snippet from
`docs/docs/tutorials/multi_agent/agent_supervisor.md`. Now there is a
single, authoritative definition of these functions, which:

- Simplifies the tutorial  
- Avoids reader confusion over which helper to use  
- Prevents future drift between duplicate code blocks  

**Issue:** Closes #___  
**Dependencies:** None

Co-authored-by: Lauren Hirata Singh <lauren@langchain.dev>
2025-07-31 19:54:22 +00:00
f8eb4244e0 docs(graphapi): update the graph image for the "Combine control flow and state updates with Command" example (#5626)
The example had the node names as - node_a, node_b & node_c. But the
graph shows the image of generate_topics. This change includes the
addition of complete & accurate graph.

---------

Co-authored-by: Eugene Yurtsev <eyurtsev@gmail.com>
2025-07-31 19:52:55 +00:00