LangChain - 聊天模型调用.py(阿里云百炼、智谱、百度千帆)

import os
from dotenv import load_dotenv
from langchain_openai import ChatOpenAI
from langchain_core.messages import HumanMessage, SystemMessage

# 对接各类聊天大模型,实现对话式文本生成,是 LangChain 1.0 最常用的模型组件,替代了旧版本的部分 LLM 使用场景。

# 加载环境变量
load_dotenv()
# 获取密钥
# 定义配置字典 (注意使用冒号 :)
qwen_config = {
    "api_key": os.getenv("QWEN_API_KEY"),  # 获取QWEN_API_KEY
    "base_url": "https://dashscope.aliyuncs.com/compatible-mode/v1",  # 请求地址
    "model_name": "qwen3.5-flash",
}


zhipu_config = {
    "api_key": os.getenv("ZHIPU_API_KEY"),  # ZHIPU_API_KEY
    "base_url": "https://open.bigmodel.cn/api/paas/v4",  # 请求地址
    "model_name": "glm-4.5",
}


baidu_config = {
    "api_key": os.getenv("BAIDU_API_KEY"),  # BAIDU_API_KEY
    "base_url": "https://qianfan.baidubce.com/v2",  # 请求地址
    "model_name": "deepseek-v3.1-250821",
}


# print(qwen_config)
# breakpoint()

model_config = baidu_config
# 初始化聊天模型
chat_model = ChatOpenAI(
    model=model_config["model_name"],  # 模型名称
    api_key=model_config["api_key"],
    base_url=model_config["base_url"],
    temperature=0.7,  # 生成随机性,0-1,0为最严谨,1为最灵活
)

# 构造聊天消息:SystemMessage(系统指令)→ HumanMessage(人类问题)
messages = [
    SystemMessage(content="你是一个友好的Python编程助手,回答简洁易懂"),
    HumanMessage(content="请介绍一下你自己"),
]

# 调用模型生成结果
response = chat_model.invoke(messages)
# 输出结果
print(response.content)
添加新评论