248
f'Add a docstring to "{fn.__name__}" or pass description=...'
249
)
250
251
- # Infer input_params from type annotation
251
+ # Validate and infer function signature.
252
+ # Accepted shapes (consistent with TS CustomToolExecuteFn):
253
+ # (input: BaseModel) — no session context needed
254
+ # (input: BaseModel, ctx) — with session context
255
+ # The first param MUST be annotated with a BaseModel subclass.
256
sig = inspect.signature(fn)
257
params = list(sig.parameters.values())
254
- input_params: t.Optional[t.Type[BaseModel]] = None
255
- for p in params:
256
- if p.annotation is not inspect.Parameter.empty:
257
- ann = p.annotation
258
- if isinstance(ann, type) and issubclass(ann, BaseModel):
259
- input_params = ann
260
- break
261
-
262
- if input_params is None:
258
+
259
+ if not params:
260
raise ValidationError(
264
- f'experimental.tool: could not infer input parameters for "{fn.__name__}". '
265
- f"Annotate a parameter with a Pydantic BaseModel subclass, e.g. "
261
+ f'experimental.tool: "{fn.__name__}" must accept at least one parameter '
262
+ f"annotated with a Pydantic BaseModel subclass, e.g. "
263
f"def {fn.__name__}(input: MyInput, ctx): ..."
264
)
265
266
+ if len(params) > 2:
267
+ raise ValidationError(
268
+ f'experimental.tool: "{fn.__name__}" accepts {len(params)} parameters, '
269
+ f"but custom tools accept at most 2: (input: BaseModel, ctx). "
270
+ f"Extra parameters will not be populated at runtime."
271
+ )
272
+
273
+ # First param must be the input model
274
+ first = params[0]
275
+ if first.annotation is inspect.Parameter.empty or not (
276
+ isinstance(first.annotation, type) and issubclass(first.annotation, BaseModel)
277
+ ):
278
+ raise ValidationError(
279
+ f'experimental.tool: first parameter of "{fn.__name__}" must be annotated '
280
+ f"with a Pydantic BaseModel subclass. Got: {first.annotation!r}. "
281
+ f"Expected: def {fn.__name__}(input: MyInput, ctx): ..."
282
+ )
283
+ input_params: t.Type[BaseModel] = first.annotation
284
+
285
# Wrap function to match CustomToolExecuteFn: (input, ctx) -> dict
270
- # Support both (input) and (input, ctx) signatures
271
- num_params = len(params)
272
- if num_params <= 1:
286
+ if len(params) == 1:
287
288
def execute(input: t.Any, ctx: t.Any) -> t.Dict[str, t.Any]:
289
return fn(input)