要在你的代理中加入對代理優化器的支援,只需要寫幾行程式碼。 不需要任何框架變更或條件邏輯。 你安裝優化套件,建立設定目錄,然後在啟動時呼叫 load_config() 。
此步驟是 優化工作流程的第一步。 你建立的基線配置定義了優化器所改進的輸入:指令、工具、技能和模型。 無論優化是否啟動,你的代理都會一樣運作。
要讓你的代理人優化器就緒,請完成三個步驟:
本文其餘部分提供完整範例並說明組態解析的運作方式。 優化執行結束後,你會套用獲勝候選並部署——詳見 部署勝者。
先決條件
- 具有已部署託管代理程式的 Foundry 專案
- 對代管代理程式的熟悉度
- Python 3.10 或更新版本
安裝優化套件
安裝 azure-ai-agentserver-optimization 套件:
pip install azure-ai-agentserver-optimization
設定組態目錄
在你的專案根節點建立 .agent_configs/baseline/ 目錄。 這個目錄定義了你代理人的基線設定——優化器讀取並改進的起點。
my-agent/
|- main.py
|- azure.yaml
|- requirements.txt
\- .agent_configs/
|- baseline/ <- your starting config
| |- metadata.yaml
| |- instructions.md
| |- tools.json
| \- skills/
| \- (initially empty)
\- <candidate_id>/ <- created by 'azd ai agent optimize apply'
\- (same layout as baseline/)
基線需要 metadata.yaml 和 instructions.md。
tools.json 檔案和 skills/ 目錄為選用項目——只有在您的代理程式使用工具或技能時才需包含。 最佳化工具會根據這些檔案中哪些存在,啟用各個目標。
metadata.yaml
中繼資料檔案告訴優化載入器設定檔的位置及使用哪種模型:
model: gpt-4.1-mini
instruction_file: instructions.md
tools_file: tools.json
skill_dir: skills
| Field | Required | Description |
|---|---|---|
model |
Yes | 模型部署名稱(例如, gpt-4.1-mini, gpt-5.1) |
instruction_file |
Yes | 系統提示檔的相對路徑 |
tools_file |
No | 工具定義 JSON 檔案的相對路徑 |
skill_dir |
No | 技能目錄的相對路徑 |
temperature |
No | 生成時的模型溫度 |
instructions.md
你經紀人的系統提示音。 以純文字或 Markdown 格式撰寫:
You are a travel approval agent for Contoso Ltd. You review travel
requests and enforce company travel policy. Check travel policy limits,
department budget, and suggest cheaper alternatives when appropriate.
Enforce policy rules strictly — do not auto-approve everything.
優化器會在優化執行時改善此提示。 套用最佳化候選版本之後,此檔案會包含改善後的版本。
tools.json
請宣告您的代理可以使用 OpenAI 函式呼叫格式呼叫的工具:
[
{
"type": "function",
"function": {
"name": "lookup_travel_policy",
"description": "Look up the company travel policy rules and limits.",
"parameters": {
"type": "object",
"properties": {}
}
}
},
{
"type": "function",
"function": {
"name": "get_flight_alternatives",
"description": "Find cheaper flight alternatives for the given destination.",
"parameters": {
"type": "object",
"properties": {
"destination": {
"type": "string",
"description": "The travel destination city"
}
},
"required": ["destination"]
}
}
}
]
優化器能改進工具描述,幫助模型更準確地呼叫工具。 優化後,你再把改進的描述套回這個檔案。
技能/(特務技能格式)
技能採用開放式 的特工技能 格式。 每個技能都是一個資料夾,裡面包含一個 SKILL.md 檔案:
skills/
\-- policy-reviewer/
\-- SKILL.md
SKILL.md 檔案包含用於中繼資料的 YAML 前言區塊,以及作為指令的 Markdown 內文:
---
name: policy-reviewer
description: Reviews travel requests. Use when someone submits a travel request.
---
# Policy Reviewer Skill
When reviewing a travel request:
1. Check destination against restricted countries list
2. Verify trip cost is within department budget
3. Confirm travel dates don't conflict with blackout periods
4. Suggest alternatives if the request exceeds policy limits
YAML 前置(name 和 description)可實現漸進揭露——代理程式在啟動時僅載入元資料,當偵測到匹配任務時啟動完整技能指令。
優化者能在優化過程中發掘並創造新技能。 當您套用最佳化候選項時,這些技能會寫入 skills/ 目錄。
想了解更多關於經紀人技能格式的資訊,請見 agentskills.io。
載入並使用設定檔
在你的代理程式入口點頂端新增設定載入器:
Note
對於 .NET 代理程式,請使用 Azure。AI。AgentServer.Core 套件。
from azure.ai.agentserver.optimization import load_config
config = load_config()
函 load_config() 式讀取 .agent_configs/ 並回傳物件 OptimizationConfig 。 當沒有啟用的優化候選方案時,系統會回傳你的基準配置。 如果找不到設定來源,則會回傳 None。
參數:
| 參數 | Description |
|---|---|
config_dir |
自訂設定目錄路徑(預設為 .agent_configs/) |
OptimizationConfig 欄位:
| Field | 類型 | Description |
|---|---|---|
instructions |
str |
系統提示詞(優化版或基準版) |
model |
str |
模型部署名稱 |
temperature |
float |
取樣溫度 |
skills |
list[Skill] |
已偵測到的技能(若無則留空) |
skills_dir |
str |
技能目錄路徑 |
tool_definitions |
list |
工具定義與最佳化描述 |
source |
str |
設定檔的來源(baseline、、 env等等) |
使用設定值
在呼叫模型時,請使用該模型和組合後的指示:
model = config.model or "gpt-4.1-mini"
instructions = config.compose_instructions()
compose_instructions() 方法會回傳系統提示,並將任何已發現的技能附加為技能目錄。
套用最佳化的工具描述
如果你的代理使用工具(函式),請對它們套用優化的描述:
tools = [lookup_travel_policy, check_department_budget, get_flight_alternatives]
config.apply_tool_descriptions(tools)
該 apply_tool_descriptions() 方法會將每個工具函式的元資料與優化設定中改進的描述進行修補。這提升了模型在決定呼叫哪個工具時的準確度。
如果你的工具與 apply_tool_descriptions() 不相容,請從 config.tool_definitions 讀取最佳化後的定義,並將其套用至你自己的工具物件。 每個定義都包含優化過的函式描述和參數描述,所以請依函數和參數名稱將兩者對應到你的工具上。
從目錄載入技能
如果你的優化設定沒有包含技能,你可以從本地目錄載入:
from azure.ai.agentserver.optimization import load_skills_from_dir
from pathlib import Path
if not config.skills and config.skills_dir:
config.skills.extend(load_skills_from_dir(Path(config.skills_dir)))
記錄設定來源(建議)
請加上一段日誌來確認設定的來源:
import logging
logger = logging.getLogger("my-agent")
logger.info(
"Config source=%s | model=%s | prompt_len=%d | skills=%d",
config.source, model, len(instructions), len(config.skills),
)
完整範例
以下範例展示了一位旅行核准代理,該代理使用優化設定來執行指示、工具與技能:
import json
import logging
import os
from pathlib import Path
from typing import Annotated
from agent_framework import Agent, tool
from agent_framework.foundry import FoundryChatClient
from agent_framework_foundry_hosting import ResponsesHostServer
from azure.identity import DefaultAzureCredential
from pydantic import Field
from azure.ai.agentserver.optimization import load_config, load_skills_from_dir
logger = logging.getLogger(__name__)
@tool(approval_mode="never_require")
def lookup_travel_policy() -> str:
"""Look up the company travel policy rules and limits."""
return json.dumps({
"company": "Contoso Ltd.",
"approval_thresholds": {
"auto": 1500, "manager": 3000,
"director": 7500, "vp": "above 7500"
},
"lodging_per_night": {"domestic": 250, "international": 400},
"airfare": "economy only; business class if flight > 6 hours",
"advance_booking_days": 14,
})
@tool(approval_mode="never_require")
def check_department_budget() -> str:
"""Check the remaining travel budget for the employee's department."""
return json.dumps({
"department": "Engineering",
"total_budget": 50000, "remaining": 14800,
})
@tool(approval_mode="never_require")
def get_flight_alternatives(
destination: Annotated[str, Field(description="The travel destination city")],
) -> str:
"""Find cheaper flight alternatives for the given destination."""
return json.dumps({
"alternatives": [
{"option": "Flexible dates (+/-2 days)", "savings": "$200-800"},
{"option": "Nearby alternate airport", "savings": "$100-400"},
],
})
def main():
# Load optimization config from .agent_configs/
config = load_config()
# Load skills from local directory if not provided by optimization
if not config.skills and config.skills_dir:
config.skills.extend(load_skills_from_dir(Path(config.skills_dir)))
model = config.model or os.environ.get(
"FOUNDRY_MODEL_NAME", "gpt-4.1-mini"
)
instructions = config.compose_instructions()
# Apply optimized tool descriptions
tools = [lookup_travel_policy, check_department_budget, get_flight_alternatives]
config.apply_tool_descriptions(tools)
logger.info(
"Config source=%s | model=%s | prompt_len=%d | skills=%d",
config.source, model, len(instructions), len(config.skills),
)
client = FoundryChatClient(
project_endpoint=os.environ["FOUNDRY_PROJECT_ENDPOINT"],
model=model,
credential=DefaultAzureCredential(),
)
agent = Agent(
client=client,
instructions=instructions,
tools=tools,
default_options={"store": False},
)
server = ResponsesHostServer(agent)
server.run()
if __name__ == "__main__":
main()
運作原理
正常操作:不設定優化環境變數。 設定載入器會
.agent_configs/baseline/讀取並回傳你的基準設定。代理人會依照你原本的指示操作。優化過程中:優化器會將
OPTIMIZATION_CONFIG候選者的設定設定為內嵌 JSON。 您的經紀人會在評估時使用候選人的指示和工具說明。Note
在評估過程中,優化器會針對資料集中的每個任務調用你的代理,因此任何外部工具呼叫都會真正執行。 關於避免意外副作用的指引,請參閱《 agent optimizer 如何運作》。
套用 winner 後:你會執行
azd ai agent optimize apply --candidate <id>,將最佳化的設定檔寫入你專案中的.agent_configs/<candidate_id>/。 然後azd deploy部署已改良配置的代理程式。 關於完整的應用與部署步驟,請參見 「部署勝者」。
你的程式碼在這些狀態之間永遠不會改變。 設定解析是完全自動化的。
組態解析順序
該 load_config() 函式透過優先順序鏈(先配對獲勝)來解析配置:
| 優先順序 | 來源 | 環境變數 | Description |
|---|---|---|---|
| 1 | 內嵌 JSON | OPTIMIZATION_CONFIG |
完整組態作為 JSON 字串 |
| 2 | Resolver API |
OPTIMIZATION_CANDIDATE_ID、OPTIMIZATION_RESOLVE_ENDPOINT |
從優化服務取得候選設定,並將其持久化到本地目錄 |
| 3 | 本地目錄 |
OPTIMIZATION_LOCAL_DIR (預設為 .agent_configs/) |
讀取 baseline/ 或特定候選目錄 |
| 4 | 未設定 | — | 傳回 None。 |
驗證
確認套件可成功匯入,且設定能夠正確載入:
# Verify the package is importable
python -c "from azure.ai.agentserver.optimization import load_config; print('OK')"
# Run locally and check the log output
azd ai agent run
# Expected log: "Config source=baseline | model=gpt-4.1-mini | ..."
相關內容
- 代理優化器概述
- 建立評估資料集與評估器
- 優化客服指示、技能、工具與模型
- 快速入門:優化託管代理人
- Agent Skills 格式 — 可攜式 Agent 技能的開放標準