Skip to main content

from tool import tool_manager

为什么世界还缺少一个 llm_requests

如果你是一名LLM开发者,你可能遇到过这样的困扰:明明在软件开发领域自己有了一个想法之后可以借助各种开发工具快速搭建一个模型来验证自己的想法或者向别人展示。但是到了LLM开发领域却有许多的脏活需要处理。依据API文档慢慢实现模型请求的代码?好在后来有了API网关解决了这个问题。想快速构建一个应用?似乎LangChain可以解决这个问题,但繁杂的文档却要求你先花一段学习如何使用它。而当你想实现一些特殊需求时,其高度封装的API成为了另一个阻碍。

如果你是一名LLM研究者,你可能遇到过这样的困扰:自己的方法需要在大量的模型上对比大量的方法,可能不同的方法上还要去考虑不同的推理配置对结果的影响,如解码超参数、是否开启推理等。而且pass@k等指标的计算还要求多次重复实验。大模型推理很贵,你希望能够缓存模型的输出结果,以减少实验的消耗。前者需要能够方便地在全局设置LLM请求的一些参数,后者需要一个工具来管理模型的输出结果。

——在LangChain之下、LLM网关之上,LLM开发领域似乎还缺少一个类似requests的工具,它仅仅封装模型请求的脏活累活,而把其他一些内容暴露给使用者,使开发者能够在其之上便捷地构建下游应用。

于是便有了llm_requests。它通过以请求体为中心的设计,把模型(Model)、推理平台(Infrastructure)、推理设置(policy)和推理参数(Params)作为一等公民,让使用者能够在不同的对象间自由组合、快速配置。

安装

pip install llm-requests

Quick Start

在模型请求前,请在当前工作目录的 .config/llmrequest/{infra-name}.json 中配置请求地址和 API Key:

{
    "api_key": "none",
    "base_url": "http://127.0.0.1:8080/"
}

例如,infra_name="llama.cpp" 对应 .config/llmrequest/llama.cpp.json。

单次请求

from llm_requests import LLMRequester
from llm_requests.infras.deepseek import deepseek_v4_1_flash

requester = LLMRequester()
print(requester.request(deepseek_v4_1_flash, "介绍一下你自己。"))

批次请求

批次请求用于并行进行多次请求,并行度取决于平台支持的上限。此外,为了防止重复请求,该方式可以接收一个缓存文件。 当缓存文件中包含当次请求的输入和参数时直接调用缓存的结果。

from llm_requests import LLMRequester
from llm_requests.infras.deepseek import deepseek_v4_1_flash

requester = LLMRequester()
results = requester.request_batch(
    deepseek_v4_1_flash,
    "介绍一下你自己。",
    batch_size=3,
    cachefile=".test.json",
)
print(results[0].output)

我们把模型的输出结果封装在了LLMRequestResult类中,它包含一次推理涉及的所有信息:

model: Model(name='gemma4-e2b', infra_name='llama.cpp', released_date='2026-04-02', support_reasoning=True, inference_params=InferenceParams(enable_reason=True, max_tokens=20000, reasoning_effort=1))
contexts: [{'role': 'system', 'content': 'You are a helpful assistant.'}, {'role': 'user', 'content': [{'type': 'text', 'text': '介绍一下你自己。'}]}]
output: 您好!很高兴向您介绍我自己。 ...
input_length: 20
output_length: 627
reasoning_output: Thinking Process:  ...
reasoning_length: 0
inference_time: 11.822667500004172
is_ooc: False
is_stop_by_length: False
appendix: {}
tool_calls: list
contents: OutContentBlock

自定义模型

我们在每个推理设施中封装了一些常用的模型。除此之外,我们还提供自定义模型:

from llm_requests import LLMRequester, Model, InferenceParams

inference_params = InferenceParams(enable_reason=True, max_tokens=2)
model = Model(
    name="deepseek-flash",
    infra_name="deepseek",
    released_date="2026-04-02",
    support_reasoning=True,
    inference_params=inference_params,
)
requester = LLMRequester()
print(requester.request(model, "介绍一下你自己。"))

name 是推理平台实际接收的模型名,infra_name 用于定位对应的配置文件和 Infrastructure 实现,三者需要保持一致。

结构化输出

可以把 Pydantic 模型同时作为输出 Schema 和提示词约束传给 request_content()。 OutputSchemaBlock 会把字段说明加入提示词,output_schema 则会要求支持的 推理设施使用 JSON Schema 约束模型输出:

from llm_requests import contents, StreamLLMRequester
from llm_requests.infras.deepseek import deepseek_v4_1_flash
from pydantic import BaseModel, Field

class DescriptionScreen(BaseModel):
    window_title: str = Field(description="窗口的完整标题")
    description: str = Field(description="对屏幕内容的简要概括")

requester = StreamLLMRequester()

contents = [
    contents.ImageContentBlock("D:\\test.png"),
    contents.TextContentBlock("请描述一下这个图片。"),
    contents.OutputSchemaBlock(DescriptionScreen)
]
print(requester.request_content(deepseek_v4_1_flash, contents=contents))

注意:对于JSON约束的支持受对应平台的限制。对于本地推理(llamacpp)保证严格遵循JSON语法,对于云端推理则需要参考平台的支持情况。

流式输出

StreamLLMRequester 通过 OutContentSplitter 实时下发思考与正文增量, 流结束后仍返回完整的 LLMRequestResult:

from llm_requests import StreamLLMRequester
from llm_requests.infras.deepseek import deepseek_v4_1_flash
from llm_requests.out_contents import OutContentSplitter, OutContentType


def print_delta(kind: OutContentType, delta: str) -> None:
    if kind in (OutContentType.thinking, OutContentType.text):
        print(delta, end="", flush=True)


splitter = OutContentSplitter(delta_sink=print_delta)
requester = StreamLLMRequester(splitter)
result = requester.request(deepseek_v4_1_flash, "介绍一下你自己。")

Callback

Callback 用于对模型输出做后处理,返回值会写入 LLMRequestResult.appendix。可以借此完成结果评分、用量统计或内容审查。 回调返回字典时,字典键必须包含在 @register_callback(...) 注册的标签中。 例如,当模型在输出代码块时会包含```时,可以利用Callback移除包裹文本:

from llm_requests import contents, StreamLLMRequester, register_callback, LLMRequestResult
from llm_requests.infras.deepseek import deepseek_v4_1_flash
from pydantic import BaseModel, Field

from llm_requests.utils import extract_code_block
from llm_requests.out_contents import OutContentSplitter, OutContentType


def print_delta(kind: OutContentType, delta: str) -> None:
    if kind in (OutContentType.thinking, OutContentType.text):
        print(delta, end="", flush=True)

@register_callback("code")
def extract_code(r: LLMRequestResult) -> dict:
    return {"code": extract_code_block(r.output)}

class DescriptionScreen(BaseModel):
    window_title: str = Field(description="窗口的完整标题")
    description: str = Field(description="对屏幕内容的简要概括")

splitter = OutContentSplitter(delta_sink=print_delta)
requester = StreamLLMRequester(splitter, callbacks=[extract_code])

contents = [
    contents.ImageContentBlock("D:\\test.png"),
    contents.TextContentBlock("请描述一下这个图片。"),
    contents.OutputSchemaBlock(DescriptionScreen)
]
print(requester.request_content(deepseek_v4_1_flash, contents=contents))

全局开关

全局开关适合设置一些无法逐次透传的参数,例如 LLMRequester 已经被上层框架 封装时。requests_allow_real=False 会禁止真实网络请求,适合离线复跑已有缓存 或进行严格的测试:

from llm_requests import LLMRequester
from llm_requests.dtypes import NotAllowedRequestError
from llm_requests.infras.deepseek import deepseek_v4_1_flash
from llm_requests.policy import change_policy

requester = LLMRequester()
with change_policy(requests_allow_real=False):
    try:
        requester.requrest(deepseek_v4_1_flash, "请你介绍一下你自己。")
    except NotAllowedRequestError:
        print("本次请求未命中缓存,已阻止真实网络请求。")

当前可配置项包括请求开关、静默模式、并行度、批量与 Callback 进度条、 Callback 重算、上下文超限处理和工具调用日志等,详见 llm_requests.policy.RequestPolicy。

工具调用

框架支持调用Callable对象作为工具。通过 ToolManager 注入工具,并可用 log_tool_calls 查看模型返回的工具调用和实际调用的工具名称:

from llm_requests import LLMRequester
from llm_requests.infras.deepseek import deepseek_v4_1_flash
from llm_requests.dtypes import ToolParams
from llm_requests.policy import change_policy
from llm_requests.tool.tools import ask, print_to
from llm_requests.tool import ToolManager

requester = LLMRequester()
tool_params = ToolParams()
tool_manager = ToolManager(tools=[print_to, ask])
with change_policy(log_tool_calls=True):
    result = requester.request(
        deepseek_v4_1_flash,
        "请先显示“你好”,再询问我的名字。",
        tool_params=tool_params, tool_manager=tool_manager
    )

ToolParams.max_tool_calls 控制一轮请求中最多执行多少次工具调用,默认 -1 表示持续执行,直到模型不再请求工具。

MCP 工具

通过 MCPManager 可以连接 MCP Server,把远端工具和本地 LangChain 工具一起 交给模型。MCP 连接按需建立,工具列表在 Manager 生命周期内缓存。

上下文式

上下文退出时会自动关闭 MCP 连接:

from llm_requests import LLMRequester
from llm_requests.infras.deepseek import deepseek_v4_1_flash
from llm_requests.mcp_manager import MCPManager

requester = LLMRequester()
with MCPManager("https://example.com/mcp"):
    result = requester.request(
        deepseek_v4_1_flash,
        "请使用可用的工具完成任务。",
    )

显式式

显式传入的 Manager 优先于上下文 Manager,并由调用方负责关闭:

from llm_requests import LLMRequester
from llm_requests.infras.deepseek import deepseek_v4_1_flash
from llm_requests.mcp_manager import MCPManager

mcp_manager = MCPManager("https://example.com/mcp")
requester = LLMRequester()

try:
    result = requester.request(
        deepseek_v4_1_flash,
        "请使用可用的工具完成任务。",
        mcp_manager=mcp_manager,
    )
finally:
    mcp_manager.close()

MCP 工具和 ToolParams 中的本地工具可以同时使用;如果名称冲突, LLMRequester 会抛出 ValueError,避免工具路由产生歧义。

当前 MCP 能力支持无需认证的 Streamable HTTP Server、工具发现和工具调用, 可用于 request() 与 request_content()。暂不支持 stdio Transport、 认证、Resources、Prompts、Sampling、动态工具列表以及 request_batch() 中的 MCP 调用。

添加推理平台

推理平台抽象为 Infrastructure。新增平台时,继承该类并实现 msg_request_route(),然后通过 register_infrastructure() 注册唯一的 infra_name。平台适配器负责:

  • 将推理参数、工具定义和可选的输出 Schema 转换为平台请求。
  • 把回复、推理内容、Token 用量、耗时和工具调用封装为 LLMRequestResult。
  • 在需要时覆盖 build_contents() 和 parallel_degree()。

可以参考 llm_requests.infras.llamacpp 与 llm_requests.infras.deepseek。配置文件名必须与模型的 infra_name 一致,例如:

.config/llmrequest/llama.cpp.json
.config/llmrequest/deepseek.json

内容块与多模态输入

内容块位于 llm_requests.contents,用于统一文本、图片、音频和视频输入。 图片、音频和视频内容块接收本地文件路径,并在创建时检查文件是否存在:

from llm_requests import LLMRequester, contents
from llm_requests.infras.llamacpp import gemma4_e2b

requester = LLMRequester()
result = requester.request_content(
    gemma4_e2b,
    contents=[
        contents.SystemContentBlock(),
        contents.TextContentBlock("请描述这张图片。"),
        contents.ImageContentBlock("D:/example/image.png"),
    ],
)
print(result.output)

可用类型:

  • SystemContentBlock:系统提示词。
  • TextContentBlock:普通文本。
  • ImageContentBlock:本地图片。
  • AudioContentBlock:本地音频。
  • VidioContentBlock:本地视频。
  • OutputSchemaBlock:把 Pydantic 字段说明加入提示词。

request() 是单轮文本请求的快捷方式;需要组合多种内容时使用 request_content()。

Metadata

Release files for llm-requests 1.1.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for llm-requests 1.1.0
File Size Uploaded Provenance Actions
llm_requests-1.1.0.tar.gz 66.4 kB Without provenance Details for llm_requests-1.1.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for llm-requests 1.1.0
File Interpreter ABI Platform Actions
llm_requests-1.1.0-py3-none-any.whl Python 3 none any Details for llm_requests-1.1.0-py3-none-any.whl

Total release size: 122.1 kB

Release files / llm_requests-1.1.0.tar.gz

Download URL llm_requests-1.1.0.tar.gz
Size 66.4 kB
Tags Source
SHA-256 checksum
How to use checksums
18465d848a32d613cc15a3b8594a9fb7bce4f45db59b244770203b7d4b729ad3
BLAKE2b-256 checksum
How to use checksums
762dcbe027c9f8913ac2fcb1c7ee723580be52bb1df8a8c1514bac898b96c8f7
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.13.13

Release files / llm_requests-1.1.0-py3-none-any.whl

Download URL llm_requests-1.1.0-py3-none-any.whl
Size 55.7 kB
Tags Python 3
SHA-256 checksum
How to use checksums
dee269145497fd2a3c4a4ab6962d9ea4ca825bd1e53bf71dcee3be4d04ec0630
BLAKE2b-256 checksum
How to use checksums
dc7aaeffbe546a1335bccf8f0f62a0450748889f3c14342511125e1199905dd3
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.13.13

Security for llm-requests 1.1.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page