langchain 1.0.0a3__py3-none-any.whl → 1.0.0a5__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
langchain/__init__.py CHANGED
@@ -2,7 +2,7 @@
2
2
 
3
3
  from typing import Any
4
4
 
5
- __version__ = "1.0.0a1"
5
+ __version__ = "1.0.0a4"
6
6
 
7
7
 
8
8
  def __getattr__(name: str) -> Any: # noqa: ANN401
@@ -1,13 +1,12 @@
1
1
  """Lazy import utilities."""
2
2
 
3
3
  from importlib import import_module
4
- from typing import Union
5
4
 
6
5
 
7
6
  def import_attr(
8
7
  attr_name: str,
9
- module_name: Union[str, None],
10
- package: Union[str, None],
8
+ module_name: str | None,
9
+ package: str | None,
11
10
  ) -> object:
12
11
  """Import an attribute from a module located in a package.
13
12
 
@@ -12,7 +12,7 @@ particularly for summarization chains and other document processing workflows.
12
12
  from __future__ import annotations
13
13
 
14
14
  import inspect
15
- from typing import TYPE_CHECKING, Union
15
+ from typing import TYPE_CHECKING
16
16
 
17
17
  if TYPE_CHECKING:
18
18
  from collections.abc import Awaitable, Callable
@@ -24,11 +24,7 @@ if TYPE_CHECKING:
24
24
 
25
25
 
26
26
  def resolve_prompt(
27
- prompt: Union[
28
- str,
29
- None,
30
- Callable[[StateT, Runtime[ContextT]], list[MessageLikeRepresentation]],
31
- ],
27
+ prompt: str | None | Callable[[StateT, Runtime[ContextT]], list[MessageLikeRepresentation]],
32
28
  state: StateT,
33
29
  runtime: Runtime[ContextT],
34
30
  default_user_content: str,
@@ -61,6 +57,7 @@ def resolve_prompt(
61
57
  def custom_prompt(state, runtime):
62
58
  return [{"role": "system", "content": "Custom"}]
63
59
 
60
+
64
61
  messages = resolve_prompt(custom_prompt, state, runtime, "content", "default")
65
62
  messages = resolve_prompt("Custom system", state, runtime, "content", "default")
66
63
  messages = resolve_prompt(None, state, runtime, "content", "Default")
@@ -88,12 +85,10 @@ def resolve_prompt(
88
85
 
89
86
 
90
87
  async def aresolve_prompt(
91
- prompt: Union[
92
- str,
93
- None,
94
- Callable[[StateT, Runtime[ContextT]], list[MessageLikeRepresentation]],
95
- Callable[[StateT, Runtime[ContextT]], Awaitable[list[MessageLikeRepresentation]]],
96
- ],
88
+ prompt: str
89
+ | None
90
+ | Callable[[StateT, Runtime[ContextT]], list[MessageLikeRepresentation]]
91
+ | Callable[[StateT, Runtime[ContextT]], Awaitable[list[MessageLikeRepresentation]]],
97
92
  state: StateT,
98
93
  runtime: Runtime[ContextT],
99
94
  default_user_content: str,
@@ -128,15 +123,13 @@ async def aresolve_prompt(
128
123
  async def async_prompt(state, runtime):
129
124
  return [{"role": "system", "content": "Async"}]
130
125
 
126
+
131
127
  def sync_prompt(state, runtime):
132
128
  return [{"role": "system", "content": "Sync"}]
133
129
 
134
- messages = await aresolve_prompt(
135
- async_prompt, state, runtime, "content", "default"
136
- )
137
- messages = await aresolve_prompt(
138
- sync_prompt, state, runtime, "content", "default"
139
- )
130
+
131
+ messages = await aresolve_prompt(async_prompt, state, runtime, "content", "default")
132
+ messages = await aresolve_prompt(sync_prompt, state, runtime, "content", "default")
140
133
  messages = await aresolve_prompt("Custom", state, runtime, "content", "default")
141
134
  ```
142
135
 
@@ -2,7 +2,7 @@
2
2
 
3
3
  from __future__ import annotations
4
4
 
5
- from typing import TYPE_CHECKING, Any, ClassVar, Protocol, TypeAlias, TypeVar, Union
5
+ from typing import TYPE_CHECKING, Any, ClassVar, Protocol, TypeAlias, TypeVar
6
6
 
7
7
  from langgraph.graph._node import StateNode
8
8
  from pydantic import BaseModel
@@ -44,7 +44,7 @@ class DataclassLike(Protocol):
44
44
  __dataclass_fields__: ClassVar[dict[str, Field[Any]]]
45
45
 
46
46
 
47
- StateLike: TypeAlias = Union[TypedDictLikeV1, TypedDictLikeV2, DataclassLike, BaseModel]
47
+ StateLike: TypeAlias = TypedDictLikeV1 | TypedDictLikeV2 | DataclassLike | BaseModel
48
48
  """Type alias for state-like types.
49
49
 
50
50
  It can either be a ``TypedDict``, ``dataclass``, or Pydantic ``BaseModel``.
@@ -58,7 +58,7 @@ It can either be a ``TypedDict``, ``dataclass``, or Pydantic ``BaseModel``.
58
58
  StateT = TypeVar("StateT", bound=StateLike)
59
59
  """Type variable used to represent the state in a graph."""
60
60
 
61
- ContextT = TypeVar("ContextT", bound=Union[StateLike, None])
61
+ ContextT = TypeVar("ContextT", bound=StateLike | None)
62
62
  """Type variable for context types."""
63
63
 
64
64
 
@@ -3,11 +3,11 @@
3
3
  from __future__ import annotations
4
4
 
5
5
  from collections.abc import Awaitable, Callable
6
- from typing import TypeVar, Union
6
+ from typing import TypeVar
7
7
 
8
8
  from typing_extensions import ParamSpec
9
9
 
10
10
  P = ParamSpec("P")
11
11
  R = TypeVar("R")
12
12
 
13
- SyncOrAsync = Callable[P, Union[R, Awaitable[R]]]
13
+ SyncOrAsync = Callable[P, R | Awaitable[R]]
@@ -1,6 +1,6 @@
1
1
  """Interrupt types to use with agent inbox like setups."""
2
2
 
3
- from typing import Literal, Union
3
+ from typing import Literal
4
4
 
5
5
  from typing_extensions import TypedDict
6
6
 
@@ -53,15 +53,15 @@ class HumanInterrupt(TypedDict):
53
53
  request = HumanInterrupt(
54
54
  action_request=ActionRequest(
55
55
  action="run_command", # The action being requested
56
- args={"command": "ls", "args": ["-l"]} # Arguments for the action
56
+ args={"command": "ls", "args": ["-l"]}, # Arguments for the action
57
57
  ),
58
58
  config=HumanInterruptConfig(
59
- allow_ignore=True, # Allow skipping this step
60
- allow_respond=True, # Allow text feedback
61
- allow_edit=False, # Don't allow editing
62
- allow_accept=True # Allow direct acceptance
59
+ allow_ignore=True, # Allow skipping this step
60
+ allow_respond=True, # Allow text feedback
61
+ allow_edit=False, # Don't allow editing
62
+ allow_accept=True, # Allow direct acceptance
63
63
  ),
64
- description="Please review the command before execution"
64
+ description="Please review the command before execution",
65
65
  )
66
66
  # Send the interrupt request and get the response
67
67
  response = interrupt([request])[0]
@@ -74,19 +74,24 @@ class HumanInterrupt(TypedDict):
74
74
 
75
75
 
76
76
  class HumanResponse(TypedDict):
77
- """The response provided by a human to an interrupt, which is returned when graph execution resumes.
77
+ """Human response.
78
+
79
+ The response provided by a human to an interrupt,
80
+ which is returned when graph execution resumes.
78
81
 
79
82
  Attributes:
80
83
  type: The type of response:
84
+
81
85
  - "accept": Approves the current state without changes
82
86
  - "ignore": Skips/ignores the current step
83
87
  - "response": Provides text feedback or instructions
84
88
  - "edit": Modifies the current state/content
85
89
  args: The response payload:
90
+
86
91
  - None: For ignore/accept actions
87
92
  - str: For text responses
88
93
  - ActionRequest: For edit actions with updated content
89
94
  """
90
95
 
91
96
  type: Literal["accept", "ignore", "response", "edit"]
92
- args: Union[None, str, ActionRequest]
97
+ args: None | str | ActionRequest
@@ -0,0 +1,15 @@
1
+ """Middleware plugins for agents."""
2
+
3
+ from .human_in_the_loop import HumanInTheLoopMiddleware
4
+ from .prompt_caching import AnthropicPromptCachingMiddleware
5
+ from .summarization import SummarizationMiddleware
6
+ from .types import AgentMiddleware, AgentState, ModelRequest
7
+
8
+ __all__ = [
9
+ "AgentMiddleware",
10
+ "AgentState",
11
+ "AnthropicPromptCachingMiddleware",
12
+ "HumanInTheLoopMiddleware",
13
+ "ModelRequest",
14
+ "SummarizationMiddleware",
15
+ ]
@@ -0,0 +1,11 @@
1
+ """Utility functions for middleware."""
2
+
3
+ from typing import Any
4
+
5
+
6
+ def _generate_correction_tool_messages(content: str, tool_calls: list) -> list[dict[str, Any]]:
7
+ """Generate tool messages for model behavior correction."""
8
+ return [
9
+ {"role": "tool", "content": content, "tool_call_id": tool_call["id"]}
10
+ for tool_call in tool_calls
11
+ ]
@@ -0,0 +1,135 @@
1
+ """Human in the loop middleware."""
2
+
3
+ from typing import Any
4
+
5
+ from langgraph.prebuilt.interrupt import (
6
+ ActionRequest,
7
+ HumanInterrupt,
8
+ HumanInterruptConfig,
9
+ HumanResponse,
10
+ )
11
+ from langgraph.types import interrupt
12
+
13
+ from langchain.agents.middleware._utils import _generate_correction_tool_messages
14
+ from langchain.agents.middleware.types import AgentMiddleware, AgentState
15
+
16
+ ToolInterruptConfig = dict[str, HumanInterruptConfig]
17
+
18
+
19
+ class HumanInTheLoopMiddleware(AgentMiddleware):
20
+ """Human in the loop middleware."""
21
+
22
+ def __init__(
23
+ self,
24
+ tool_configs: ToolInterruptConfig,
25
+ message_prefix: str = "Tool execution requires approval",
26
+ ) -> None:
27
+ """Initialize the human in the loop middleware.
28
+
29
+ Args:
30
+ tool_configs: The tool interrupt configs to use for the middleware.
31
+ message_prefix: The message prefix to use when constructing interrupt content.
32
+ """
33
+ super().__init__()
34
+ self.tool_configs = tool_configs
35
+ self.message_prefix = message_prefix
36
+
37
+ def after_model(self, state: AgentState) -> dict[str, Any] | None:
38
+ """Trigger HITL flows for relevant tool calls after an AIMessage."""
39
+ messages = state["messages"]
40
+ if not messages:
41
+ return None
42
+
43
+ last_message = messages[-1]
44
+
45
+ if not hasattr(last_message, "tool_calls") or not last_message.tool_calls:
46
+ return None
47
+
48
+ # Separate tool calls that need interrupts from those that don't
49
+ interrupt_tool_calls = []
50
+ auto_approved_tool_calls = []
51
+
52
+ for tool_call in last_message.tool_calls:
53
+ tool_name = tool_call["name"]
54
+ if tool_name in self.tool_configs:
55
+ interrupt_tool_calls.append(tool_call)
56
+ else:
57
+ auto_approved_tool_calls.append(tool_call)
58
+
59
+ # If no interrupts needed, return early
60
+ if not interrupt_tool_calls:
61
+ return None
62
+
63
+ approved_tool_calls = auto_approved_tool_calls.copy()
64
+
65
+ # Right now, we do not support multiple tool calls with interrupts
66
+ if len(interrupt_tool_calls) > 1:
67
+ tool_names = [t["name"] for t in interrupt_tool_calls]
68
+ msg = (
69
+ f"Called the following tools which require interrupts: {tool_names}\n\n"
70
+ "You may only call ONE tool that requires an interrupt at a time"
71
+ )
72
+ return {
73
+ "messages": _generate_correction_tool_messages(msg, last_message.tool_calls),
74
+ "jump_to": "model",
75
+ }
76
+
77
+ # Right now, we do not support interrupting a tool call if other tool calls exist
78
+ if auto_approved_tool_calls:
79
+ tool_names = [t["name"] for t in interrupt_tool_calls]
80
+ msg = (
81
+ f"Called the following tools which require interrupts: {tool_names}. "
82
+ "You also called other tools that do not require interrupts. "
83
+ "If you call a tool that requires and interrupt, you may ONLY call that tool."
84
+ )
85
+ return {
86
+ "messages": _generate_correction_tool_messages(msg, last_message.tool_calls),
87
+ "jump_to": "model",
88
+ }
89
+
90
+ # Only one tool call will need interrupts
91
+ tool_call = interrupt_tool_calls[0]
92
+ tool_name = tool_call["name"]
93
+ tool_args = tool_call["args"]
94
+ description = f"{self.message_prefix}\n\nTool: {tool_name}\nArgs: {tool_args}"
95
+ tool_config = self.tool_configs[tool_name]
96
+
97
+ request: HumanInterrupt = {
98
+ "action_request": ActionRequest(
99
+ action=tool_name,
100
+ args=tool_args,
101
+ ),
102
+ "config": tool_config,
103
+ "description": description,
104
+ }
105
+
106
+ responses: list[HumanResponse] = interrupt([request])
107
+ response = responses[0]
108
+
109
+ if response["type"] == "accept":
110
+ approved_tool_calls.append(tool_call)
111
+ elif response["type"] == "edit":
112
+ edited: ActionRequest = response["args"] # type: ignore[assignment]
113
+ new_tool_call = {
114
+ "type": "tool_call",
115
+ "name": tool_call["name"],
116
+ "args": edited["args"],
117
+ "id": tool_call["id"],
118
+ }
119
+ approved_tool_calls.append(new_tool_call)
120
+ elif response["type"] == "ignore":
121
+ return {"jump_to": "__end__"}
122
+ elif response["type"] == "response":
123
+ tool_message = {
124
+ "role": "tool",
125
+ "tool_call_id": tool_call["id"],
126
+ "content": response["args"],
127
+ }
128
+ return {"messages": [tool_message], "jump_to": "model"}
129
+ else:
130
+ msg = f"Unknown response type: {response['type']}"
131
+ raise ValueError(msg)
132
+
133
+ last_message.tool_calls = approved_tool_calls
134
+
135
+ return {"messages": [last_message]}
@@ -0,0 +1,62 @@
1
+ """Anthropic prompt caching middleware."""
2
+
3
+ from typing import Literal
4
+
5
+ from langchain.agents.middleware.types import AgentMiddleware, AgentState, ModelRequest
6
+
7
+
8
+ class AnthropicPromptCachingMiddleware(AgentMiddleware):
9
+ """Prompt Caching Middleware.
10
+
11
+ Optimizes API usage by caching conversation prefixes for Anthropic models.
12
+
13
+ Learn more about Anthropic prompt caching
14
+ `here <https://docs.anthropic.com/en/docs/build-with-claude/prompt-caching>`__.
15
+ """
16
+
17
+ def __init__(
18
+ self,
19
+ type: Literal["ephemeral"] = "ephemeral",
20
+ ttl: Literal["5m", "1h"] = "5m",
21
+ min_messages_to_cache: int = 0,
22
+ ) -> None:
23
+ """Initialize the middleware with cache control settings.
24
+
25
+ Args:
26
+ type: The type of cache to use, only "ephemeral" is supported.
27
+ ttl: The time to live for the cache, only "5m" and "1h" are supported.
28
+ min_messages_to_cache: The minimum number of messages until the cache is used,
29
+ default is 0.
30
+ """
31
+ self.type = type
32
+ self.ttl = ttl
33
+ self.min_messages_to_cache = min_messages_to_cache
34
+
35
+ def modify_model_request(self, request: ModelRequest, state: AgentState) -> ModelRequest: # noqa: ARG002
36
+ """Modify the model request to add cache control blocks."""
37
+ try:
38
+ from langchain_anthropic import ChatAnthropic
39
+ except ImportError:
40
+ msg = (
41
+ "AnthropicPromptCachingMiddleware caching middleware only supports "
42
+ "Anthropic models."
43
+ "Please install langchain-anthropic."
44
+ )
45
+ raise ValueError(msg)
46
+
47
+ if not isinstance(request.model, ChatAnthropic):
48
+ msg = (
49
+ "AnthropicPromptCachingMiddleware caching middleware only supports "
50
+ f"Anthropic models, not instances of {type(request.model)}"
51
+ )
52
+ raise ValueError(msg)
53
+
54
+ messages_count = (
55
+ len(request.messages) + 1 if request.system_prompt else len(request.messages)
56
+ )
57
+ if messages_count < self.min_messages_to_cache:
58
+ return request
59
+
60
+ request.model_settings["cache_control"] = {"type": self.type, "ttl": self.ttl}
61
+
62
+ return request
@@ -0,0 +1,248 @@
1
+ """Summarization middleware."""
2
+
3
+ import uuid
4
+ from collections.abc import Callable, Iterable
5
+ from typing import Any, cast
6
+
7
+ from langchain_core.messages import (
8
+ AIMessage,
9
+ AnyMessage,
10
+ MessageLikeRepresentation,
11
+ RemoveMessage,
12
+ ToolMessage,
13
+ )
14
+ from langchain_core.messages.human import HumanMessage
15
+ from langchain_core.messages.utils import count_tokens_approximately, trim_messages
16
+ from langgraph.graph.message import (
17
+ REMOVE_ALL_MESSAGES,
18
+ )
19
+
20
+ from langchain.agents.middleware.types import AgentMiddleware, AgentState
21
+ from langchain.chat_models import BaseChatModel, init_chat_model
22
+
23
+ TokenCounter = Callable[[Iterable[MessageLikeRepresentation]], int]
24
+
25
+ DEFAULT_SUMMARY_PROMPT = """<role>
26
+ Context Extraction Assistant
27
+ </role>
28
+
29
+ <primary_objective>
30
+ Your sole objective in this task is to extract the highest quality/most relevant context from the conversation history below.
31
+ </primary_objective>
32
+
33
+ <objective_information>
34
+ You're nearing the total number of input tokens you can accept, so you must extract the highest quality/most relevant pieces of information from your conversation history.
35
+ This context will then overwrite the conversation history presented below. Because of this, ensure the context you extract is only the most important information to your overall goal.
36
+ </objective_information>
37
+
38
+ <instructions>
39
+ The conversation history below will be replaced with the context you extract in this step. Because of this, you must do your very best to extract and record all of the most important context from the conversation history.
40
+ You want to ensure that you don't repeat any actions you've already completed, so the context you extract from the conversation history should be focused on the most important information to your overall goal.
41
+ </instructions>
42
+
43
+ The user will message you with the full message history you'll be extracting context from, to then replace. Carefully read over it all, and think deeply about what information is most important to your overall goal that should be saved:
44
+
45
+ With all of this in mind, please carefully read over the entire conversation history, and extract the most important and relevant context to replace it so that you can free up space in the conversation history.
46
+ Respond ONLY with the extracted context. Do not include any additional information, or text before or after the extracted context.
47
+
48
+ <messages>
49
+ Messages to summarize:
50
+ {messages}
51
+ </messages>""" # noqa: E501
52
+
53
+ SUMMARY_PREFIX = "## Previous conversation summary:"
54
+
55
+ _DEFAULT_MESSAGES_TO_KEEP = 20
56
+ _DEFAULT_TRIM_TOKEN_LIMIT = 4000
57
+ _DEFAULT_FALLBACK_MESSAGE_COUNT = 15
58
+ _SEARCH_RANGE_FOR_TOOL_PAIRS = 5
59
+
60
+
61
+ class SummarizationMiddleware(AgentMiddleware):
62
+ """Middleware that summarizes conversation history when token limits are approached.
63
+
64
+ This middleware monitors message token counts and automatically summarizes older
65
+ messages when a threshold is reached, preserving recent messages and maintaining
66
+ context continuity by ensuring AI/Tool message pairs remain together.
67
+ """
68
+
69
+ def __init__(
70
+ self,
71
+ model: str | BaseChatModel,
72
+ max_tokens_before_summary: int | None = None,
73
+ messages_to_keep: int = _DEFAULT_MESSAGES_TO_KEEP,
74
+ token_counter: TokenCounter = count_tokens_approximately,
75
+ summary_prompt: str = DEFAULT_SUMMARY_PROMPT,
76
+ summary_prefix: str = SUMMARY_PREFIX,
77
+ ) -> None:
78
+ """Initialize the summarization middleware.
79
+
80
+ Args:
81
+ model: The language model to use for generating summaries.
82
+ max_tokens_before_summary: Token threshold to trigger summarization.
83
+ If None, summarization is disabled.
84
+ messages_to_keep: Number of recent messages to preserve after summarization.
85
+ token_counter: Function to count tokens in messages.
86
+ summary_prompt: Prompt template for generating summaries.
87
+ summary_prefix: Prefix added to system message when including summary.
88
+ """
89
+ super().__init__()
90
+
91
+ if isinstance(model, str):
92
+ model = init_chat_model(model)
93
+
94
+ self.model = model
95
+ self.max_tokens_before_summary = max_tokens_before_summary
96
+ self.messages_to_keep = messages_to_keep
97
+ self.token_counter = token_counter
98
+ self.summary_prompt = summary_prompt
99
+ self.summary_prefix = summary_prefix
100
+
101
+ def before_model(self, state: AgentState) -> dict[str, Any] | None:
102
+ """Process messages before model invocation, potentially triggering summarization."""
103
+ messages = state["messages"]
104
+ self._ensure_message_ids(messages)
105
+
106
+ total_tokens = self.token_counter(messages)
107
+ if (
108
+ self.max_tokens_before_summary is not None
109
+ and total_tokens < self.max_tokens_before_summary
110
+ ):
111
+ return None
112
+
113
+ cutoff_index = self._find_safe_cutoff(messages)
114
+
115
+ if cutoff_index <= 0:
116
+ return None
117
+
118
+ messages_to_summarize, preserved_messages = self._partition_messages(messages, cutoff_index)
119
+
120
+ summary = self._create_summary(messages_to_summarize)
121
+ new_messages = self._build_new_messages(summary)
122
+
123
+ return {
124
+ "messages": [
125
+ RemoveMessage(id=REMOVE_ALL_MESSAGES),
126
+ *new_messages,
127
+ *preserved_messages,
128
+ ]
129
+ }
130
+
131
+ def _build_new_messages(self, summary: str) -> list[HumanMessage]:
132
+ return [
133
+ HumanMessage(content=f"Here is a summary of the conversation to date:\n\n{summary}")
134
+ ]
135
+
136
+ def _ensure_message_ids(self, messages: list[AnyMessage]) -> None:
137
+ """Ensure all messages have unique IDs for the add_messages reducer."""
138
+ for msg in messages:
139
+ if msg.id is None:
140
+ msg.id = str(uuid.uuid4())
141
+
142
+ def _partition_messages(
143
+ self,
144
+ conversation_messages: list[AnyMessage],
145
+ cutoff_index: int,
146
+ ) -> tuple[list[AnyMessage], list[AnyMessage]]:
147
+ """Partition messages into those to summarize and those to preserve."""
148
+ messages_to_summarize = conversation_messages[:cutoff_index]
149
+ preserved_messages = conversation_messages[cutoff_index:]
150
+
151
+ return messages_to_summarize, preserved_messages
152
+
153
+ def _find_safe_cutoff(self, messages: list[AnyMessage]) -> int:
154
+ """Find safe cutoff point that preserves AI/Tool message pairs.
155
+
156
+ Returns the index where messages can be safely cut without separating
157
+ related AI and Tool messages. Returns 0 if no safe cutoff is found.
158
+ """
159
+ if len(messages) <= self.messages_to_keep:
160
+ return 0
161
+
162
+ target_cutoff = len(messages) - self.messages_to_keep
163
+
164
+ for i in range(target_cutoff, -1, -1):
165
+ if self._is_safe_cutoff_point(messages, i):
166
+ return i
167
+
168
+ return 0
169
+
170
+ def _is_safe_cutoff_point(self, messages: list[AnyMessage], cutoff_index: int) -> bool:
171
+ """Check if cutting at index would separate AI/Tool message pairs."""
172
+ if cutoff_index >= len(messages):
173
+ return True
174
+
175
+ search_start = max(0, cutoff_index - _SEARCH_RANGE_FOR_TOOL_PAIRS)
176
+ search_end = min(len(messages), cutoff_index + _SEARCH_RANGE_FOR_TOOL_PAIRS)
177
+
178
+ for i in range(search_start, search_end):
179
+ if not self._has_tool_calls(messages[i]):
180
+ continue
181
+
182
+ tool_call_ids = self._extract_tool_call_ids(cast("AIMessage", messages[i]))
183
+ if self._cutoff_separates_tool_pair(messages, i, cutoff_index, tool_call_ids):
184
+ return False
185
+
186
+ return True
187
+
188
+ def _has_tool_calls(self, message: AnyMessage) -> bool:
189
+ """Check if message is an AI message with tool calls."""
190
+ return (
191
+ isinstance(message, AIMessage) and hasattr(message, "tool_calls") and message.tool_calls # type: ignore[return-value]
192
+ )
193
+
194
+ def _extract_tool_call_ids(self, ai_message: AIMessage) -> set[str]:
195
+ """Extract tool call IDs from an AI message."""
196
+ tool_call_ids = set()
197
+ for tc in ai_message.tool_calls:
198
+ call_id = tc.get("id") if isinstance(tc, dict) else getattr(tc, "id", None)
199
+ if call_id is not None:
200
+ tool_call_ids.add(call_id)
201
+ return tool_call_ids
202
+
203
+ def _cutoff_separates_tool_pair(
204
+ self,
205
+ messages: list[AnyMessage],
206
+ ai_message_index: int,
207
+ cutoff_index: int,
208
+ tool_call_ids: set[str],
209
+ ) -> bool:
210
+ """Check if cutoff separates an AI message from its corresponding tool messages."""
211
+ for j in range(ai_message_index + 1, len(messages)):
212
+ message = messages[j]
213
+ if isinstance(message, ToolMessage) and message.tool_call_id in tool_call_ids:
214
+ ai_before_cutoff = ai_message_index < cutoff_index
215
+ tool_before_cutoff = j < cutoff_index
216
+ if ai_before_cutoff != tool_before_cutoff:
217
+ return True
218
+ return False
219
+
220
+ def _create_summary(self, messages_to_summarize: list[AnyMessage]) -> str:
221
+ """Generate summary for the given messages."""
222
+ if not messages_to_summarize:
223
+ return "No previous conversation history."
224
+
225
+ trimmed_messages = self._trim_messages_for_summary(messages_to_summarize)
226
+ if not trimmed_messages:
227
+ return "Previous conversation was too long to summarize."
228
+
229
+ try:
230
+ response = self.model.invoke(self.summary_prompt.format(messages=trimmed_messages))
231
+ return cast("str", response.content).strip()
232
+ except Exception as e: # noqa: BLE001
233
+ return f"Error generating summary: {e!s}"
234
+
235
+ def _trim_messages_for_summary(self, messages: list[AnyMessage]) -> list[AnyMessage]:
236
+ """Trim messages to fit within summary generation limits."""
237
+ try:
238
+ return trim_messages(
239
+ messages,
240
+ max_tokens=_DEFAULT_TRIM_TOKEN_LIMIT,
241
+ token_counter=self.token_counter,
242
+ start_on="human",
243
+ strategy="last",
244
+ allow_partial=True,
245
+ include_system=True,
246
+ )
247
+ except Exception: # noqa: BLE001
248
+ return messages[-_DEFAULT_FALLBACK_MESSAGE_COUNT:]