Skip to main content

my-llm-py

PyPI Python License Discord QQ群

通用的 LLM Provider 协议适配器

异步调用 OpenAI Chat Completions、OpenAI Responses、Anthropic Messages、Gemini 和 Ollama。请求使用官方 SDK,输入、输出与流事件采用五种协议的标准字典,不另定义消息类型。 需要 Python 3.12+,不内置厂商或模型清单。

安装

pip install my-llm-py
# 或 uv add my-llm-py

调用

ProviderProfile.protocol 选择上游 API,stdio_protocol 选择调用者的输入输出协议。 两者独立;例如用 Chat 消息调用 Responses API,并继续收到 Chat 消息。

import asyncio
import os
from my_llm import ModelProfile, MyLLM, ProviderProfile

async def main():
    async with MyLLM(
        provider=ProviderProfile(
            protocol="openai_responses",
            api_key=os.environ["OPENAI_API_KEY"],
        ),
        model=ModelProfile(model=os.environ["LLM_MODEL"]),
        stdio_protocol="openai_chat",
    ) as llm:
        message = await llm.generate(messages=[{"role": "user", "content": "你好"}])
        print(message["content"])

asyncio.run(main())

五个协议名为 openai_chat、openai_responses、anthropic、gemini、ollama。 省略 stdio_protocol 时,首次调用从整个 messages/tools 列表识别一次并绑定到实例。 纯文本消息等重叠输入默认使用 openai_chat;需要其他格式时显式指定。 同一实例的 messages 与 tools 使用同一种协议,不混用历史格式。

async def print_answer(llm):
    # 此示例的 llm 使用 stdio_protocol="openai_chat"。
    stream = await llm.generate(
        messages=[{"role": "user", "content": "你好"}], stream=True,
    )
    async with stream:
        async for event in stream:
            for choice in event.get("choices", []):
                print(choice["delta"].get("content", ""), end="", flush=True)
    return stream.result  # 完成后的标准消息字典

流式工具调用完整后才返回;本库不执行工具。SDK Client 在同一 MyLLM 实例内延迟创建并复用, 通过 async with MyLLM(...) 或 await llm.aclose() 统一关闭;每次请求单独关闭响应流。 Provider、Model 和连接配置在构造时保存副本,生成时仅接受消息、工具和生成选项。 replay_reasoning_content_when_tool_calls 在兼容 Chat 服务中需要显式启用(默认 False);Ollama 默认 True。仅思考已开启且 assistant 有工具调用时补空思维链。

独立格式转换

MyCodec 无状态,不绑定 profile,可复用于任意转换路径。

from my_llm import MyCodec

codec = MyCodec()
converted = codec.convert(
    [{"role": "user", "content": "你好"}],
    input_format="openai_chat", target_format="gemini",
)
assert converted["messages"] == [{"role": "user", "parts": [{"text": "你好"}]}]

消息、工具和流事件各有对称的 encode/decode 接口;profile=None 使用标准协议。 同协议往返保留原生签名、未知字段和嵌套字典。

详见文档目录、API 使用指南、 配置指南及架构与测试边界。

安装最新的开发版本 (main 分支)

git clone https://github.com/JJJJSTIYYYY/my-llm.git
cd ./my-llm
uv sync --group dev --locked
uv run pytest -q
uv run ruff check src tests examples
uv run ruff format --check src tests examples
uv run python examples/local_demo.py
uv build

构建与验证指南 包含安装和发行包验证步骤。 本地开发规范说明目录、导入与测试辅助代码的约定。 项目采用 Apache License 2.0。

Metadata

Release files for my-llm-py 1.0.3

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

Source distribution (sdist)

Source distribution for my-llm-py 1.0.3
File Size Uploaded Provenance
my_llm_py-1.0.3.tar.gz 302.1 kB Without provenance Details

Built distribution (wheel)

Table of built distributions (wheels) for my-llm-py 1.0.3
File Interpreter ABI Platform
my_llm_py-1.0.3-py3-none-any.whl Python 3 none any Details

Total release size: 396.7 kB

Release files / my_llm_py-1.0.3.tar.gz

Download URL my_llm_py-1.0.3.tar.gz
Size 302.1 kB
Tags Source
SHA-256 checksum
How to use checksums
28151c4b648836e709f188544ff437be6b90e070d880ced40fd10a6cb38877ee
BLAKE2b-256 checksum
How to use checksums
f0b160be649c030b4cee812c335de12dcfb9cec38689c6d929375606b1e39551
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.12.12

Release files / my_llm_py-1.0.3-py3-none-any.whl

Download URL my_llm_py-1.0.3-py3-none-any.whl
Size 94.6 kB
Tags Python 3
SHA-256 checksum
How to use checksums
2cdcd076552ef4626dfe3925cf4b89e952a69e559b79b6a8180c962206f9022c
BLAKE2b-256 checksum
How to use checksums
b94b17ee30b226ff3041b13676d0ed50dc629a85bad7071798eedf0ef2f7c46f
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.12.12

Security for my-llm-py 1.0.3

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.

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