經過昨天的訓練,相信大家都已經成功聘請了自己的第一位 AI 員工 ChatCompletionAgent
。今天,我們要介紹一位來自 OpenAI 總部的「官方派遣工」,它不僅資質優異,還自帶強大的工具與雲端管理能力,它就是:OpenAIAssistantAgent
。
相較於 ChatCompletionAgent
這種「白手起家」的員工,OpenAIAssistantAgent
就像一個經驗豐富、裝備齊全的超級經理人。它背後是 OpenAI Assistants API,這套 API 已經為你處理了許多複雜的底層邏輯,讓你能夠更專注於應用層的開發。
OpenAIAssistantAgent
的超能力為什麼它這麼強?因為 Assistants API 提供了幾個核心且開箱即用的功能:
OpenAIAssistantAgent
能夠直接使用這些工具,來分析數據、執行程式碼、或是從你上傳的檔案中檢索資訊。ChatHistory
嗎?在 Assistants API 中,所有的對話歷史都儲存在遠端的 Thread
中。這意味著你可以隨時中斷對話,隔天再回來,Agent 依然記得你們上次的討論內容,大大簡化了狀態管理的複雜性。要請這位派遣工來,你只需要一個 OpenAI API Key。我們將它建立起來,並為它配置一個強大的工具。
using Microsoft.SemanticKernel;
using Microsoft.Extensions.Configuration;
using Microsoft.SemanticKernel.Agents.OpenAI;
using OpenAI.Assistants;
using System.ClientModel;
using Microsoft.SemanticKernel.ChatCompletion;
var config = new ConfigurationBuilder()
.AddUserSecrets<Program>()
.Build();
// 步驟一:建立 OpenAI 客戶端並設定助理代理
AssistantClient client = OpenAIAssistantAgent.CreateOpenAIClient(new ApiKeyCredential(config["OpenAI:ApiKey"]!)).GetAssistantClient();
// 步驟二:建立具備程式碼解譯功能的助理
Assistant assistant =
await client.CreateAssistantAsync(
"gpt-4o-mini",
name: "CodeInterpreterAgent",
instructions: """
您是一個數據分析專家。請分析提供的數據並提供洞察。
總是使用 Markdown 格式回應。
""",
enableCodeInterpreter: true);
// 建立 Semantic Kernel 的 OpenAI 助理代理包裝器
OpenAIAssistantAgent agent = new(assistant, client);
// 步驟三:建立對話執行緒並開始互動
var chatThread = new OpenAIAssistantAgentThread(client);
// 顯示歡迎訊息
Console.WriteLine("你好,我是你的數據分析師助理。");
// 步驟四:向助理發送數據分析請求
await foreach (ChatMessageContent response in agent.InvokeAsync(new ChatMessageContent(AuthorRole.User, "請幫我計算 100 到 200 之間所有數字的總和。"), chatThread))
{
// 顯示助理的角色和回應內容
Console.WriteLine($"{response.Role}: {response.Content}");
}
這段程式碼中,我們啟用 Code Interpreter
的功能。當你運行程式時,你會看到它會自主地生成 Python 程式碼 sum(range(100, 201))
,並執行它來得到正確的答案。這個過程完全是自動的,你不需要手動編寫任何程式碼來調用這個工具。
File Search
更是另一個改變遊戲規則的強大功能。你可以上傳文件,然後讓 Agent 成為你的「私人文檔問答專家」。
// 步驟一:建立向量存儲用於檔案搜尋
VectorStoreClient storeClient = new(config["OpenAI:ApiKey"]!);
CreateVectorStoreOperation operation = await storeClient.CreateVectorStoreAsync(waitUntilCompleted: true);
string storeId = operation.VectorStoreId;
// 步驟二:準備要上傳的檔案
string fileName = "test-document.txt";
// 用於追蹤上傳的檔案參考
Dictionary<string, OpenAIFile> fileReferences = [];
// 步驟三:上傳檔案到 OpenAI 並加入向量存儲
Console.WriteLine("Uploading files...");
OpenAIFileClient fileClient = new(config["OpenAI:ApiKey"]!);
// 上傳檔案,指定用途為助理服務
OpenAIFile fileInfo = await fileClient.UploadFileAsync(fileName, FileUploadPurpose.Assistants);
// 將上傳的檔案加入向量存儲中,等待處理完成
await storeClient.AddFileToVectorStoreAsync(storeId, fileInfo.Id, waitUntilCompleted: true);
fileReferences.Add(fileInfo.Id, fileInfo);
// 步驟四:建立具備檔案搜尋功能的助理
// 啟用 enableFileSearch 並指定向量存儲 ID,讓助理可以搜尋檔案內容
assistant =
await client.CreateAssistantAsync(
"gpt-4o-mini",
name: "DocumentExpertAgent",
instructions: """
你是一位專門回答文件內容的專家。
請根據提供的檔案內容來回答問題。
""",
enableFileSearch: true,
vectorStoreId: storeId);
// 步驟五:建立新的對話執行緒和代理包裝器
chatThread = new OpenAIAssistantAgentThread(client);
agent = new(assistant, client);
// 顯示歡迎訊息
Console.WriteLine("請提出你想問的文件問題。");
// 步驟六:向助理發送檔案相關問題並接收回應
// 助理將會搜尋上傳的檔案內容來回答問題
await foreach (ChatMessageContent response in agent.InvokeAsync(new ChatMessageContent(AuthorRole.User, "文件中有沒有提到 Semantic Kernel 概念?"), chatThread))
{
// 顯示助理的角色和回應內容
Console.WriteLine($"{response.Role}: {response.Content}");
}
當你提出問題時,DocumentExpertAgent
會自動在指定的檔案中搜尋相關內容,並根據找到的資訊來回答你的問題。這讓 RAG (檢索增強生成) 的應用變得異常簡單,幾乎是零程式碼實現。
OpenAIAssistantAgent
是 Semantic Kernel 整合 OpenAI 最強大的範例之一。它將複雜的工具調用與對話管理,轉化為簡單的設定,讓你能夠專注於更核心的商業邏輯。你可以根據你的需求,選擇最適合的 Agent 類型:如果你需要完全的控制權與自定義,ChatCompletionAgent
是你的好選擇;如果你想快速利用 OpenAI 的強大功能,OpenAIAssistantAgent
絕對是首選。