Skip to main content

Phad LLM SDK for Python

Project description

Phad LLM SDK for Python

Phad LLM SDK 是一个用于与大语言模型交互的 Python SDK,提供了统一的调用接口,支持流式响应和非流式响应,简化了大模型服务的调用流程。

功能特性

  • 统一调用接口:提供了简洁易用的 API,支持多种大语言模型服务
  • 流式响应支持:支持流式返回生成结果,提升用户体验
  • 消息构建器:内置消息构建器,方便构建对话消息列表
  • 单例模式:客户端采用单例模式,确保资源高效利用
  • 环境变量配置:通过环境变量灵活配置服务地址和路径

安装

从 PyPI 安装

pip install phad-llm-sdk

从源码安装

# 克隆仓库
git clone https://github.com/yourusername/phad-llm-sdk-python.git
cd phad-llm-sdk-python

# 安装包
pip install -e .

配置

SDK 需要通过环境变量配置以下参数:

  • VLLM_LLM_URL: 大模型服务的基础 URL
  • LLM_QWEN_PATH: API 路径(可选)

你可以创建一个 .env 文件来存储这些配置:

VLLM_LLM_URL=http://localhost:8000
LLM_QWEN_PATH=v1/chat/completions

快速开始

基本使用

from phad_llm_sdk import llm_client

# 使用消息构建器构建消息列表
message_builder = llm_client.create_message_builder()
messages = message_builder\
    .add_system_message("你是一个AI助手,喜欢帮助别人。")\
    .add_user_message("你好,能帮我解释一下什么是机器学习吗?")\
    .build()

# 调用大模型(非流式)
response = llm_client.chat(messages)
print("非流式响应:")
print(response)

# 调用大模型(流式)
print("\n流式响应:")
stream_response = llm_client.chat(messages, stream=True)
if stream_response:
    import json
    for chunk in stream_response.iter_lines():
        if chunk:
            chunk = chunk.decode('utf-8')
            if chunk.startswith('data: '):
                chunk = chunk[6:]
            if chunk == '[DONE]':
                break
            try:
                chunk_data = json.loads(chunk)
                content = chunk_data.get("choices", [{}])[0].get("delta", {}).get("content", "")
                if content:
                    print(content, end="")
            except json.JSONDecodeError:
                pass
    print()
else:
    print("流式请求失败")

自定义参数

from phad_llm_sdk import llm_client

# 构建消息
message_builder = llm_client.create_message_builder()
messages = message_builder\
    .add_system_message("你是一个AI助手,喜欢帮助别人。")\
    .add_user_message("你好,能帮我解释一下什么是深度学习吗?")\
    .build()

# 自定义参数调用
response = llm_client.chat(
    messages=messages,
    stream=False,
    max_tokens=500,
    temperature=0.8,
    top_p=0.9,
    think=True
)
print(response)

API 文档

LLMClient

LLMClient 是大模型客户端的主类,提供了与大语言模型交互的核心方法。

方法

  • chat(messages, stream=False, max_tokens=200, temperature=0.7, top_p=0.1, think=False): 调用大模型进行对话

    • messages: 消息列表,格式为 [{"role": "system", "content": "..."}, {"role": "user", "content": "..."}]
    • stream: 是否使用流式响应
    • max_tokens: 最大生成 token 数
    • temperature: 温度参数,控制生成的随机性
    • top_p: 采样的核概率,控制生成的多样性
    • think: 是否返回思考过程
    • 返回值: 如果 stream=True,返回响应对象;如果 stream=False,返回 {"message": {"content": "回答内容"}}
  • create_message_builder(): 创建消息构建器

    • 返回值: MessageBuilder 实例

MessageBuilder

MessageBuilder 是一个消息构建器,用于方便地构建消息列表。

方法

  • add_message(role, content): 添加一条消息

    • role: 角色,例如 "system"、"user"、"assistant"
    • content: 消息内容
    • 返回值: 自身,支持链式调用
  • add_system_message(content): 添加系统消息

    • content: 系统消息内容
    • 返回值: 自身,支持链式调用
  • add_user_message(content): 添加用户消息

    • content: 用户消息内容
    • 返回值: 自身,支持链式调用
  • add_assistant_message(content): 添加助手消息

    • content: 助手消息内容
    • 返回值: 自身,支持链式调用
  • build(): 构建消息列表

    • 返回值: 消息列表,格式为 [{"role": "...", "content": "..."}]

项目结构

phad-llm-sdk/
├── src/
│   └── phad_llm_sdk/
│       ├── client/
│       │   ├── LLMClient.py      # 主要客户端实现
│       │   ├── VLLMClient.py     # VLLM 客户端实现
│       │   └── __init__.py
│       ├── dto/
│       │   ├── req/              # 请求数据模型
│       │   │   ├── __init__.py
│       │   │   └── llm_send.py
│       │   ├── resp/             # 响应数据模型
│       │   │   ├── __init__.py
│       │   │   └── llm_resp.py
│       │   └── __init__.py
│       ├── utils/
│       │   ├── HttpUtils.py      # HTTP 工具类
│       │   └── __init__.py
│       └── __init__.py           # 包导出文件
├── pyproject.toml                 # 项目配置文件
├── setup.py                       # 安装脚本
├── setup.cfg                      # 安装配置文件
├── requirements.txt               # 依赖文件
├── README.md                      # 项目说明文件
└── LICENSE                        # 许可证文件

配置示例

.env 文件示例

# 大模型服务基础 URL
VLLM_LLM_URL=http://localhost:8000

# API 路径(可选)
LLM_QWEN_PATH=v1/chat/completions

故障排除

常见问题

  1. 连接失败:请检查 VLLM_LLM_URL 环境变量是否正确配置,确保大模型服务正在运行。

  2. 导入错误:请确保已正确安装 SDK,并且 Python 版本 >= 3.7。

  3. 响应异常:请检查请求参数是否正确,特别是消息格式是否符合要求。

日志调试

如果遇到问题,可以开启详细日志来排查:

import logging
logging.basicConfig(level=logging.DEBUG)

from phad_llm_sdk import llm_client
# 后续代码...

版本历史

  • v0.1.0:初始版本,支持基本的大模型调用和流式响应

许可证

本项目采用 MIT 许可证,详见 LICENSE 文件。

贡献

欢迎提交 Issue 和 Pull Request 来改进这个 SDK。

联系方式

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

phad_llm_sdk-1.2.3.tar.gz (16.2 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

phad_llm_sdk-1.2.3-py3-none-any.whl (16.9 kB view details)

Uploaded Python 3

File details

Details for the file phad_llm_sdk-1.2.3.tar.gz.

File metadata

  • Download URL: phad_llm_sdk-1.2.3.tar.gz
  • Upload date:
  • Size: 16.2 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.13.0

File hashes

Hashes for phad_llm_sdk-1.2.3.tar.gz
Algorithm Hash digest
SHA256 de47514779c17a00b60164ca128d0e9aba4bb1f3728c63530716ad87bc332f32
MD5 3c335ae187bd9ba08a1a5941910748bc
BLAKE2b-256 943e08d423614f07c56f5c4b4c6fb3ecb453280a4c539421e47e4f22d5369c92

See more details on using hashes here.

File details

Details for the file phad_llm_sdk-1.2.3-py3-none-any.whl.

File metadata

  • Download URL: phad_llm_sdk-1.2.3-py3-none-any.whl
  • Upload date:
  • Size: 16.9 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.13.0

File hashes

Hashes for phad_llm_sdk-1.2.3-py3-none-any.whl
Algorithm Hash digest
SHA256 58f0bc07505522d25f493cc4b4079ae34eb84d55103c9160437a3407f180d30b
MD5 d9b8fc6c94087d67a40323d7db30c271
BLAKE2b-256 f33df40cf6cc597b87713b9f8f3671bdf5dbccc2ed62ef2ccae6800a0b9d6bb2

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page