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 | class FunctionTool(AsyncBaseTool):
"""Function Tool.
A tool that takes in a function and optionally handles workflow context.
"""
def __init__(
self,
fn: Optional[Callable[..., Any]] = None,
metadata: Optional[ToolMetadata] = None,
async_fn: Optional[AsyncCallable] = None,
) -> None:
if fn is None and async_fn is None:
raise ValueError("fn must be provided")
# If async_fn is provided explicitly, use it. Otherwise check if fn is async
if async_fn is not None:
self._async_fn = async_fn
self._fn = fn or async_to_sync(async_fn)
else:
assert fn is not None
if inspect.iscoroutinefunction(fn):
self._async_fn = fn
self._fn = async_to_sync(fn)
else:
self._fn = fn
self._async_fn = sync_to_async(fn)
# Determine if function requires context by inspecting signature
fn_to_inspect = fn or async_fn
assert fn_to_inspect is not None
sig = inspect.signature(fn_to_inspect)
self.requires_context = any(
param.annotation == Context for param in sig.parameters.values()
)
if metadata is None:
raise ValueError("metadata must be provided")
self._metadata = metadata
@classmethod
def from_defaults(
cls,
fn: Optional[Callable[..., Any]] = None,
name: Optional[str] = None,
description: Optional[str] = None,
return_direct: bool = False,
fn_schema: Optional[Type[BaseModel]] = None,
async_fn: Optional[AsyncCallable] = None,
tool_metadata: Optional[ToolMetadata] = None,
) -> "FunctionTool":
if tool_metadata is None:
fn_to_parse = fn or async_fn
assert fn_to_parse is not None, "fn must be provided"
name = name or fn_to_parse.__name__
docstring = fn_to_parse.__doc__
# Get function signature
fn_sig = inspect.signature(fn_to_parse)
# Remove ctx parameter from schema if present
has_ctx = any(
param.annotation == Context for param in fn_sig.parameters.values()
)
ctx_param_name = None
if has_ctx:
ctx_param_name = next(
param.name
for param in fn_sig.parameters.values()
if param.annotation == Context
)
fn_sig = fn_sig.replace(
parameters=[
param
for param in fn_sig.parameters.values()
if param.annotation != Context
]
)
# Handle FieldInfo defaults
fn_sig = fn_sig.replace(
parameters=[
param.replace(default=inspect.Parameter.empty)
if isinstance(param.default, FieldInfo)
else param
for param in fn_sig.parameters.values()
]
)
description = description or f"{name}{fn_sig}\n{docstring}"
if fn_schema is None:
fn_schema = create_schema_from_function(
f"{name}",
fn_to_parse,
additional_fields=None,
ignore_fields=[ctx_param_name]
if ctx_param_name is not None
else None,
)
tool_metadata = ToolMetadata(
name=name,
description=description,
fn_schema=fn_schema,
return_direct=return_direct,
)
return cls(
fn=fn,
metadata=tool_metadata,
async_fn=async_fn,
)
@property
def metadata(self) -> ToolMetadata:
"""Metadata."""
return self._metadata
@property
def fn(self) -> Callable[..., Any]:
"""Function."""
return self._fn
@property
def async_fn(self) -> AsyncCallable:
"""Async function."""
return self._async_fn
def call(
self, *args: Any, ctx: Optional[Context] = None, **kwargs: Any
) -> ToolOutput:
"""Call."""
if self.requires_context:
if ctx is None:
raise ValueError("Context is required for this tool")
tool_output = self._fn(ctx, *args, **kwargs)
else:
tool_output = self._fn(*args, **kwargs)
return ToolOutput(
content=str(tool_output),
tool_name=self.metadata.name,
raw_input={"args": args, "kwargs": kwargs},
raw_output=tool_output,
)
async def acall(
self, *args: Any, ctx: Optional[Context] = None, **kwargs: Any
) -> ToolOutput:
"""Call."""
if self.requires_context:
if ctx is None:
raise ValueError("Context is required for this tool")
tool_output = await self._async_fn(ctx, *args, **kwargs)
else:
tool_output = await self._async_fn(*args, **kwargs)
return ToolOutput(
content=str(tool_output),
tool_name=self.metadata.name,
raw_input={"args": args, "kwargs": kwargs},
raw_output=tool_output,
)
def to_langchain_tool(
self,
**langchain_tool_kwargs: Any,
) -> "Tool":
"""To langchain tool."""
from llama_index.core.bridge.langchain import Tool
langchain_tool_kwargs = self._process_langchain_tool_kwargs(
langchain_tool_kwargs
)
return Tool.from_function(
func=self.fn,
coroutine=self.async_fn,
**langchain_tool_kwargs,
)
def to_langchain_structured_tool(
self,
**langchain_tool_kwargs: Any,
) -> "StructuredTool":
"""To langchain structured tool."""
from llama_index.core.bridge.langchain import StructuredTool
langchain_tool_kwargs = self._process_langchain_tool_kwargs(
langchain_tool_kwargs
)
return StructuredTool.from_function(
func=self.fn,
coroutine=self.async_fn,
**langchain_tool_kwargs,
)
|