Mistral 整合在 Agent Framework Python 中提供用於聊天代理程式的 MistralChatClient 和用於文字嵌入功能的 MistralEmbeddingClient。
安裝套件
pip install agent-framework-mistral --pre
Configuration
MISTRAL_API_KEY="<api-key>"
MISTRAL_CHAT_MODEL="mistral-small-latest"
MISTRAL_EMBEDDING_MODEL="mistral-embed"
# Optional compatible endpoint:
MISTRAL_SERVER_URL="<server-url>"
你也可以將 api_key、model 和 server_url 直接傳遞給任一用戶端。
在用戶端設定傳輸設定。 當你透過 options 或額外的關鍵字引數在每次呼叫中傳遞 server_url、http_headers、retries 和 timeout_ms 時,Agent Framework 會拒絕它們。 每次呼叫時仍可使用生成選項。
建立聊天代理
使用 MistralChatClient 建立一個 Agent。 用戶端會從前一節所示的環境變數讀取 API 金鑰與聊天模型。
import asyncio
from agent_framework import Agent
from agent_framework.mistral import MistralChatClient
async def main() -> None:
client = MistralChatClient()
try:
agent = Agent(
client=client,
instructions="You are a helpful assistant.",
)
response = await agent.run("How many days are in a week?")
print(response.text)
finally:
await client.close()
asyncio.run(main())
所選的 Mistral 模型決定可用的模型層級能力。
聊天功能
MistralChatClient 支援以下代理框架功能:
| 能力 | Usage |
|---|---|
| 串流 | 呼叫 agent.run(..., stream=True) 以逐一處理回應更新。 |
| 功能工具 | 新增代理框架功能工具到 Agent(tools=...)。 |
| 結構化輸出 | 將 Pydantic 模型、JSON 架構映射或 JSON 物件模式傳遞給 response_format。 |
| 多模態輸入 | 在使用者訊息中傳送圖片資料、網址及PDF文件網址。 |
| Reasoning | 針對支援的模型設定 reasoning_effort,並將回傳的 thinking 作為 text_reasoning 內容讀取。 |
關於可執行的函式工具與串流範例,請參見 Mistral agent 範例。
產生內嵌
建立客戶端並呼叫 get_embeddings()。
async def basic_embedding_example() -> None:
"""Generate embeddings for a list of texts."""
print("=== Basic Embedding Generation ===")
# 1. Create the embedding client using environment-based configuration.
client = MistralEmbeddingClient()
# 2. Generate embeddings for multiple texts.
texts = ["Hello, world!", "How are you?", "Agent Framework with Mistral AI"]
try:
result = await client.get_embeddings(texts)
# 3. Print the generated vectors and usage metadata.
print(f"Generated {len(result)} embeddings")
for i, embedding in enumerate(result):
print(f" Text {i + 1}: dimensions={embedding.dimensions}, vector={embedding.vector[:5]}...")
if result.usage:
print(
f" Usage: {result.usage['input_token_count']} input tokens, "
f"{result.usage['total_token_count']} total tokens"
)
finally:
await client.close()
async def embedding_with_options_example() -> None:
"""Generate embeddings with custom dimensions."""
print("\n=== Embedding with Custom Dimensions ===")
from agent_framework.mistral import MistralEmbeddingOptions
# Only some models support a custom output dimension (e.g. codestral-embed; mistral-embed does not).
client = MistralEmbeddingClient(model="codestral-embed")
options: MistralEmbeddingOptions = {"dimensions": 256}
使用 MistralEmbeddingOptions 請求受支援的輸出維度。 你也可以設定 MISTRAL_SERVER_URL 應用程式何時使用相容的客製化端點。
這很重要
Mistral AI 是第三方系統。 在傳送應用程式資料前,請先審查其服務條款、資料處理、區域邊界、模型授權及使用成本。
Tools
MistralChatClient 支援本地調用函式工具及 Agent Framework 函式調用迴圈。 所選模型必須支援函式呼叫。