跳转到主要内容

Documentation Index

Fetch the complete documentation index at: https://simplellmfunc.cn/llms.txt

Use this file to discover all available pages before exploring further.

装饰器 API 参考

@llm_function

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_interfaceLLM_Interface必填要调用的模型
toolkitList[Tool] | NoneNone模型可用的工具列表
max_tool_callsint | NoneNone强制返回最终答案前的最大工具调用次数。None = 无限制
system_prompt_templatestr | NoneNone覆盖系统提示词模板
user_prompt_templatestr | NoneNone覆盖用户提示词模板
**llm_kwargsAny转发给 LLM 的参数(temperature、max_tokens 等)

特殊调用时参数

参数类型描述
_template_paramsDict[str, Any]文档字符串中 {占位符} 的模板值
_abort_signalAbortSignal取消信号

示例

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

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。

参数

参数类型默认值描述
llm_interfaceLLM_Interface必填要调用的模型
toolkitList[Tool] | NoneNone可用的工具列表
max_tool_callsint | None框架默认值每次调用的工具调用上限
streamboolFalse启用流式输出
strict_signatureboolFalse强制严格的参数验证
self_referenceSelfReference | NoneNone显式 SelfReference(自引用)后端
self_reference_keystr | NoneNone为此键自动创建 SelfReference
**llm_kwargsAny转发给 LLM 的参数

特殊调用时参数

参数类型描述
_template_paramsDict[str, Any]模板值
_abort_signalAbortSignal取消信号
_too_long_to_filebool将过长的工具结果截断到临时文件

History 参数

函数必须具有名为 historychat_history 的参数(类型:list | None)。框架使用该参数来承载对话状态。

示例

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

@tool

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 调用的工具。可不带参数使用,也可带参数使用。

参数

参数类型默认值描述
namestr | None函数名覆盖工具名称
descriptionstr | None来自文档字符串覆盖工具描述
best_practicesSequence[str] | None来自文档字符串覆盖最佳实践列表
prompt_injection_builderCallable | NoneNone动态系统提示词注入
too_long_to_fileboolFalse将超过 20k token 的结果写入临时文件

要求

  • 被装饰的函数必须async def
  • 文档字符串应包含 ArgsReturnsBest Practices 部分
  • 参数类型将成为工具的 JSON schema

示例

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 类

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()DictOpenAI 格式的工具定义
.serialize_tools(tools)List[Dict]类方法:序列化工具列表
.build_system_prompt_injection(context)str | None动态提示词注入

属性

属性类型描述
.namestr工具名称
.descriptionstr工具描述
.parametersList[Parameter]提取的参数列表
.funcCallable底层异步函数