|
| 1 | +from __future__ import annotations |
| 2 | + |
| 3 | +import inspect |
| 4 | +from abc import ABC, abstractmethod |
| 5 | +from functools import partial |
| 6 | +from typing import Any, Callable, Dict, Type |
| 7 | + |
| 8 | +from pydantic import BaseModel, Field, create_model |
| 9 | + |
| 10 | + |
| 11 | +class BaseTool(ABC): |
| 12 | + """Abstract base class for all QuantMind tools. |
| 13 | +
|
| 14 | + A tool self-describes its capability via a name, description, and a Pydantic |
| 15 | + input schema, and exposes an async `run` that validates inputs before execution. |
| 16 | + """ |
| 17 | + |
| 18 | + @property |
| 19 | + @abstractmethod |
| 20 | + def name(self) -> str: |
| 21 | + """Unique name used by an LLM to invoke this tool.""" |
| 22 | + |
| 23 | + @property |
| 24 | + @abstractmethod |
| 25 | + def description(self) -> str: |
| 26 | + """Human-readable description of the tool for LLM selection.""" |
| 27 | + |
| 28 | + @property |
| 29 | + @abstractmethod |
| 30 | + def args_schema(self) -> Type[BaseModel]: |
| 31 | + """Pydantic model describing required/optional input arguments.""" |
| 32 | + |
| 33 | + @abstractmethod |
| 34 | + async def _arun(self, **kwargs: Any) -> Any: |
| 35 | + """Core async execution logic for the tool (implemented by subclasses).""" |
| 36 | + |
| 37 | + async def run(self, **kwargs: Any) -> Any: |
| 38 | + """Validate inputs against schema, then execute the tool asynchronously.""" |
| 39 | + validated = self.args_schema(**kwargs) |
| 40 | + return await self._arun(**validated.model_dump()) |
| 41 | + |
| 42 | + def to_openai_schema(self) -> Dict[str, Any]: |
| 43 | + """Return schema compatible with OpenAI function calling tools.""" |
| 44 | + return { |
| 45 | + "type": "function", |
| 46 | + "function": { |
| 47 | + "name": self.name, |
| 48 | + "description": self.description, |
| 49 | + "parameters": self.args_schema.model_json_schema(), |
| 50 | + }, |
| 51 | + } |
| 52 | + |
| 53 | + |
| 54 | +class FunctionTool(BaseTool): |
| 55 | + """Wrap a Python callable as a QuantMind tool. |
| 56 | +
|
| 57 | + The callable may be sync or async. Sync functions are executed in a thread |
| 58 | + pool to avoid blocking the event loop. |
| 59 | + """ |
| 60 | + |
| 61 | + def __init__( |
| 62 | + self, |
| 63 | + fn: Callable[..., Any], |
| 64 | + name: str, |
| 65 | + description: str, |
| 66 | + args_schema: Type[BaseModel], |
| 67 | + ) -> None: |
| 68 | + self._fn = fn |
| 69 | + self._name = name |
| 70 | + self._description = description |
| 71 | + self._args_schema = args_schema |
| 72 | + |
| 73 | + @property |
| 74 | + def name(self) -> str: # type: ignore[override] |
| 75 | + return self._name |
| 76 | + |
| 77 | + @property |
| 78 | + def description(self) -> str: # type: ignore[override] |
| 79 | + return self._description |
| 80 | + |
| 81 | + @property |
| 82 | + def args_schema(self) -> Type[BaseModel]: # type: ignore[override] |
| 83 | + return self._args_schema |
| 84 | + |
| 85 | + async def _arun(self, **kwargs: Any) -> Any: # type: ignore[override] |
| 86 | + if inspect.iscoroutinefunction(self._fn): |
| 87 | + return await self._fn(**kwargs) # type: ignore[misc] |
| 88 | + # For sync functions, run in a thread pool |
| 89 | + import asyncio |
| 90 | + |
| 91 | + loop = asyncio.get_running_loop() |
| 92 | + return await loop.run_in_executor(None, partial(self._fn, **kwargs)) |
| 93 | + |
| 94 | + |
| 95 | +def _build_args_schema_from_signature( |
| 96 | + fn: Callable[..., Any], |
| 97 | +) -> Type[BaseModel]: |
| 98 | + """Create a Pydantic model from a function's signature. |
| 99 | +
|
| 100 | + Parameters without annotations default to `Any`. All parameters are required |
| 101 | + unless a default value exists on the function. |
| 102 | + """ |
| 103 | + sig = inspect.signature(fn) |
| 104 | + fields: Dict[str, tuple[Any, Any]] = {} |
| 105 | + |
| 106 | + for param in sig.parameters.values(): |
| 107 | + if param.kind in (param.VAR_POSITIONAL, param.VAR_KEYWORD): |
| 108 | + # Skip variadic params for schema simplicity |
| 109 | + continue |
| 110 | + |
| 111 | + annotation = ( |
| 112 | + param.annotation if param.annotation is not inspect._empty else Any |
| 113 | + ) |
| 114 | + |
| 115 | + # Required if no default, else use default |
| 116 | + if param.default is inspect._empty: |
| 117 | + default = Field(..., description=f"Parameter for {param.name}") |
| 118 | + else: |
| 119 | + default = Field( |
| 120 | + default=param.default, description=f"Parameter for {param.name}" |
| 121 | + ) |
| 122 | + |
| 123 | + fields[param.name] = (annotation, default) |
| 124 | + |
| 125 | + model_name = f"{fn.__name__.capitalize()}Inputs" |
| 126 | + return create_model(model_name, **fields) # type: ignore[return-value] |
| 127 | + |
| 128 | + |
| 129 | +def tool(fn: Callable[..., Any]) -> BaseTool: |
| 130 | + """Decorator that converts a function into a QuantMind Tool. |
| 131 | +
|
| 132 | + The function's docstring becomes the description; its signature and type |
| 133 | + annotations define the input schema. Returns a `FunctionTool` instance. |
| 134 | + """ |
| 135 | + docstring = inspect.getdoc(fn) |
| 136 | + if not docstring: |
| 137 | + raise ValueError( |
| 138 | + "Tool function must have a docstring for its description." |
| 139 | + ) |
| 140 | + |
| 141 | + description = docstring.strip() |
| 142 | + name = fn.__name__ |
| 143 | + args_schema = _build_args_schema_from_signature(fn) |
| 144 | + return FunctionTool( |
| 145 | + fn=fn, name=name, description=description, args_schema=args_schema |
| 146 | + ) |
0 commit comments