You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在LangChain中串联AzureOpenAI?解决客户端无法作为Runnable的问题

解决方案

问题原因

LangChain的链操作(|)要求每个环节必须是Runnable类型(或符合Runnable接口的可调用对象),而你使用的原生AzureOpenAI客户端并不满足这个要求,因此抛出类型错误。


方法一:使用LangChain封装的AzureChatOpenAI类(推荐)

LangChain提供了专门适配Azure OpenAI的AzureChatOpenAI类,它已经实现了Runnable接口,可以直接接入链中使用。

代码示例

from langchain_openai import AzureChatOpenAI
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.output_parsers import StrOutputParser
import os

# 初始化LangChain封装的Azure OpenAI客户端
client = AzureChatOpenAI(
    azure_endpoint=os.getenv("AZURE_OPENAI_ENDPOINT"),
    api_key=os.getenv("AZURE_OPENAI_API_KEY"),
    api_version="2024-05-01-preview",
    azure_deployment="你的Azure部署名称"  # 必须指定部署的模型名称
)

# 构建链
normal_chain = (
    ChatPromptTemplate.from_messages([("system", "write a tweet about {topic} in the style of Elon Musk")])
    | client
    | StrOutputParser()
)

# 调用链
result = normal_chain.invoke({"topic": "AI发展"})
print(result)

注意事项

  • 需要安装langchain-openai包:pip install langchain-openai
  • azure_deployment参数必须填写你在Azure OpenAI门户中创建的模型部署名称,不能省略。

方法二:将原生AzureOpenAI客户端包装为Runnable

如果你坚持使用原生AzureOpenAI客户端,可以将其包装成符合Runnable要求的可调用函数,通过RunnableLambda或直接传入函数实现。

代码示例

from openai import AzureOpenAI
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.output_parsers import StrOutputParser
from langchain_core.runnables import RunnableLambda
import os

# 初始化原生Azure OpenAI客户端
client = AzureOpenAI(
    azure_endpoint=os.getenv("AZURE_OPENAI_ENDPOINT"),
    api_key=os.getenv("AZURE_OPENAI_API_KEY"),
    api_version="2024-05-01-preview"
)

# 定义包装函数,接收LangChain的消息格式并调用客户端
def call_azure_openai(messages):
    response = client.chat.completions.create(
        model="你的Azure部署名称",  # 替换为你的部署名称
        messages=messages
    )
    return response.choices[0].message.content

# 构建链,用RunnableLambda包装函数
normal_chain = (
    ChatPromptTemplate.from_messages([("system", "write a tweet about {topic} in the style of Elon Musk")])
    | RunnableLambda(call_azure_openai)
    | StrOutputParser()
)

# 调用链
result = normal_chain.invoke({"topic": "可持续能源"})
print(result)

说明

  • 包装函数需要将LangChain生成的messages列表直接传入client.chat.completions.create的messages参数
  • 必须指定model参数为你的Azure模型部署名称

内容的提问来源于stack exchange,提问作者Janarddan Sarkar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.19 16:53:23