"""工具定义和上下文"""
from pydantic import BaseModel
from typing import Generic, TypeVar, Callable, Awaitable, Any


class ToolContext(BaseModel):
    """工具执行上下文"""
    session_id: str
    message_id: str
    call_id: str
    metadata: dict[str, Any] = {}


class ToolOutput(BaseModel):
    """工具执行输出"""
    content: str
    metadata: dict[str, Any] = {}


T = TypeVar('T', bound=BaseModel)


class Tool(Generic[T]):
    """工具定义"""

    def __init__(
        self,
        name: str,
        description: str,
        parameters: type[T],
        execute: Callable[[T, ToolContext], Awaitable[ToolOutput]]
    ):
        self.name = name
        self.description = description
        self.parameters = parameters
        self.execute = execute

    def to_openai_schema(self) -> dict:
        """转换为 OpenAI function calling 格式"""
        return {
            "type": "function",
            "function": {
                "name": self.name,
                "description": self.description,
                "parameters": self.parameters.model_json_schema()
            }
        }
