使用 langchain-azure-ai 來建立 LangChain 應用程式,呼叫部署在 Microsoft Foundry 中的模型。 具備 OpenAI 相容 API 的模型可直接使用。 在本文中,你將建立聊天與嵌入客戶端、運行提示鏈,並將生成與驗證工作流程結合。
先決條件
一個 Azure 訂閱。 免費創建一個。
Foundry 專案中的 Foundry 使用者角色。
重要
Foundry RBAC 角色最近已重新命名。 Foundry 用戶、Foundry 擁有者、Foundry Account Owner 以及 Foundry Project Manager 先前分別被稱為 Azure AI 使用者、Azure AI 擁有者、Azure AI 帳戶擁有者及 Azure AI Project 管理者。 在更名期間,你可能還會在某些地方看到之前的名字。角色 ID 與核心權限不會因命名而改變。
一個已部署的聊天模型,支援與 OpenAI 相容的 API,例如
gpt-4.1或Mistral-Large-3。部署的嵌入模型,比如說
text-embedding-3-large。Python 3.10 或更新版本。
安裝所需的套件:
pip install -U langchain langchain-azure-ai azure-identity
重要
langchain-azure-ai 使用新的 Microsoft Foundry SDK(v2)。 如果你用的是 Foundry Classic,建議用 langchain-azure-ai[v1],它使用 Azure AI Inference SDK(已退休)。
了解更多。
設定環境
設定以下連接模式之一:
- 使用 Microsoft Entra ID 的專案端點 (建議方式)。
- 具備 API 金鑰的直接端點。
import os
# Option 1: Project endpoint (recommended)
os.environ["FOUNDRY_PROJECT_ENDPOINT"] = (
"https://<resource>.services.ai.azure.com/api/projects/<project>"
)
# Option 2: Direct OpenAI-compatible endpoint + API key
os.environ["OPENAI_BASE_URL"] = (
"https://<resource>.services.ai.azure.com/openai/v1"
)
os.environ["OPENAI_API_KEY"] = "<your-api-key>"
這個程式碼片段的作用:定義 langchain-azure-ai 模型類別用於專案端點或直接端點存取的環境變數。
使用聊天模型
你可以用以下方式 init_chat_model輕鬆實例化模型:
from langchain.chat_models import init_chat_model
model = init_chat_model("azure_ai:gpt-4.1")
重要
使用 init_chat_model 時需要 langchain>=1.2.13。 如果你無法更新版本,直接 設定客戶端。
所有支援 OpenAI 相容 API 的 Foundry 模型都可以與用戶端一起使用,但你需要先將它們部署到 Foundry 資源中。 使用 project_endpoint(環境變數 FOUNDRY_PROJECT_ENDPOINT)需要使用 Microsoft Entra ID 進行驗證,並具備 Foundry User 角色。
這段程式碼的功能: 利用 init_chat_model 便捷方法建立聊天模型客戶端。 用戶端會透過 Foundry 專案端點或環境中設定的直接端點路由到指定模型。
參考資料:
確認你的設定
執行一個簡單的模型調用:
response = model.invoke("Say hello")
response.pretty_print()
================================== Ai Message ==================================
Hello! 👋 How can I help you today?
這段內容 :發送基本提示以驗證端點、認證及模型路由。
參考資料:
可配置模型
你也可以透過指定 configurable_fields來建立一個執行時可配置的模型。 當你省略參數 model 時,它預設會變成一個可設定的欄位。
from langchain.chat_models import init_chat_model
from azure.identity import DefaultAzureCredential
configurable_model = init_chat_model(
model_provider="azure_ai",
temperature=0,
credential=DefaultAzureCredential()
)
configurable_model.invoke(
"what's your name",
config={"configurable": {"model": "gpt-5-nano"}}, # Run with GPT-5-nano
).pretty_print()
configurable_model.invoke(
"what's your name",
config={"configurable": {"model": "Mistral-Large-3"}}, # Run with Mistral Large
).pretty_print()
================================== Ai Message ==================================
Hi! I'm ChatGPT, an AI assistant built by OpenAI. You can call me ChatGPT or just Assistant. How can I help you today?
================================== Ai Message ==================================
I don't have a name, but you can call me **Assistant** or anything you like! 😊 What can I help you with today?
這段內容 :建立一個可配置的模型實例,讓你在呼叫時能輕鬆切換模型。 由於 model 參數在 init_chat_model中缺少,預設為 可配置欄位 ,且可透過 invoke()傳遞 。 透過設定 configurable_fields,你可以加入其他欄位並使其可配置。
直接配置用戶端
你也可以用 AzureAIOpenAIApiChatModel class 建立聊天模型客戶端。
import os
from azure.identity import DefaultAzureCredential
from langchain_azure_ai.chat_models import AzureAIOpenAIApiChatModel
model = AzureAIOpenAIApiChatModel(
project_endpoint=os.environ["FOUNDRY_PROJECT_ENDPOINT"],
credential=DefaultAzureCredential(),
model="Mistral-Large-3",
)
預設情況下 AzureAIOpenAIApiChatModel 它使用 OpenAI 回應 API。 你可以透過傳遞 use_responses_api=False來改變此行為:
import os
from azure.identity import DefaultAzureCredential
from langchain_azure_ai.chat_models import AzureAIOpenAIApiChatModel
model = AzureAIOpenAIApiChatModel(
endpoint=os.environ["FOUNDRY_PROJECT_ENDPOINT"],
credential=DefaultAzureCredential(),
model="Mistral-Large-3",
use_responses_api=False
)
執行非同步呼叫
請使用非同步憑證,如果你的應用程式呼叫模型為 ainvoke。 使用 Microsoft Entra ID 進行認證時,請使用對應的非同步實作來設定憑證:
import os
from azure.identity.aio import DefaultAzureCredential as DefaultAzureCredentialAsync
from langchain_azure_ai.chat_models import AzureAIOpenAIApiChatModel
model = AzureAIOpenAIApiChatModel(
project_endpoint=os.environ["FOUNDRY_PROJECT_ENDPOINT"],
credential=DefaultAzureCredentialAsync(),
model="gpt-4.1",
)
async def main():
response = await model.ainvoke("Say hello asynchronously")
response.pretty_print()
import asyncio
asyncio.run(main())
提示
如果你在 Jupyter 筆記本中執行這段程式碼,你可以直接使用 await main() 而非 asyncio.run(main())。
================================== Ai Message ==================================
Hello! 👋 How can I help you today?
這段程式碼片段的功能:建立一個非同步客戶端,並使用ainvoke 執行一個非阻塞請求。
參考資料:
推理
許多模型能進行多步驟推理來得出結論。 這需要將複雜問題拆解成更小、更易管理的步驟。
from langchain.chat_models import init_chat_model
model = init_chat_model("azure_ai:DeepSeek-R1-0528")
for chunk in model.stream("Why do parrots have colorful feathers?"):
reasoning_steps = [r for r in chunk.content_blocks if r["type"] == "reasoning"]
print(reasoning_steps if reasoning_steps else chunk.text, end="")
print("\n")
Parrots have colorful feathers primarily due to a combination of evolutionary ...
參考資料:
伺服器端工具
部署於 Foundry 的 OpenAI 模型支援伺服器端工具呼叫迴圈:模型能與網頁搜尋、程式碼解譯器及其他工具互動,並在一次對話回合內分析結果。 若模型在伺服器端呼叫工具,回應訊息內容將包含代表工具調用及結果的內容。
重要
命名空間 langchain_azure_ai.tools.builtin 中的工具僅支援於 OpenAI 模型中。
這些是 OpenAI 提供的工具,用以擴展模型的功能。 欲查看完整支援工具清單,請參閱 內建工具。
以下範例展示了如何使用網頁搜尋:
from langchain.chat_models import init_chat_model
from langchain_azure_ai.tools.builtin import WebSearchTool
from azure.identity import DefaultAzureCredential
model = init_chat_model("azure_ai:gpt-4.1", credential=DefaultAzureCredential())
model_with_web_search = model.bind_tools([WebSearchTool()])
result = model_with_web_search.invoke("What is the current price of gold? Give me the answer in one sentence.")
result.content[-1]["text"]
As of today, March 24, 2026, the spot price of gold is approximately $4,397.80 per ounce. ([tradingeconomics.com](https://tradingeconomics.com/commodity/gold))
有些工具可能需要在你的專案中配置其他資源。 用 azure-ai-projects 來設定那些資源,然後從 LangChain/LangGraph 參考它們。
下例說明了如何在將檔案存放區用於工具之前先行設定:
import os
from azure.ai.projects import AIProjectClient
from azure.identity import DefaultAzureCredential
# Create clients to call Foundry API
project = AIProjectClient(
endpoint=os.environ["FOUNDRY_PROJECT_ENDPOINT"],
credential=DefaultAzureCredential(),
)
openai = project.get_openai_client()
# Create vector store and upload file
vector_store = openai.vector_stores.create(name="ProductInfoStore")
vector_store_id = vector_store.id
with open("product_info.md", "rb") as file_handle:
vector_store_file = openai.vector_stores.files.upload_and_poll(
vector_store_id=vector_store.id,
file=file_handle,
)
此片段的功能: 在 Microsoft Foundry 中建立一個向量儲存庫,讓模型能在下一個程式碼區塊中搜尋該檔案的內容(搭配 FileSearchTool 使用)。
from langchain_azure_ai.tools.builtin import FileSearchTool
model_with_tools = model.bind_tools([FileSearchTool(vector_store_ids=[vector_store.id])])
results = model_with_tools.invoke("Tell me about Contoso products")
print("Answer:", results.content[-1]["text"])
print("Annotations:", results.content[-1]["annotations"])
Answer: Contoso offers the following products:
1. **The widget**
- Description: A high-quality widget that is perfect for all your widget needs.
- Price: $19.99
2. **The gadget**
- Description: An advanced gadget that offers exceptional performance and reliability.
- Price: $49.99
These products are part of Contoso's main offerings as detailed in their product information documentation.
Annotations: [{'file_id': 'assistant-MvU5SEqUcUBumoLUV5BXxn', 'filename': 'product_info.md', 'type': 'file_citation', 'file_index': 395}]
在代理中使用 Foundry 模型
使用 create_agent 連接 Foundry 的模型來建立類似 ReAct 的代理迴圈:
from langchain.agents import create_agent
agent = create_agent(
model="azure_ai:gpt-5.2",
system_prompt="You're an informational agent. Answer questions cheerfully.",
)
response = agent.invoke({"messages": "what's your name?"})
response["messages"][-1].pretty_print()
================================== Ai Message ==================================
I’m ChatGPT, your AI assistant.
伺服器端工具也可以使用,但需要呼叫 bind_tools。
from langchain.chat_models import init_chat_model
from langchain.agents import create_agent
from langchain_azure_ai.tools.builtin import ImageGenerationTool
model = init_chat_model("azure_ai:gpt-5.2")
tools = [ImageGenerationTool(model="gpt-image-1.5", size="1024x1024")]
model_with_tools = model.bind_tools(tools)
agent = create_agent(
model=model_with_tools,
tools=tools,
system_prompt="You're an informational agent. Answer questions with graphics.",
)
提示
Foundry 中的影像產生工具需要將模型部署名稱做為標頭的一部分來傳遞,x-ms-oai-image-generation-deployment,用於影像產生。 使用 langchain-azure-ai時,這會自動處理。 不過,如果你打算用這個工具與 langchain-openai 一起使用,必須手動傳遞標頭資訊。
使用嵌入模型
你可以用以下方式 init_embeddings輕鬆實例化模型:
from langchain.embeddings import init_embeddings
from azure.identity import DefaultAzureCredential
embed_model = init_embeddings(
"azure_ai:text-embedding-3-small",
credential=DefaultAzureCredential(),
)
這段內容的作用是:透過便利的方法創建嵌入模型客戶端。 與 init_chat_model不同, init_embeddings 不會自動退回到 DefaultAzureCredential,因此要明確傳遞憑證。
所有支援 OpenAI 相容 API 的 Foundry 模型都可以與用戶端一起使用,但你需要先將它們部署到 Foundry 資源中。 使用 project_endpoint(環境變數 FOUNDRY_PROJECT_ENDPOINT)需要使用 Microsoft Entra ID 進行驗證,並具備 Foundry User 角色。
或者用 AzureAIOpenAIApiEmbeddingsModel 建立嵌入客戶端。
import os
from azure.identity import DefaultAzureCredential
from langchain_azure_ai.embeddings import AzureAIOpenAIApiEmbeddingsModel
embed_model = AzureAIOpenAIApiEmbeddingsModel(
project_endpoint=os.environ["FOUNDRY_PROJECT_ENDPOINT"],
credential=DefaultAzureCredential(),
model="text-embedding-3-large",
)
針對直接端點與 API 金鑰認證:
import os
from langchain_azure_ai.embeddings import AzureAIOpenAIApiEmbeddingsModel
embed_model = AzureAIOpenAIApiEmbeddingsModel(
endpoint=os.environ["OPENAI_BASE_URL"],
credential=os.environ["OPENAI_API_KEY"],
model="text-embedding-3-large",
)
此段程式碼:設置嵌入生成以進行向量搜尋、檢索和排名工作流程。
參考資料:
範例:使用向量儲存執行相似度搜尋
使用記憶體內的向量儲存器進行本地實驗。
from langchain_core.documents import Document
from langchain_core.vectorstores import InMemoryVectorStore
vector_store = InMemoryVectorStore(embed_model)
documents = [
Document(id="1", page_content="foo", metadata={"baz": "bar"}),
Document(id="2", page_content="thud", metadata={"bar": "baz"}),
]
vector_store.add_documents(documents=documents)
results = vector_store.similarity_search(query="thud", k=1)
for doc in results:
print(f"* {doc.page_content} [{doc.metadata}]")
* thud [{'bar': 'baz'}]
這段內容 :將範例文件加入向量儲存庫,並回傳查詢時最相似的文件。
參考資料:
使用記錄進行偵錯要求
啟用 langchain_azure_ai 除錯日誌以檢查請求流程。
import logging
import sys
logger = logging.getLogger("langchain_azure_ai")
logger.setLevel(logging.DEBUG)
handler = logging.StreamHandler(stream=sys.stdout)
formatter = logging.Formatter(
"%(asctime)s:%(levelname)s:%(name)s:%(message)s"
)
handler.setFormatter(formatter)
logger.addHandler(handler)
此片段的功能: 設定Python日誌以發布詳細的 SDK 日誌,協助排除端點或有效負載問題。
參考資料:
環境變數參考
你可以設定以下環境變數。 這些值在建構物件時也可以設定:
| 變數 | 角色 | 範例 | 構造子中的參數 |
|---|---|---|---|
FOUNDRY_PROJECT_ENDPOINT |
Foundry 的專案端點。 使用專案端點需使用 Microsoft Entra ID 認證(建議)。 | https://contoso.services.ai.azure.com/api/projects/my-project |
project_endpoint |
AZURE_OPENAI_ENDPOINT |
OpenAI 資源的根目錄。 | https://contoso.openai.azure.com |
沒有。 |
OPENAI_BASE_URL |
直接兼容 OpenAI 的端點用於模型呼叫。 | https://contoso.services.ai.azure.com/openai/v1 |
endpoint |
OPENAI_API_KEY 或 AZURE_OPENAI_API_KEY |
API 金鑰與 OPENAI_BASE_URL 或 AZURE_OPENAI_ENDPOINT 一同使用於金鑰驗證。 |
<your-api-key> |
credential |
AZURE_OPENAI_DEPLOYMENT_NAME |
模型在 Foundry 或 OpenAI 資源中的部署名稱。 請在 Foundry 入口網站中確認名稱,因為部署名稱可能與底層模型不同。 任何支援 OpenAI 相容 API 的模型皆可使用,但並非所有參數皆可支援。 | Mistral-Large-3 |
model |
AZURE_OPENAI_API_VERSION |
要用的 API 版本。 當 api_version 可用時,我們建構 OpenAI 客戶端,並透過 api-version注入default_query查詢參數。 |
v1 或 preview |
api_version |
重要
不再使用用於 AZURE_AI_INFERENCE_ENDPOINT 或 AZURE_AI_CREDENTIALS(舊有系統)的環境變數 AzureAIChatCompletionsModel 和 AzureAIEmbeddingsModel。