Skip to main content
Open In ColabOpen on GitHub

Yuan2.0

这个笔记本展示了如何在LangChain中使用YUAN2 API以及langchain.chat_models.ChatYuan2。

Yuan2.0 是由 IEIT 系统开发的新一代基础大语言模型。我们已经发布了三个模型,分别是 Yuan 2.0-102B、Yuan 2.0-51B 和 Yuan 2.0-2B,并为其他开发者提供了预训练、微调和推理服务的相关脚本。Yuan2.0 是基于 Yuan1.0 开发的,利用更广泛且高质量的预训练数据以及指令微调数据集来增强模型在语义、数学、推理、代码、知识等方面的理解能力。

Getting Started

安装

首先,Yuan2.0 提供了一个与 OpenAI 兼容的 API,并通过使用 OpenAI 客户端将 ChatYuan2 集成到 langchain 聊天模型中。 因此,请确保在你的 Python 环境中安装了 openai 包。运行以下命令:

%pip install --upgrade --quiet openai

导入所需的模块

安装后,将必要的模块导入到您的Python脚本中:

from langchain_community.chat_models import ChatYuan2
from langchain_core.messages import AIMessage, HumanMessage, SystemMessage

设置您的API服务器

设置您的 OpenAI 兼容 API 服务器,请参考 yuan2 openai api server。 如果您本地部署了 API 服务器,只需设置 yuan2_api_key="EMPTY" 或您想要的任何内容即可。请确保 yuan2_api_base 设置正确。

yuan2_api_key = "your_api_key"
yuan2_api_base = "http://127.0.0.1:8001/v1"

初始化 ChatYuan2 模型

如何初始化聊天模型:<br/>

chat = ChatYuan2(
yuan2_api_base="http://127.0.0.1:8001/v1",
temperature=1.0,
model_name="yuan2",
max_retries=3,
streaming=False,
)

基本用法

像这样使用系统消息和人类消息调用模型:

messages = [
SystemMessage(content="你是一个人工智能助手。"),
HumanMessage(content="你好,你是谁?"),
]
print(chat.invoke(messages))

基本用法(带流式传输)

连续交互,请使用流式特征:

from langchain_core.callbacks import StreamingStdOutCallbackHandler

chat = ChatYuan2(
yuan2_api_base="http://127.0.0.1:8001/v1",
temperature=1.0,
model_name="yuan2",
max_retries=3,
streaming=True,
callbacks=[StreamingStdOutCallbackHandler()],
)
messages = [
SystemMessage(content="你是个旅游小助手。"),
HumanMessage(content="给我介绍一下北京有哪些好玩的。"),
]
chat.invoke(messages)

高级功能

使用异步调用

使用非阻塞性调用方式,像这样调用模型:<br/>

async def basic_agenerate():
chat = ChatYuan2(
yuan2_api_base="http://127.0.0.1:8001/v1",
temperature=1.0,
model_name="yuan2",
max_retries=3,
)
messages = [
[
SystemMessage(content="你是个旅游小助手。"),
HumanMessage(content="给我介绍一下北京有哪些好玩的。"),
]
]

result = await chat.agenerate(messages)
print(result)
import asyncio

asyncio.run(basic_agenerate())

使用提示模板

使用非阻塞调用并像这样使用聊天模板:

async def ainvoke_with_prompt_template():
from langchain_core.prompts.chat import (
ChatPromptTemplate,
)

chat = ChatYuan2(
yuan2_api_base="http://127.0.0.1:8001/v1",
temperature=1.0,
model_name="yuan2",
max_retries=3,
)
prompt = ChatPromptTemplate.from_messages(
[
("system", "你是一个诗人,擅长写诗。"),
("human", "给我写首诗,主题是{theme}。"),
]
)
chain = prompt | chat
result = await chain.ainvoke({"theme": "明月"})
print(f"type(result): {type(result)}; {result}")
asyncio.run(ainvoke_with_prompt_template())

使用异步调用进行流式传输

使用astream方法进行非阻塞调用并获取流式输出:<br/>

async def basic_astream():
chat = ChatYuan2(
yuan2_api_base="http://127.0.0.1:8001/v1",
temperature=1.0,
model_name="yuan2",
max_retries=3,
)
messages = [
SystemMessage(content="你是个旅游小助手。"),
HumanMessage(content="给我介绍一下北京有哪些好玩的。"),
]
result = chat.astream(messages)
async for chunk in result:
print(chunk.content, end="", flush=True)
import asyncio

asyncio.run(basic_astream())