如何利用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)
相关推荐
云和数据.ChenGuang1 小时前
Python 重写(Override)深度解析:从 MRO 到 super() 的完整机制
java·开发语言·人工智能·python·langchain·1024程序员节
云和数据.ChenGuang5 小时前
Python 单继承与多继承深度剖析:从 MRO 到实战取舍
开发语言·人工智能·python·langchain
全栈偏科生8 小时前
LangChain JS 入门:快速搭建前端 AI 开发环境
langchain
郝学胜-神的一滴10 小时前
AI 编程智能体 17:四步搞定专属AI智能体
大数据·人工智能·python·神经网络·算法·langchain·强化学习
咚咚咚小柒11 小时前
【前端】LangChain.js学习
前端·javascript·人工智能·typescript·langchain·vue·ai编程
览讯冷却12 小时前
冷却塔噪声的健康危害与法规要求的技术梳理
经验分享·笔记·科技·其他·百度·制造·业界资讯
clz131452112 小时前
RAG 文档切分实战:从语义分层到长度优化
langchain
寻道码路14 小时前
AI Agent 工程化开发实战(四):工具调用循环——解构 create_agent 背后的机制
人工智能·langchain·ai agent·工具调用·langgraph
染指111016 小时前
160.Agent-LangGraph-自定义主管架构智能体
人工智能·windows·microsoft·langchain·1024程序员节·agents
lambo mercy1 天前
核心组件8——检索器(Retrievers)
langchain