Skip to main content

Implementation of LangChain for ZhipuAI(Just for coding exercise)

Project description

langchain-zhipuai

PyPI version

langchain-zhipuai 是一个为 LangChain 实现的 ZhipuAI (智谱 AI) 大模型接口包。它允许用户在 LangChain 框架内方便地使用智谱AI提供的各种强大的语言模型。 这个项目最初是作为一个编码练习,但旨在提供一个功能完整且易于使用的集成。

特性

  • 支持智谱 AI 的多种对话模型 (例如 glm-4-plus, glm-4-air, glm-4-flash 等,默认 glm-4-plus)。
  • 支持智谱 AI 的多种嵌入模型 (例如 embedding-3, embedding-2),默认 embedding-3
  • 支持标准的 LangChain invoke, stream, 和 generate (批量) API。
  • 灵活的消息输入格式 (字典列表或 BaseMessage 对象列表)。
  • 可配置的参数,如 temperature, max_tokens, stop 序列等。
  • 自动处理API密钥。
  • 返回包含 usage_metadataresponse_metadata 的标准 LangChain 输出对象。

安装

你可以使用 uvpip 来安装这个包:

使用 uv:

uv add langchain-zhipuai-dev

或者使用 pip:

pip install langchain-zhipuai-dev

环境配置

在使用之前,你需要设置你的智谱 AI API 密钥。可以通过设置环境变量 ZHIPUAI_API_KEY 来完成:

export ZHIPUAI_API_KEY="YOUR_ZHIPUAI_API_KEY"

或者,你也可以在代码中初始化 ChatZhipuAI 类时直接传递 api_key 参数。

对话模型(Chat)

下面是一些如何使用 langchain-zhipuai 的基本示例。

1. 初始化

首先,导入并初始化 ChatZhipuAI 类:

import os
from langchain_zhipuai_dev.chat import ChatZhipuAI
from langchain_core.messages import HumanMessage, SystemMessage, AIMessage

# 从环境变量加载 API Key
llm = ChatZhipuAI(
    model_name="glm-4-plus",  # 可选,默认为 "glm-4-plus"
    temperature=0.7,     # 可选,默认为 None (使用智谱AI的默认值)
    # api_key="YOUR_ZHIPUAI_API_KEY" # 如果没有设置环境变量,可以在这里提供
)

2. 使用 invoke API (单次调用)

invoke 方法用于发送一次请求并获取单个完整的响应。

messages = [
    SystemMessage(content="你是一个乐于助人的 AI 助手。"),
    HumanMessage(content="你好,请介绍一下你自己。")
]

response = llm.invoke(messages)

print("Invoke API Response:")
print(f"Type: {type(response)}")
print(f"Content: {response.content}")
if response.usage_metadata:
    print(f"Usage: {response.usage_metadata}")
if response.response_metadata:
    print(f"Response Metadata: {response.response_metadata}")

3. 使用 stream API (流式响应)

stream 方法用于获取流式响应,逐步接收模型生成的内容。

messages = [
    HumanMessage(content="给我讲一个关于编程的笑话。")
]

print("\nStream API Response:")
full_streamed_content = []
for chunk in llm.stream(messages):
    print(chunk.content, end="", flush=True)
    full_streamed_content.append(chunk.content)
    # AIMessageChunk 包含 content, additional_kwargs, response_metadata, usage_metadata, id
    # 最后一个 chunk 通常包含 usage_metadata 和 response_metadata
    if chunk.usage_metadata:
        print(f"\nStream (final chunk) Usage: {chunk.usage_metadata}")
    if chunk.response_metadata:
        print(f"Stream (final chunk) Response Metadata: {chunk.response_metadata}")

print("\n--- End of Stream ---")
print("Full streamed content:", "".join(full_streamed_content))

4. 使用 generate API (批量处理)

generate 方法用于一次性处理多个消息列表(提示)。

list_of_prompts = [
    [HumanMessage(content="天空为什么是蓝色的?")],
    [
        SystemMessage(content="你是一只猫。"),
        HumanMessage(content="你最喜欢吃什么?")
    ]
]

batch_response = llm.generate(list_of_prompts)

print("\nGenerate API (Batch) Response:")
for i, generation_result in enumerate(batch_response.generations):
    # ChatGeneration 包含 message (AIMessage) 和 generation_info
    chat_generation = generation_result[0] # 通常每个提示只有一个生成结果
    print(f"\nResponse for prompt {i+1}:")
    print(f"  Content: {chat_generation.message.content}")
    if chat_generation.message.usage_metadata:
        print(f"  Usage: {chat_generation.message.usage_metadata}")
    if chat_generation.message.response_metadata:
        print(f"  Response Metadata: {chat_generation.message.response_metadata}")
    if chat_generation.generation_info:
         print(f"  Generation Info: {chat_generation.generation_info}")

if batch_response.llm_output:
    print(f"\nLLM Output from generate: {batch_response.llm_output}")

参数说明

初始化 ChatZhipuAI 时可以传递以下参数:

  • model_name (str, 可选): 指定要使用的智谱AI模型名称。默认为 "glm-4-plus"
  • temperature (float, 可选): 控制生成文本的随机性。默认为 None (使用API的默认值)。
  • max_tokens (int, 可选): 生成文本的最大长度。默认为 None
  • timeout (int, 可选): API请求的超时时间(秒)。默认为 None
  • stop (List[str], 可选): 一个或多个停止序列。默认为 None
  • max_retries (int, 可选): API请求失败时的最大重试次数。默认为 3
  • api_key (str, 可选): 你的智谱AI API密钥。如果未提供,则会尝试从环境变量 ZHIPUAI_API_KEY 中读取。

消息格式

ChatZhipuAI 支持两种主要的消息输入格式:


嵌入模型(Embeddings)

langchain-zhipuai 还提供了对智谱 AI 嵌入模型的支持,可用于文本向量化等场景。

用法示例

初始化过程参照上述内容。

from langchain_zhipuai_dev.embedding import ZhipuAIEmbeddings
from pydantic import SecretStr

# 初始化嵌入模型
embeddings = ZhipuAIEmbeddings(
    api_key=SecretStr("YOUR_ZHIPUAI_API_KEY"),  # 可选,若已设置环境变量可省略
    model="embedding-3"  # 可选,默认为 "embedding-3"
)

# 文本批量嵌入
texts = ["你好世界", "langchain 嵌入测试"]
vectors = embeddings.embed_documents(texts)
print(vectors)  # List[List[float]]

# 单条查询嵌入
query = "什么是人工智能?"
query_vector = embeddings.embed_query(query)
print(query_vector)  # List[float]

参数说明

  • api_key (SecretStr,可选): 智谱 AI API 密钥。若未提供,则尝试从环境变量读取。
  • model (str,可选): 嵌入模型名称,默认为 "embedding-3"

方法说明

  • embed_documents(texts: List[str]) -> List[List[float]]: 批量获取文本嵌入向量。
  • embed_query(text: str) -> List[float]: 获取单条文本的嵌入向量。

  • 字典列表: 例如 [{"role": "user", "content": "你好"}]
  • BaseMessage 对象列表: 例如 [HumanMessage(content="你好")] (推荐,更符合LangChain生态)

支持的角色包括 system, user, assistant, 以及通用的 ChatMessage (需要指定 role)。

贡献

欢迎为此项目做出贡献!如果你发现任何bug或有改进建议,请随时提交Issue或Pull Request。

许可证

该项目使用 MIT 许可证。详情请参阅 LICENSE 文件 (如果存在)。

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

langchain_zhipuai_dev-0.3.0.tar.gz (7.8 kB view details)

Uploaded Source

Built Distribution

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

langchain_zhipuai_dev-0.3.0-py3-none-any.whl (8.7 kB view details)

Uploaded Python 3

File details

Details for the file langchain_zhipuai_dev-0.3.0.tar.gz.

File metadata

File hashes

Hashes for langchain_zhipuai_dev-0.3.0.tar.gz
Algorithm Hash digest
SHA256 ecc0e94d964557c83b6f8add42b4135c1efd8bbb4ace35830164656a30a66184
MD5 a4fc992fc4d8dcddfa727f274ec76c15
BLAKE2b-256 63b0fbb04bb4783297c61bac6ec1b48090a44c02eec6d65b73b0841a7c536588

See more details on using hashes here.

File details

Details for the file langchain_zhipuai_dev-0.3.0-py3-none-any.whl.

File metadata

File hashes

Hashes for langchain_zhipuai_dev-0.3.0-py3-none-any.whl
Algorithm Hash digest
SHA256 f01eef97ea8417c60528307fdd8b3f043c6be6878459cf51236a3037a5d23293
MD5 b53f1207273932f81aae4197de8f3d2b
BLAKE2b-256 8a40285767db99ba2b450fcbc4f8c46aaad77bc202422e7b432168ed50bf61d4

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