> ## Documentation Index
> Fetch the complete documentation index at: https://simplellmfunc.cn/llms.txt
> Use this file to discover all available pages before exploring further.

# 装饰器

> @llm_function、@llm_chat 和 @tool 的 API 参考

# 装饰器 API 参考

## @llm\_function

```python theme={null}
from SimpleLLMFunc import llm_function

@llm_function(
    llm_interface: LLM_Interface,
    toolkit: Optional[List[Tool]] = None,
    max_tool_calls: Optional[int] = None,
    system_prompt_template: Optional[str] = None,
    user_prompt_template: Optional[str] = None,
    **llm_kwargs: Any,
)
```

将一个异步函数转换为 `LLMFunction` callable instance。`await fn(...)` 返回解析后的类型化结果；`fn.stream(...)` 产出 `ReactOutput`。

对于多模态输入，`llm_function` 保持普通 Python 函数风格：显式把图片参数标注为 `ImgUrl`、`ImgPath`，或包含这些类型的列表/Union。`ImgUrl` 支持 `http(s)` URL 与 `data:` URL；`ImgPath` 会在 provider 边界编码为图片 data URL。

### 参数

| 参数                       | 类型                   | 默认值    | 描述                                     |
| ------------------------ | -------------------- | ------ | -------------------------------------- |
| `llm_interface`          | `LLM_Interface`      | 必填     | 要调用的模型                                 |
| `toolkit`                | `List[Tool] \| None` | `None` | 模型可用的工具列表                              |
| `max_tool_calls`         | `int \| None`        | `None` | 强制返回最终答案前的最大工具调用次数。`None` = 无限制        |
| `system_prompt_template` | `str \| None`        | `None` | 覆盖系统提示词模板                              |
| `user_prompt_template`   | `str \| None`        | `None` | 覆盖用户提示词模板                              |
| `**llm_kwargs`           | `Any`                | —      | 转发给 LLM 的参数（temperature、max\_tokens 等） |

### 特殊调用时参数

| 参数                 | 类型               | 描述                  |
| ------------------ | ---------------- | ------------------- |
| `_template_params` | `Dict[str, Any]` | 文档字符串中 `{占位符}` 的模板值 |
| `_abort_signal`    | `AbortSignal`    | 取消信号                |

### 示例

```python theme={null}
from pydantic import BaseModel, Field
from SimpleLLMFunc import llm_function, OpenAICompatible

llm = OpenAICompatible.load_from_json_file("provider.json")["openrouter"]["gpt-4o"]

class Sentiment(BaseModel):
    label: str = Field(description="positive, negative, or neutral")
    score: float = Field(description="confidence 0.0–1.0")

@llm_function(llm_interface=llm)
async def classify(text: str) -> Sentiment:
    """Classify the sentiment of the text."""
    pass

# Usage
result = await classify("I love this!")
print(result)  # Sentiment(label="positive", score=0.95)
```

***

## @llm\_chat

```python theme={null}
from SimpleLLMFunc import llm_chat

@llm_chat(
    llm_interface: LLM_Interface,
    toolkit: Optional[List[Tool]] = None,
    max_tool_calls: Optional[int] = DEFAULT_MAX_TOOL_CALLS,
    stream: bool = False,
    strict_signature: bool = False,
    self_reference: Optional[SelfReference] = None,
    self_reference_key: Optional[str] = None,
    **llm_kwargs: Any,
)
```

创建一个 `LLMChat` callable instance。调用它会产出 `AsyncGenerator[ReactOutput, None]`，并为 SelfRef 提供稳定的 agent identity。

对于多模态 chat 输入，推荐使用单个显式的 `message: UserChatMessage` 参数。`UserChatMessage` 兼容 OpenAI Chat Completions user message，可以包含 text 与 `image_url` content parts。

### 参数

| 参数                   | 类型                      | 默认值     | 描述                      |
| -------------------- | ----------------------- | ------- | ----------------------- |
| `llm_interface`      | `LLM_Interface`         | 必填      | 要调用的模型                  |
| `toolkit`            | `List[Tool] \| None`    | `None`  | 可用的工具列表                 |
| `max_tool_calls`     | `int \| None`           | 框架默认值   | 每次调用的工具调用上限             |
| `stream`             | `bool`                  | `False` | 启用流式输出                  |
| `strict_signature`   | `bool`                  | `False` | 强制严格的参数验证               |
| `self_reference`     | `SelfReference \| None` | `None`  | 显式 SelfReference（自引用）后端 |
| `self_reference_key` | `str \| None`           | `None`  | 为此键自动创建 SelfReference   |
| `**llm_kwargs`       | `Any`                   | —       | 转发给 LLM 的参数             |

### 特殊调用时参数

| 参数                  | 类型               | 描述              |
| ------------------- | ---------------- | --------------- |
| `_template_params`  | `Dict[str, Any]` | 模板值             |
| `_abort_signal`     | `AbortSignal`    | 取消信号            |
| `_too_long_to_file` | `bool`           | 将过长的工具结果截断到临时文件 |

### History 参数

函数必须具有名为 `history` 或 `chat_history` 的参数（类型：`list | None`）。框架使用该参数来承载对话状态。

### 示例

```python theme={null}
from SimpleLLMFunc import llm_chat, tool

@tool
async def search(query: str) -> str:
    """Search for information."""
    return f"Result for: {query}"

@llm_chat(llm_interface=llm, toolkit=[search], stream=True)
async def agent(message: str, history: list | None = None):
    """A helpful research assistant."""
    pass

# Usage
history = []
async for output in agent("What is SimpleLLMFunc?", history):
    if is_response_yield(output):
        print(output.response)
        history = output.messages
```

### 多模态 Chat 示例

```python theme={null}
from SimpleLLMFunc import llm_chat
from SimpleLLMFunc.type import UserChatMessage, ImgUrl

@llm_chat(llm_interface=llm)
async def vision_agent(message: UserChatMessage, history: list | None = None):
    """回答用户图片相关的问题。"""
    pass

async for output in vision_agent(
    UserChatMessage.multimodal(
        "这张图里有什么？",
        ImgUrl("https://example.com/cat.jpg", detail="high"),
    ),
    history=[],
):
    ...
```

***

## @tool

```python theme={null}
from SimpleLLMFunc import tool

@tool(
    name: Optional[str] = None,
    description: Optional[str] = None,
    best_practices: Optional[Sequence[str]] = None,
    prompt_injection_builder: Optional[Callable] = None,
    too_long_to_file: bool = False,
)
```

将一个异步函数注册为可被 LLM 调用的工具。可不带参数使用，也可带参数使用。

### 参数

| 参数                         | 类型                      | 默认值     | 描述                      |
| -------------------------- | ----------------------- | ------- | ----------------------- |
| `name`                     | `str \| None`           | 函数名     | 覆盖工具名称                  |
| `description`              | `str \| None`           | 来自文档字符串 | 覆盖工具描述                  |
| `best_practices`           | `Sequence[str] \| None` | 来自文档字符串 | 覆盖最佳实践列表                |
| `prompt_injection_builder` | `Callable \| None`      | `None`  | 动态系统提示词注入               |
| `too_long_to_file`         | `bool`                  | `False` | 将超过 20k token 的结果写入临时文件 |

### 要求

* 被装饰的函数**必须**是 `async def`
* 文档字符串应包含 `Args`、`Returns` 和 `Best Practices` 部分
* 参数类型将成为工具的 JSON schema

### 示例

```python theme={null}
from SimpleLLMFunc import tool

@tool
async def calculate(expression: str) -> float:
    """
    Evaluate a math expression.

    Args:
        expression: Python math expression (e.g., "2 ** 10").

    Returns:
        Numeric result.

    Best Practices:
        - Use Python syntax.
        - Keep expressions simple.
    """
    return float(eval(expression))

# Used without parentheses (simple form)
@tool
async def simple_tool(x: str) -> str:
    """Do something."""
    return x.upper()
```

***

## Tool 类

```python theme={null}
from SimpleLLMFunc import Tool

tool_instance = Tool(
    name: str,
    description: str,
    func: Callable[..., Awaitable[Any]],
    best_practices: Optional[Sequence[str]] = None,
    prompt_injection_builder: Optional[Callable] = None,
    too_long_to_file: bool = False,
)
```

用于不使用装饰器的方式以编程方式创建工具。

### 方法

| 方法                                        | 返回值           | 描述             |
| ----------------------------------------- | ------------- | -------------- |
| `.tool_spec()`                            | `Dict`        | 工具规格字典         |
| `.to_openai_tool()`                       | `Dict`        | OpenAI 格式的工具定义 |
| `.serialize_tools(tools)`                 | `List[Dict]`  | 类方法：序列化工具列表    |
| `.build_system_prompt_injection(context)` | `str \| None` | 动态提示词注入        |

### 属性

| 属性             | 类型                | 描述      |
| -------------- | ----------------- | ------- |
| `.name`        | `str`             | 工具名称    |
| `.description` | `str`             | 工具描述    |
| `.parameters`  | `List[Parameter]` | 提取的参数列表 |
| `.func`        | `Callable`        | 底层异步函数  |
