-
Notifications
You must be signed in to change notification settings - Fork 21.5k
Expand file tree
/
Copy pathtool.py
More file actions
416 lines (329 loc) · 12.9 KB
/
tool.py
File metadata and controls
416 lines (329 loc) · 12.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
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
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
"""Messages for tools."""
import json
from typing import Any, Literal, cast, overload
from uuid import UUID
from pydantic import Field, model_validator
from typing_extensions import NotRequired, TypedDict, override
from langchain_core.messages import content as types
from langchain_core.messages.base import BaseMessage, BaseMessageChunk, merge_content
from langchain_core.messages.content import InvalidToolCall
from langchain_core.utils._merge import merge_dicts, merge_obj
class ToolOutputMixin:
"""Mixin for objects that tools can return directly.
If a custom BaseTool is invoked with a `ToolCall` and the output of custom code is
not an instance of `ToolOutputMixin`, the output will automatically be coerced to
a string and wrapped in a `ToolMessage`.
"""
class ToolMessage(BaseMessage, ToolOutputMixin):
"""Message for passing the result of executing a tool back to a model.
`ToolMessage` objects contain the result of a tool invocation. Typically, the result
is encoded inside the `content` field.
`tool_call_id` is used to associate the tool call request with the tool call
response. Useful in situations where a chat model is able to request multiple tool
calls in parallel.
Example:
A `ToolMessage` representing a result of `42` from a tool call with id
```python
from langchain_core.messages import ToolMessage
ToolMessage(content="42", tool_call_id="call_Jja7J89XsjrOLA5r!MEOW!SL")
```
Example:
A `ToolMessage` where only part of the tool output is sent to the model
and the full output is passed in to artifact.
```python
from langchain_core.messages import ToolMessage
tool_output = {
"stdout": "From the graph we can see that the correlation between "
"x and y is ...",
"stderr": None,
"artifacts": {"type": "image", "base64_data": "/9j/4gIcSU..."},
}
ToolMessage(
content=tool_output["stdout"],
artifact=tool_output,
tool_call_id="call_Jja7J89XsjrOLA5r!MEOW!SL",
)
```
"""
tool_call_id: str
"""Tool call that this message is responding to."""
type: Literal["tool"] = "tool"
"""The type of the message (used for serialization)."""
artifact: Any = None
"""Artifact of the Tool execution which is not meant to be sent to the model.
Should only be specified if it is different from the message content, e.g. if only
a subset of the full tool output is being passed as message content but the full
output is needed in other parts of the code.
"""
status: Literal["success", "error"] = "success"
"""Status of the tool invocation."""
additional_kwargs: dict = Field(default_factory=dict, repr=False)
"""Currently inherited from `BaseMessage`, but not used."""
response_metadata: dict = Field(default_factory=dict, repr=False)
"""Currently inherited from `BaseMessage`, but not used."""
@model_validator(mode="before")
@classmethod
def coerce_args(cls, values: dict) -> dict:
"""Coerce the model arguments to the correct types.
Args:
values: The model arguments.
"""
content = values["content"]
if isinstance(content, tuple):
content = list(content)
if not isinstance(content, (str, list)):
try:
values["content"] = str(content)
except ValueError as e:
msg = (
"ToolMessage content should be a string or a list of string/dicts. "
f"Received:\n\n{content=}\n\n which could not be coerced into a "
"string."
)
raise ValueError(msg) from e
elif isinstance(content, list):
values["content"] = []
for i, x in enumerate(content):
if not isinstance(x, (str, dict)):
try:
values["content"].append(str(x))
except ValueError as e:
msg = (
"ToolMessage content should be a string or a list of "
"string/dicts. Received a list but "
f"element ToolMessage.content[{i}] is not a dict and could "
f"not be coerced to a string.:\n\n{x}"
)
raise ValueError(msg) from e
else:
values["content"].append(x)
tool_call_id = values["tool_call_id"]
if isinstance(tool_call_id, (UUID, int, float)):
values["tool_call_id"] = str(tool_call_id)
return values
@overload
def __init__(
self,
content: str | list[str | dict],
**kwargs: Any,
) -> None: ...
@overload
def __init__(
self,
content: str | list[str | dict] | None = None,
content_blocks: list[types.ContentBlock] | None = None,
**kwargs: Any,
) -> None: ...
def __init__(
self,
content: str | list[str | dict] | None = None,
content_blocks: list[types.ContentBlock] | None = None,
**kwargs: Any,
) -> None:
"""Initialize a `ToolMessage`.
Specify `content` as positional arg or `content_blocks` for typing.
Args:
content: The contents of the message.
content_blocks: Typed standard content.
**kwargs: Additional fields.
"""
if content_blocks is not None:
super().__init__(
content=cast("str | list[str | dict]", content_blocks),
**kwargs,
)
else:
super().__init__(content=content, **kwargs)
class ToolMessageChunk(ToolMessage, BaseMessageChunk):
"""Tool Message chunk."""
# Ignoring mypy re-assignment here since we're overriding the value
# to make sure that the chunk variant can be discriminated from the
# non-chunk variant.
type: Literal["ToolMessageChunk"] = "ToolMessageChunk" # type: ignore[assignment]
@override
def __add__(self, other: Any) -> BaseMessageChunk: # type: ignore[override]
if isinstance(other, ToolMessageChunk):
if self.tool_call_id != other.tool_call_id:
msg = "Cannot concatenate ToolMessageChunks with different tool_call_ids."
raise ValueError(msg)
return self.__class__(
tool_call_id=self.tool_call_id,
content=merge_content(self.content, other.content),
artifact=merge_obj(self.artifact, other.artifact),
additional_kwargs=merge_dicts(
self.additional_kwargs, other.additional_kwargs
),
response_metadata=merge_dicts(
self.response_metadata, other.response_metadata
),
id=self.id,
status=_merge_status(self.status, other.status),
)
return super().__add__(other)
class ToolCall(TypedDict):
"""Represents an AI's request to call a tool.
Example:
```python
{"name": "foo", "args": {"a": 1}, "id": "123"}
```
This represents a request to call the tool named `'foo'` with arguments
`{"a": 1}` and an identifier of `'123'`.
!!! note "Factory function"
`tool_call` may also be used as a factory to create a `ToolCall`. Benefits
include:
* Required arguments strictly validated at creation time
"""
name: str
"""The name of the tool to be called."""
args: dict[str, Any]
"""The arguments to the tool call as a dictionary."""
id: str | None
"""An identifier associated with the tool call.
An identifier is needed to associate a tool call request with a tool
call result in events when multiple concurrent tool calls are made.
"""
type: NotRequired[Literal["tool_call"]]
"""Used for discrimination."""
def tool_call(
*,
name: str,
args: dict[str, Any],
id: str | None,
) -> ToolCall:
"""Create a tool call.
Args:
name: The name of the tool to be called.
args: The arguments to the tool call as a dictionary.
id: An identifier associated with the tool call.
Returns:
The created tool call.
"""
return ToolCall(name=name, args=args, id=id, type="tool_call")
class ToolCallChunk(TypedDict):
"""A chunk of a tool call (yielded when streaming).
When merging `ToolCallChunk` objects (e.g., via `AIMessageChunk.__add__`), all
string attributes are concatenated. Chunks are only merged if their values of
`index` are equal and not `None`.
Example:
```python
left_chunks = [ToolCallChunk(name="foo", args='{"a":', index=0)]
right_chunks = [ToolCallChunk(name=None, args="1}", index=0)]
(
AIMessageChunk(content="", tool_call_chunks=left_chunks)
+ AIMessageChunk(content="", tool_call_chunks=right_chunks)
).tool_call_chunks == [ToolCallChunk(name="foo", args='{"a":1}', index=0)]
```
"""
name: str | None
"""The name of the tool to be called."""
args: str | None
"""The arguments to the tool call as a JSON-parseable string."""
id: str | None
"""An identifier associated with the tool call.
An identifier is needed to associate a tool call request with a tool
call result in events when multiple concurrent tool calls are made.
"""
index: int | None
"""The index of the tool call in a sequence.
Used for merging chunks.
"""
type: NotRequired[Literal["tool_call_chunk"]]
"""Used for discrimination."""
def tool_call_chunk(
*,
name: str | None = None,
args: str | None = None,
id: str | None = None,
index: int | None = None,
) -> ToolCallChunk:
"""Create a tool call chunk.
Args:
name: The name of the tool to be called.
args: The arguments to the tool call as a JSON string.
id: An identifier associated with the tool call.
index: The index of the tool call in a sequence.
Returns:
The created tool call chunk.
"""
return ToolCallChunk(
name=name, args=args, id=id, index=index, type="tool_call_chunk"
)
def invalid_tool_call(
*,
name: str | None = None,
args: str | None = None,
id: str | None = None,
error: str | None = None,
) -> InvalidToolCall:
"""Create an invalid tool call.
Args:
name: The name of the tool to be called.
args: The arguments to the tool call as a JSON string.
id: An identifier associated with the tool call.
error: An error message associated with the tool call.
Returns:
The created invalid tool call.
"""
return InvalidToolCall(
name=name, args=args, id=id, error=error, type="invalid_tool_call"
)
def default_tool_parser(
raw_tool_calls: list[dict],
) -> tuple[list[ToolCall], list[InvalidToolCall]]:
"""Best-effort parsing of tools.
Args:
raw_tool_calls: List of raw tool call dicts to parse.
Returns:
A list of tool calls and invalid tool calls.
"""
tool_calls = []
invalid_tool_calls = []
for raw_tool_call in raw_tool_calls:
if "function" not in raw_tool_call:
continue
function_name = raw_tool_call["function"]["name"]
try:
function_args = json.loads(raw_tool_call["function"]["arguments"])
parsed = tool_call(
name=function_name or "",
args=function_args or {},
id=raw_tool_call.get("id"),
)
tool_calls.append(parsed)
except json.JSONDecodeError as e:
invalid_tool_calls.append(
invalid_tool_call(
name=function_name,
args=raw_tool_call["function"]["arguments"],
id=raw_tool_call.get("id"),
error=str(e),
)
)
return tool_calls, invalid_tool_calls
def default_tool_chunk_parser(raw_tool_calls: list[dict]) -> list[ToolCallChunk]:
"""Best-effort parsing of tool chunks.
Args:
raw_tool_calls: List of raw tool call dicts to parse.
Returns:
List of parsed ToolCallChunk objects.
"""
tool_call_chunks = []
for tool_call in raw_tool_calls:
if "function" not in tool_call:
function_args = None
function_name = None
else:
function_args = tool_call["function"]["arguments"]
function_name = tool_call["function"]["name"]
parsed = tool_call_chunk(
name=function_name,
args=function_args,
id=tool_call.get("id"),
index=tool_call.get("index"),
)
tool_call_chunks.append(parsed)
return tool_call_chunks
def _merge_status(
left: Literal["success", "error"], right: Literal["success", "error"]
) -> Literal["success", "error"]:
return "error" if "error" in {left, right} else "success"