跳到主要內容

Yuan2.0

本筆記本示範如何在 LangChain 中使用 YUAN2 API,透過 langchain.chat_models.ChatYuan2。

Yuan2.0 是由 IEIT System 開發的新一代基礎大型語言模型。我們已發布所有三個模型,Yuan 2.0-102B、Yuan 2.0-51B 和 Yuan 2.0-2B。我們也為其他開發人員提供用於預訓練、微調和推論服務的相關腳本。Yuan2.0 基於 Yuan1.0,利用更廣泛的高品質預訓練資料和指令微調資料集,以增強模型在語義、數學、推理、程式碼、知識和其他方面的理解能力。

開始使用

安裝

首先,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 伺服器

依照 yuan2 openai api 伺服器 設定您的 OpenAI 相容 API 伺服器。如果您在本機部署了 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 模型

以下是如何初始化聊天模型

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)

進階功能

搭配非同步呼叫使用

像這樣使用非封鎖呼叫調用模型

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}")
API 參考:ChatPromptTemplate
asyncio.run(ainvoke_with_prompt_template())

在串流中搭配非同步呼叫使用

若要進行具有串流輸出的非封鎖呼叫,請使用 astream 方法

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())

此頁面是否有幫助?