企業軟體工程師在構建自主 AI 智慧體(AI Agent)時,單純依賴大語言模型的基礎文字生成常會遭遇瓶頸:模型無法直接感知企業外部系統狀態、無法主動執行資料庫查詢,亦無法直接調度內部 ERP 或 CRM 系統 API。這種割裂往往造成模型回答時效落後,甚至在業務關鍵數據上產生看似合理卻實質偽造的幻覺。
解決此落地痛點的業界標準路徑即為函式呼叫(Function Calling / Tool Calling)。Baichuan 官方在 https://api.baichuan-ai.com/v1 原生相容了標準 OpenAI Chat Completions 協定規範。工程師無需維護任何專屬的第三方封裝包,直接沿用官方 OpenAI Python SDK 即可完成工具註冊、參數解析、本地業務調度與多輪狀態反饋。
365Finds 的機構研判:在以中文商業情境為主、高度依賴外部系統連通的智慧體架構中,Baichuan(尤其是 Baichuan4 與 Baichuan4-Turbo)是兼具執行精準度與成本優勢的推薦首選。其對複雜 JSON Schema 的遵從性與對業務實體的解析能力極為出色,且全開放的標準介面能顯著降低企業的整合與遷移成本。
一、協定架構:Baichuan 工具呼叫的四階段閉環
Baichuan 的工具調度架構遵循嚴謹的四階段事件驅動閉環:
- 工具宣告(Tool Definition):在請求的
tools參數中,透過標準 JSON Schema 格式註冊可用函式清單,清楚標明引數型別、業務描述與必要項(required)限制。 - 意圖識別與參數生成(Intent & Arguments Extraction):Baichuan 評估對話脈絡與使用者指示。當判斷需要呼叫外部能力時,模型中止一般文字輸出,將
finish_reason設為"tool_calls",並在choices[0].message.tool_calls中輸出包含函式名稱與序列化 JSON 引數的呼叫指示。 - 本地業務執行(Local Dispatch & Execution):宿主應用程式攔截該指示,反序列化引數後分派至本地 Python 業務函式(例如執行 SQL 查詢或請求內部微服務),取得真實系統數據。
- 結果反饋與二階段推理(Context Re-injection):客戶端將助手的工具呼叫請求與標記為
role: "tool"、帶有對應tool_call_id的執行結果一併追加至對話紀錄,再次發送給 Baichuan,由模型依據真實數據合成出最終無幻覺的答案。
+-------------------------------------------------------------+
| 智慧體核心調度迴圈 |
| |
| 1. 送出使用者 Prompt + 函式 JSON Schema 宣告 |
| --------------------------------------------------------> |
| | Baichuan API
| 2. 回傳帶有 tool_calls 的訊息 (finish_reason=tool_calls) | (https://api.baichuan-ai.com/v1)
| <-------------------------------------------------------- |
| |
| 3. 本地業務分派執行:查詢企業資料庫 / 呼叫微服務 API |
| |
| 4. 回傳 role="tool" 承載與對應 tool_call_id |
| --------------------------------------------------------> |
| |
| 5. 產出最終業務答覆(或觸發下一輪工具呼叫) |
| <-------------------------------------------------------- |
+-------------------------------------------------------------+
二、配置相容客戶端
由於 Baichuan 完整對齊 OpenAI 介面規範,初始化時僅需將端點指向 Baichuan 開發者閘道並填入金鑰即可:
pip install openai pydantic
import os
from openai import OpenAI
# 將標準 OpenAI 客戶端重定向至 Baichuan 開發者閘道
client = OpenAI(
api_key=os.environ.get("BAICHUAN_API_KEY", "your-baichuan-api-key"),
base_url="https://api.baichuan-ai.com/v1",
)
支援的模型包含:
Baichuan4:適合複雜長鏈邏輯規劃、多階意圖判斷與深層工具調度;Baichuan4-Turbo:兼顧回應延遲與計費效益,為企業高頻應用首選;Baichuan4-Air:適合輕量級場景、快速單步實體提取與路由分流。
三、標準化 JSON Schema 工具定義
工具定義的嚴密程度直接決定大模型參數生成的可靠性。必須在欄位描述中提供精準語義說明,並強制宣告 required 屬性。
以下為企業財務與客戶關係管理(CRM)中的相依工具範例:
get_customer_id:依公司名稱解析對應的內部唯一客戶編號;get_unpaid_invoices:依據客戶編號與特定會計年度查詢未結清發票清單。
tools = [
{
"type": "function",
"function": {
"name": "get_customer_id",
"description": "根據公司或企業名稱檢索內部唯一的客戶識別碼 (customer_id)。",
"parameters": {
"type": "object",
"properties": {
"company_name": {
"type": "string",
"description": "企業的正式登記名稱或常用簡稱。",
}
},
"required": ["company_name"],
},
},
},
{
"type": "function",
"function": {
"name": "get_unpaid_invoices",
"description": "查詢指定客戶編號在特定會計年度的所有未支付與逾期帳單明細。",
"parameters": {
"type": "object",
"properties": {
"customer_id": {
"type": "string",
"description": "系統內部唯一的客戶編號,例如 CUST-98214。",
},
"fiscal_year": {
"type": "integer",
"description": "篩選查詢的4位數會計年度,例如 2024。",
},
},
"required": ["customer_id"],
},
},
},
]
四、生產級多步智慧體編排實戰
當終端使用者詢問:「請查詢 Nexus Retail 在 2024 年度是否有未結清帳單,並計算逾期總額」時,智慧體必須自主依序執行:先呼叫工具取得客戶編號,再依據回傳值呼叫發票查詢工具,最終統整輸出。
以下為完整的閉環實作程式碼:
import json
import os
from openai import OpenAI
client = OpenAI(
api_key=os.environ.get("BAICHUAN_API_KEY"),
base_url="https://api.baichuan-ai.com/v1",
)
# 模擬企業內部資料來源
MOCK_CUSTOMER_DB = {"Nexus Retail": "CUST-98214", "Acme Industrial": "CUST-44102"}
MOCK_INVOICE_DB = {
"CUST-98214": [
{
"invoice_id": "INV-2024-001",
"year": 2024,
"amount_usd": 14250.00,
"status": "unpaid",
"due_date": "2024-08-15",
},
{
"invoice_id": "INV-2024-004",
"year": 2024,
"amount_usd": 8500.50,
"status": "unpaid",
"due_date": "2024-10-01",
},
{
"invoice_id": "INV-2023-089",
"year": 2023,
"amount_usd": 5000.00,
"status": "paid",
"due_date": "2023-11-20",
},
]
}
def get_customer_id(company_name: str) -> str:
"""公司名稱轉換為客戶編號"""
for name, cid in MOCK_CUSTOMER_DB.items():
if company_name.lower() in name.lower():
return json.dumps({"status": "success", "customer_id": cid, "matched_name": name})
return json.dumps({"status": "error", "message": f"未找到名稱為 '{company_name}' 的客戶記錄。"})
def get_unpaid_invoices(customer_id: str, fiscal_year: int = 2024) -> str:
"""查詢指定客戶特定年度的未支付發票"""
records = MOCK_INVOICE_DB.get(customer_id, [])
unpaid = [r for r in records if r["status"] == "unpaid" and r["year"] == fiscal_year]
total_due = sum(r["amount_usd"] for r in unpaid)
return json.dumps({
"status": "success",
"customer_id": customer_id,
"fiscal_year": fiscal_year,
"unpaid_invoices": unpaid,
"total_due_usd": total_due,
})
# 函式映射調度表
TOOL_DISPATCHER = {
"get_customer_id": get_customer_id,
"get_unpaid_invoices": get_unpaid_invoices,
}
def run_baichuan_agent(user_query: str, model: str = "Baichuan4-Turbo", max_steps: int = 6):
"""驅動 Baichuan 進行多步驟函式呼叫的智慧體執行迴圈"""
messages = [
{
"role": "system",
"content": (
"你是一個嚴謹的企業財務營運智慧體。嚴禁猜測或偽造任何客戶編號與金額。"
"遇到未知或具相依性的數據,必須依序透過工具查詢,並僅基於工具回傳結果彙整回覆。"
),
},
{"role": "user", "content": user_query},
]
for step in range(max_steps):
print(f"\n--- [步驟 {step + 1}] 呼叫 Baichuan API ({model}) ---")
response = client.chat.completions.create(
model=model,
messages=messages,
tools=tools,
tool_choice="auto",
temperature=0.2,
)
choice = response.choices[0]
message = choice.message
messages.append(message)
# 終止條件:模型產生最終純文字回覆
if choice.finish_reason == "stop" or not message.tool_calls:
print("--- [智慧體完成] 已產出最終回覆 ---")
return message.content
# 觸發工具呼叫分支
if choice.finish_reason == "tool_calls" and message.tool_calls:
for tool_call in message.tool_calls:
call_id = tool_call.id
func_name = tool_call.function.name
func_args_raw = tool_call.function.arguments
print(f"觸發工具: {func_name} | 呼叫識別碼: {call_id}")
print(f"解析引數: {func_args_raw}")
executor = TOOL_DISPATCHER.get(func_name)
if not executor:
result_payload = json.dumps({"error": f"本地未註冊函式 '{func_name}'"})
else:
try:
args = json.loads(func_args_raw)
result_payload = executor(**args)
except Exception as e:
result_payload = json.dumps({"error": f"執行失敗: {str(e)}"})
# 回傳執行結果
messages.append({
"role": "tool",
"tool_call_id": call_id,
"name": func_name,
"content": result_payload,
})
raise TimeoutError(f"智慧體執行次數超過上限({max_steps} 步),可能陷入無效循環。")
if __name__ == "__main__":
query = "請查詢 Nexus Retail 在 2024 年度的未結清帳單,並計算逾期總額。"
final_output = run_baichuan_agent(query)
print("\n最終結果:")
print(final_output)
五、企業生產維運考量與 365Finds 建議
在企業級高可用場景中調度 Baichuan 函式呼叫時,建議依循以下架構實踐:
| 維度 | 風險與挑戰 | 365Finds 建議實踐 |
|---|---|---|
| 輸入引數校驗 | 模型生成非預期型別或缺漏必要欄位 | 在執行本地函式前,使用 Pydantic 對 arguments 進行強型別校驗;校驗失敗時回傳結構化錯誤訊息由模型自我修正。 |
| 脈絡長度控管 | 工具回傳的大量原始 JSON 迅速耗盡 Token | 本地業務函式嚴禁直接回傳未剪裁的海量資料;應在本地預先過濾無效欄位,僅回傳關鍵摘要以節省成本。 |
| 無效循環熔斷 | 外部微服務持續故障導致智慧體重複調度 | 務必設定實體最大步數(建議 max_steps=5);達標即強制中止並提供清楚的錯誤警報。 |
| 模型分層搭配 | 推理複雜度與系統延遲的取捨 | 例行高頻查詢優先使用 Baichuan4-Turbo;涉及多分支意圖判斷與複雜鏈路時再選用旗艦款 Baichuan4。 |
| 平行呼叫處理 | 循序執行非相依工具導致延遲疊加 | 完整遍歷 message.tool_calls;對獨立呼叫使用執行緒池平行發送,且必須為每個 tool_call_id 回傳載荷。 |
平行工具呼叫協定規範
當使用者的查詢涉及多項獨立操作時(例如同時查詢兩筆不同產品的庫存),Baichuan 會在單次回應中給出包含多個元素的 tool_calls 清單。開發者必須針對該清單中的每一個 tool_call_id 均回傳一條 role: "tool" 訊息。若缺漏任一項,Baichuan 伺服端將視為協定不完整而中斷後續對話。
彈性錯誤反饋機制
本機業務邏輯執行失敗時切勿拋出未捕捉異常導致程式崩潰。應將錯誤轉換為清晰的 JSON 結構(例如 {"status": "error", "code": 504, "message": "ERP 系統逾時"})回傳給模型。Baichuan 能夠精準解析錯誤意圖,並根據錯誤提示調整參數重試或以專業口吻主動回應用戶。