如何利用langchian调用百度大模型API

Baidu AI Cloud Qianfan Platform 使用LangChain进行聊天模型集成

概述

百度智能云的千帆平台是一个一站式的大模型开发和服务运营平台,为企业开发者提供了包括文心一言(ERNIE-Bot)和第三方开源模型在内的多种模型。主要分为三类模型:

  1. Embedding
  2. Chat
  3. Completion

本文介绍如何使用LangChain与千帆平台的聊天模型进行集成,具体对应LangChain的langchain/chat_models包。

API 初始化

在使用百度千帆平台的大模型服务前,需要初始化相关参数,可以通过环境变量或者直接传参进行初始化:

sh 复制代码
export QIANFAN_AK=XXX
export QIANFAN_SK=XXX
支持的模型
  • ERNIE-Bot-turbo(默认)
  • ERNIE-Bot
  • ERNIE-Speed-128K
  • BLOOMZ-7B
  • Llama-2-7b-chat
  • Llama-2-13b-chat
  • Llama-2-70b-chat
  • Qianfan-BLOOMZ-7B-compressed
  • Qianfan-Chinese-Llama-2-7B
  • ChatGLM2-6B-32K
  • AquilaChat-7B
基本设置和调用

使用示例代码初始化并调用聊天模型:

python 复制代码
import os
from langchain_community.chat_models import QianfanChatEndpoint
from langchain_core.language_models.chat_models import HumanMessage

os.environ["QIANFAN_AK"] = "Your_api_key"
os.environ["QIANFAN_SK"] = "Your_secret_Key"

chat = QianfanChatEndpoint(streaming=True)
messages = [HumanMessage(content="Hello")]
response = chat.invoke(messages)

print(response.content)
异步调用

可以使用异步方法进行调用:

python 复制代码
await chat.ainvoke(messages)
批量调用

支持批量处理消息:

python 复制代码
responses = chat.batch([messages])
print(responses[0].content)
流式处理

支持流式处理消息输出:

python 复制代码
try:
    for chunk in chat.stream(messages):
        print(chunk.content, end="", flush=True)
except TypeError as e:
    print(e)
使用不同模型

默认使用ERNIE-Bot-turbo,如果需要使用其他模型,可以在初始化时指定:

python 复制代码
chatBot = QianfanChatEndpoint(
    streaming=True,
    model="ERNIE-Bot",
)

messages = [HumanMessage(content="Hello")]
response = chatBot.invoke(messages)
print(response.content)
模型参数

目前只有ERNIE-Bot和ERNIE-Bot-turbo支持以下参数,可以在调用时指定:

  • temperature
  • top_p
  • penalty_score

示例代码:

python 复制代码
response = chat.invoke(
    [HumanMessage(content="Hello")],
    **{"top_p": 0.4, "temperature": 0.1, "penalty_score": 1}
)
print(response.content)
相关推荐
葫芦和十三16 小时前
渐进发现|代码库不是文档库
langchain·agent·ai编程
柒和远方1 天前
LangGraph 深度解析:从增强型 LLM 到生产级 Agent
langchain·llm·agent
2601_961845152 天前
粉笔行测题库|系统班|刷题
网络·百度·微信·微信公众平台·facebook·新浪微博
沪漂阿龙2 天前
《LangChain》成本、限流、缓存、降级:AI 应用上线要考虑的问题
人工智能·langchain
段一凡-华北理工大学2 天前
LangChain框架在高炉炼铁智能化领域的应用~系列文章09:工具调用Tool — 让AI学会操作高炉仪表盘
网络·人工智能·架构·langchain·高炉炼铁·高炉智能化·高炉智能体
Niuguangshuo2 天前
LangChain 学习之旅(五):Agent 与工具调用实战
学习·langchain
yangshicong2 天前
第16章:AI数据分析与Text-to-SQL
人工智能·python·sql·数据分析·langchain
小陈phd2 天前
基于LangChain 实现提示词链、工具调用与多轮对话记忆系统
langchain
奋飛2 天前
从 Prompt 到 Agent:LangChain 究竟解决了什么问题
ai·langchain·prompt·agent
倾颜3 天前
从本地 Ollama 到线上多模型 Runtime:接入 DeepSeek / Qwen 的实战复盘
langchain·next.js·deepseek