當我們將某些代理程式從實驗階段轉換至發行候選階段時,我們已更新 API 以簡化和簡化其使用。 請參閱特定案例指南,以瞭解如何更新現有的程序代碼,以使用最新的可用 API。
常見的代理程式調用 API
在 1.43.0 版中,我們將發行新的通用代理程式調用 API,以允許所有代理程式類型透過一般 API 叫用。
為了啟用這個新的 API,我們將介紹一個稱為AgentThread的概念,這代表對話線程,並抽象化各類代理程式在線程管理上的不同需求。 對於某些代理程式類型,未來也會允許不同的線程實作與相同的代理程式搭配使用。
我們引進的常見 Invoke 方法可讓您提供想要傳遞給代理的訊息,以及選擇性的 AgentThread。 如果提供了AgentThread,這將繼續在AgentThread上的對話。 如果未提供AgentThread,則會建立新的預設線程,並作為回應的一部分傳回。
您也可以手動建立 AgentThread 實例,例如,如果您有來自基礎代理程式服務的線程標識碼,而且您想要繼續該線程的情況。 您也可以自訂執行緒的選項,例如關聯工具。
以下是一個範例,說明任何代理程式現在如何與無代理依賴的程式碼搭配使用。
private async Task UseAgentAsync(Agent agent, AgentThread? agentThread = null)
{
// Invoke the agent, and continue the existing thread if provided.
var responses = agent.InvokeAsync(new ChatMessageContent(AuthorRole.User, "Hi"), agentThread);
// Output results.
await foreach (AgentResponseItem<ChatMessageContent> response in responses)
{
Console.WriteLine(response);
agentThread = response.Thread;
}
// Delete the thread if required.
if (agentThread is not null)
{
await agentThread.DeleteAsync();
}
}
這些變更已套用在:
Azure AI 代理程式線程選項
AzureAIAgent目前只支援 類型AzureAIAgentThread為的線程。
除了允許在代理程式調用上自動為您建立線程之外,您也可以手動建構 的 AzureAIAgentThread實例。
AzureAIAgentThread 支援使用自定義工具和元數據來建立,還有用於開啟對話的訊息。
AgentThread thread = new AzureAIAgentThread(
agentsClient,
messages: seedMessages,
toolResources: tools,
metadata: metadata);
您也可以建構 繼續現有交談的 AzureAIAgentThread 實例。
AgentThread thread = new AzureAIAgentThread(
agentsClient,
id: "my-existing-thread-id");
基岩代理程式線程選項
BedrockAgent目前只支援 類型BedrockAgentThread為的線程。
除了允許在代理程式調用上自動為您建立線程之外,您也可以手動建構 的 BedrockAgentThread實例。
AgentThread thread = new BedrockAgentThread(amazonBedrockAgentRuntimeClient);
您也可以建構 繼續現有交談的 BedrockAgentThread 實例。
AgentThread thread = new BedrockAgentThread(
amazonBedrockAgentRuntimeClient,
sessionId: "my-existing-session-id");
聊天完成代理線程選項
ChatCompletionAgent目前只支援 類型ChatHistoryAgentThread為的線程。
ChatHistoryAgentThread 會使用記憶體 ChatHistory 內部物件將訊息儲存在線程上。
除了允許在代理程式調用上自動為您建立線程之外,您也可以手動建構 的 ChatHistoryAgentThread實例。
AgentThread thread = new ChatHistoryAgentThread();
您可以建構的實例,並延續現有的交談,方法是將現有的訊息納入物件。
ChatHistory chatHistory = new([new ChatMessageContent(AuthorRole.User, "Hi")]);
AgentThread thread = new ChatHistoryAgentThread(chatHistory: chatHistory);
OpenAI Assistant 線程選項
OpenAIAssistantAgent目前只支援 類型OpenAIAssistantAgentThread為的線程。
除了允許在代理程式調用上自動為您建立線程之外,您也可以手動建構 的 OpenAIAssistantAgentThread實例。
OpenAIAssistantAgentThread 支援使用自定義工具和元數據來建立,還有用於開啟對話的訊息。
AgentThread thread = new OpenAIAssistantAgentThread(
assistantClient,
messages: seedMessages,
codeInterpreterFileIds: fileIds,
vectorStoreId: "my-vector-store",
metadata: metadata);
您也可以建構 繼續現有交談的 OpenAIAssistantAgentThread 實例。
AgentThread thread = new OpenAIAssistantAgentThread(
assistantClient,
id: "my-existing-thread-id");
OpenAIAssistantAgent C# 移轉指南
我們最近在OpenAIAssistantAgent和語意核心代理程序架構周圍進行了重大轉變。
這些變更已套用在:
這些變更的目的是:
- 請與我們的
AzureAIAgent使用模式保持一致。 - 修正靜態初始化模式的 Bug。
- 避免因為我們對基礎 SDK 的抽象而限制功能。
本指南提供將 C# 程式代碼從舊實作移轉至新程序代碼的逐步指示。 變更包括建立助理、管理助理生命週期、處理線程、檔案和向量存放區的更新。
1. 用戶端實例化
先前需要OpenAIClientProvider來創建任何OpenAIAssistantAgent。 此相依性已簡化。
新方法
OpenAIClient client = OpenAIAssistantAgent.CreateAzureOpenAIClient(new AzureCliCredential(), new Uri(endpointUrl));
AssistantClient assistantClient = client.GetAssistantClient();
老路 (已被取代)
var clientProvider = new OpenAIClientProvider(...);
2. 助手生命週期
建立小幫手
您現在可以利用現有或新的 Assistant 定義從OpenAIAssistantAgent直接實例化AssistantClient。
新方法
Assistant definition = await assistantClient.GetAssistantAsync(assistantId);
OpenAIAssistantAgent agent = new(definition, client);
外掛程式可以在初始化期間直接加入
KernelPlugin plugin = KernelPluginFactory.CreateFromType<YourPlugin>();
Assistant definition = await assistantClient.GetAssistantAsync(assistantId);
OpenAIAssistantAgent agent = new(definition, client, [plugin]);
使用擴充方法建立新的小幫手定義:
Assistant assistant = await assistantClient.CreateAssistantAsync(
model,
name,
instructions: instructions,
enableCodeInterpreter: true);
老路 (已被取代)
先前,助理定義是以間接方式管理的。
3. 叫用代理程式
您可以直接指定 RunCreationOptions ,啟用基礎 SDK 功能的完整存取權。
新方法
RunCreationOptions options = new(); // configure as needed
var result = await agent.InvokeAsync(options);
老路 (已被取代)
var options = new OpenAIAssistantInvocationOptions();
刪除助理功能
您可以直接使用 AssistantClient 管理助理的刪除。
await assistantClient.DeleteAssistantAsync(agent.Id);
5. 線程生命週期
建立線程
線程現在會透過 AssistantAgentThread來管理。
新方法
var thread = new AssistantAgentThread(assistantClient);
// Calling CreateAsync is an optional step.
// A thread will be created automatically on first use if CreateAsync was not called.
// Note that CreateAsync is not on the AgentThread base implementation since not all
// agent services support explicit thread creation.
await thread.CreateAsync();
老路 (已被取代)
先前,執行緒管理是間接或代理綁定。
線程刪除
var thread = new AssistantAgentThread(assistantClient, "existing-thread-id");
await thread.DeleteAsync();
6. 檔案生命週期
檔案建立與刪除現在會利用 OpenAIFileClient。
檔案上傳
string fileId = await client.UploadAssistantFileAsync(stream, "<filename>");
檔案刪除
await client.DeleteFileAsync(fileId);
7. 向量存放區生命週期
向量儲存區會透過 VectorStoreClient 及方便的擴充方法直接管理。
向量存放區建立
string vectorStoreId = await client.CreateVectorStoreAsync([fileId1, fileId2], waitUntilCompleted: true);
向量存放區刪除
await client.DeleteVectorStoreAsync(vectorStoreId);
回溯相容性
已取代的模式會標示為 [Obsolete]。 若要隱藏過時的警告 (CS0618),請更新您的項目檔,如下所示:
<PropertyGroup>
<NoWarn>$(NoWarn);CS0618</NoWarn>
</PropertyGroup>
此移轉指南可協助您順暢地轉換至新的實作、簡化用戶端初始化、資源管理,以及與 語意核心 .NET SDK 整合。
這很重要
對於升級至 語意核心 Python 1.26.1 或更新版本的開發人員,已引進重大更新和破壞性變更,以在接近一般可用性(GA)時改善我們的代理框架。
這些變更已套用在:
先前的變更已套用在:
本指南提供將 Python 程式代碼從舊實作移轉至新實作的逐步指示。
代理匯入
所有代理程式匯入路徑都已合併在下 semantic_kernel.agents。
已更新匯入樣式
from semantic_kernel.agents import (
AutoGenConversableAgent,
AzureAIAgent,
AzureAssistantAgent,
BedrockAgent,
ChatCompletionAgent,
OpenAIAssistantAgent,
)
先前的匯入樣式 (已淘汰):
from semantic_kernel.agents import ChatCompletionAgent
from semantic_kernel.agents.autogen import AutoGenConversableAgent
from semantic_kernel.agents.azure_ai import AzureAIAgent
from semantic_kernel.agents.bedrock import BedrockAgent
from semantic_kernel.agents.open_ai import AzureAssistantAgent, OpenAIAssistantAgent
常見的代理程式調用 API
從語意核心 Python 1.26.0 和更新版本開始,我們引進了新的通用抽象概念,以管理所有代理程式的線程。 針對每個代理程式,我們現在公開一個實作AgentThread基類的線程類別,允許透過create()和delete()等方法進行內容管理。
代理人回應get_response(...)、invoke(...)、invoke_stream(...)現在會傳回一個AgentResponseItem[ChatMessageContent],具有兩個屬性。
message: TMessage # Usually ChatMessageContent
thread: AgentThread # Contains the concrete type for the given agent
將訊息新增至線程
訊息應該透過 messages 引數新增至線程,作為代理程式的方法 get_response(...)、invoke(...) 或 invoke_stream(...) 的一部分。
Azure AI 代理程式線程
AzureAIAgentThread可以這樣建立,如下所示:
from semantic_kernel.agents import AzureAIAgentThread
thread = AzureAIAgentThread(
client: AIProjectClient, # required
messages: list[ThreadMessageOptions] | None = None, # optional
metadata: dict[str, str] | None = None, # optional
thread_id: str | None = None, # optional
tool_resources: "ToolResources | None" = None, # optional
)
提供thread_id(字串)可讓您繼續現有的交談。 如果省略,則會建立新的線程,並作為代理程序回應的一部分傳回。
完整的實作範例:
import asyncio
from azure.identity.aio import DefaultAzureCredential
from semantic_kernel.agents import AzureAIAgent, AzureAIAgentSettings, AzureAIAgentThread
USER_INPUTS = [
"Why is the sky blue?",
"What are we talking about?",
]
async def main() -> None:
ai_agent_settings = AzureAIAgentSettings.create()
async with (
DefaultAzureCredential() as creds,
AzureAIAgent.create_client(credential=creds) as client,
):
# 1. Create an agent on the Azure AI agent service
agent_definition = await client.agents.create_agent(
model=ai_agent_settings.model_deployment_name,
name="Assistant",
instructions="Answer the user's questions.",
)
# 2. Create a Semantic Kernel agent for the Azure AI agent
agent = AzureAIAgent(
client=client,
definition=agent_definition,
)
# 3. Create a thread for the agent
# If no thread is provided, a new thread will be
# created and returned with the initial response
thread: AzureAIAgentThread = None
try:
for user_input in USER_INPUTS:
print(f"# User: {user_input}")
# 4. Invoke the agent with the specified message for response
response = await agent.get_response(messages=user_input, thread=thread)
print(f"# {response.content}: {response}")
thread = response.thread
finally:
# 6. Cleanup: Delete the thread and agent
await thread.delete() if thread else None
await client.agents.delete_agent(agent.id)
if __name__ == "__main__":
asyncio.run(main())
基岩代理程式線程
BedrockAgent 使用 BedrockAgentThread 來管理交談歷程記錄和上下文。 您可以提供 session_id 來繼續或開啟全新的交談情境。
from semantic_kernel.agents import BedrockAgentThread
thread = BedrockAgentThread(
bedrock_runtime_client: Any,
session_id: str | None = None,
)
如果未提供session_id,則會自動建立新的上下文。
完整的實作範例:
import asyncio
from semantic_kernel.agents import BedrockAgent, BedrockAgentThread
async def main():
bedrock_agent = await BedrockAgent.create_and_prepare_agent(
"semantic-kernel-bedrock-agent",
instructions="You are a friendly assistant. You help people find information.",
)
# Create a thread for the agent
# If no thread is provided, a new thread will be
# created and returned with the initial response
thread: BedrockAgentThread = None
try:
while True:
user_input = input("User:> ")
if user_input == "exit":
print("\n\nExiting chat...")
break
# Invoke the agent
# The chat history is maintained in the session
response = await bedrock_agent.get_response(
input_text=user_input,
thread=thread,
)
print(f"Bedrock agent: {response}")
thread = response.thread
except KeyboardInterrupt:
print("\n\nExiting chat...")
return False
except EOFError:
print("\n\nExiting chat...")
return False
finally:
# Delete the agent
await bedrock_agent.delete_agent()
await thread.delete() if thread else None
if __name__ == "__main__":
asyncio.run(main())
聊天記錄代理程式線程
ChatCompletionAgent使用 ChatHistoryAgentThread 來管理交談歷程記錄。 它可以初始化,如下所示:
from semantic_kernel.agents import ChatHistoryAgentThread
thread = ChatHistoryAgentThread(
chat_history: ChatHistory | None = None,
thread_id: str | None = None
)
提供thread_id可讓現有交談得以繼續。 省略它會建立新的線程。 持續性對話內容支援線程狀態的串行化和解除凍結。
完整的實作範例:
import asyncio
from semantic_kernel.agents import ChatCompletionAgent, ChatHistoryAgentThread
from semantic_kernel.connectors.ai.open_ai import AzureChatCompletion
# Simulate a conversation with the agent
USER_INPUTS = [
"Hello, I am John Doe.",
"What is your name?",
"What is my name?",
]
async def main():
# 1. Create the agent by specifying the service
agent = ChatCompletionAgent(
service=AzureChatCompletion(),
name="Assistant",
instructions="Answer the user's questions.",
)
# 2. Create a thread to hold the conversation
# If no thread is provided, a new thread will be
# created and returned with the initial response
thread: ChatHistoryAgentThread = None
for user_input in USER_INPUTS:
print(f"# User: {user_input}")
# 3. Invoke the agent for a response
response = await agent.get_response(
messages=user_input,
thread=thread,
)
print(f"# {response.name}: {response}")
# 4. Store the thread, which allows the agent to
# maintain conversation history across multiple messages.
thread = response.thread
# 5. Cleanup: Clear the thread
await thread.delete() if thread else None
if __name__ == "__main__":
asyncio.run(main())
OpenAI 助理討論串
AzureAssistantAgent和OpenAIAssistantAgent使用AssistantAgentThread管理交談歷程記錄和上下文。
from semantic_kernel.agents import ChatHistoryAgentThread
thread = AssistantAgentThread(
client: AsyncOpenAI,
thread_id: str | None = None,
messages: Iterable["ThreadCreateMessage"] | NotGiven = NOT_GIVEN,
metadata: dict[str, Any] | NotGiven = NOT_GIVEN,
tool_resources: ToolResources | NotGiven = NOT_GIVEN,
)
如果提供thread_id,則會繼續現有的交談,否則會建立新的討論串。
完整的實作範例:
# Copyright (c) Microsoft. All rights reserved.
import asyncio
from semantic_kernel.agents import AzureAssistantAgent
# Simulate a conversation with the agent
USER_INPUTS = [
"Why is the sky blue?",
"What is the speed of light?",
"What have we been talking about?",
]
async def main():
# 1. Create the client using Azure OpenAI resources and configuration
client, model = AzureAssistantAgent.setup_resources()
# 2. Create the assistant on the Azure OpenAI service
definition = await client.beta.assistants.create(
model=model,
instructions="Answer questions about the world in one sentence.",
name="Assistant",
)
# 3. Create a Semantic Kernel agent for the Azure OpenAI assistant
agent = AzureAssistantAgent(
client=client,
definition=definition,
)
# 4. Create a new thread for use with the assistant
# If no thread is provided, a new thread will be
# created and returned with the initial response
thread = None
try:
for user_input in USER_INPUTS:
print(f"# User: '{user_input}'")
# 6. Invoke the agent for the current thread and print the response
response = await agent.get_response(messages=user_input, thread=thread)
print(f"# {response.name}: {response}")
thread = response.thread
finally:
# 7. Clean up the resources
await thread.delete() if thread else None
await agent.client.beta.assistants.delete(assistant_id=agent.id)
if __name__ == "__main__":
asyncio.run(main())
代理程式調用的訊息輸入
先前的實作只允許單一訊息輸入至例如get_response(...)、invoke(...)及invoke_stream(...)等方法。 我們現在已更新這些方法以支援多個 messages (str | ChatMessageContent | list[str | ChatMessageContent])。 訊息輸入必須以關鍵字參數傳入 messages,例如 agent.get_response(messages="user input") 或 agent.invoke(messages="user input")。
代理程式調用方法需要更新,如下所示:
舊方式
response = await agent.get_response(message="some user input", thread=thread)
新方法
response = await agent.get_response(messages=["some initial inputer", "other input"], thread=thread)
AzureAIAgent
在 語意核心 Python 1.26.0+中, AzureAIAgent 線程建立現在會透過 AzureAIAgentThread 物件進行管理,而不是直接在用戶端上管理。
舊方式
thread = await client.agents.create_thread()
新方法
from semantic_kernel.agents import AzureAIAgentThread
thread = AzureAIAgentThread(
client: AIProjectClient, # required
messages: list[ThreadMessageOptions] | None = None, # optional
metadata: dict[str, str] | None = None, # optional
thread_id: str | None = None, # optional
tool_resources: "ToolResources | None" = None, # optional
)
如果最初未提供 thread_id,則會在代理程序回應中建立並回傳新的執行緒。
ChatCompletionAgent
ChatCompletionAgent已更新 ,以簡化服務組態、外掛程式處理和函式呼叫行為。 以下是移轉時應考慮的重要變更。
服務說明
您現在可以直接將服務指定為代理程式建構函式的一部分:
新方法
from semantic_kernel.agents import ChatCompletionAgent
from semantic_kernel.connectors.ai.open_ai import AzureChatCompletion
agent = ChatCompletionAgent(
service=AzureChatCompletion(),
name="<name>",
instructions="<instructions>",
)
注意:當同時提供內核和服務時,如果其共用相同的service_id或ai_model_id,則服務會優先。 否則,如果它們是單獨的,核心上註冊的第一個 AI 服務將會被使用。
舊方式 (仍然有效)
先前,您會先將服務新增至核心,然後將核心傳遞至代理程式:
from semantic_kernel.agents import ChatCompletionAgent
from semantic_kernel.connectors.ai.open_ai import AzureChatCompletion
kernel = Kernel()
kernel.add_service(AzureChatCompletion())
agent = ChatCompletionAgent(
kernel=kernel,
name="<name>",
instructions="<instructions>",
)
2.新增外掛程式
外掛程式現在可以透過建構函式直接提供:
新方法
from semantic_kernel.agents import ChatCompletionAgent
from semantic_kernel.connectors.ai.open_ai import AzureChatCompletion
agent = ChatCompletionAgent(
service=AzureChatCompletion(),
name="<name>",
instructions="<instructions>",
plugins=[SamplePlugin()],
)
舊方式 (仍然有效)
先前必須分別將外掛程式新增至核心:
from semantic_kernel.agents import ChatCompletionAgent
from semantic_kernel.connectors.ai.open_ai import AzureChatCompletion
kernel = Kernel()
kernel.add_plugin(SamplePlugin())
agent = ChatCompletionAgent(
kernel=kernel,
name="<name>",
instructions="<instructions>",
)
注意:這兩種方法都是有效的,但直接指定外掛程式可簡化初始化。
3. 叫用代理程式
您現在有兩種方式可以叫用代理程式。 新的方法會直接擷取單一回應,而舊方法則支援串流。
新方式 (沒有對話線程/內容)
response = await agent.get_response(messages="user input")
# response is of type AgentResponseItem[ChatMessageContent]
注意:如果下一個回應未使用傳回的線程,交談將會使用新的線程,因此不會繼續進行先前的內容。
新方法(具情境的單一回應)
thread = ChatHistoryAgentThread()
for user_input in ["First user input", "Second User Input"]:
response = await agent.get_response(messages=user_input, thread=thread)
# response is of type AgentResponseItem[ChatMessageContent]
thread = response.thread
舊方式 (不再有效)
chat_history = ChatHistory()
chat_history.add_user_message("<user_input>")
response = agent.get_response(message="user input", chat_history=chat_history)
4. 控制函數呼叫
在代理程式建構函式內指定服務時,現在可以直接控制函式呼叫行為:
agent = ChatCompletionAgent(
service=AzureChatCompletion(),
name="<name>",
instructions="<instructions>",
plugins=[MenuPlugin()],
function_choice_behavior=FunctionChoiceBehavior.Auto(
filters={"included_functions": ["get_specials", "get_item_price"]}
),
)
注意:先前,函式呼叫組態需要核心或服務物件上的個別設定。 如果執行設定指定的service_id或ai_model_id與 AI 服務組態相同,則執行設定中定義的函式呼叫行為(通過KernelArguments)將優先於在建構函式中設定的函式選擇行為。
這些更新可增強簡單性和可設定性,讓 ChatCompletionAgent 更容易整合和維護。
OpenAIAssistantAgent
AzureAssistantAgent和 OpenAIAssistantAgent 變更包括建立助理、建立線程、處理外掛程式、使用程式代碼解釋器工具、使用檔案搜尋工具,以及將聊天訊息新增至線程的更新。
設定資源
舊方式
用戶端 AsyncAzureOpenAI 是在建立 Agent 物件的一部分建立。
agent = await AzureAssistantAgent.create(
deployment_name="optional-deployment-name",
api_key="optional-api-key",
endpoint="optional-endpoint",
ad_token="optional-ad-token",
ad_token_provider=optional_callable,
default_headers={"optional_header": "optional-header-value"},
env_file_path="optional-env-file-path",
env_file_encoding="optional-env-file-encoding",
...,
)
新方法
代理程式提供靜態方法來建立指定資源的必要用戶端,其中方法層級關鍵詞自變數優先於現有 .env 檔案中的環境變數和值。
client, model = AzureAssistantAgent.setup_resources(
ad_token="optional-ad-token",
ad_token_provider=optional_callable,
api_key="optional-api-key",
api_version="optional-api-version",
base_url="optional-base-url",
default_headers="optional-default-headers",
deployment_name="optional-deployment-name",
endpoint="optional-endpoint",
env_file_path="optional-env-file-path",
env_file_encoding="optional-env-file-encoding",
token_scope="optional-token-scope",
)
1.建立助理
舊方式
agent = await AzureAssistantAgent.create(
kernel=kernel,
service_id=service_id,
name=AGENT_NAME,
instructions=AGENT_INSTRUCTIONS,
enable_code_interpreter=True,
)
或
agent = await OpenAIAssistantAgent.create(
kernel=kernel,
service_id=service_id,
name=<name>,
instructions=<instructions>,
enable_code_interpreter=True,
)
新方法
# Azure AssistantAgent
# Create the client using Azure OpenAI resources and configuration
client, model = AzureAssistantAgent.setup_resources()
# Create the assistant definition
definition = await client.beta.assistants.create(
model=model,
instructions="<instructions>",
name="<name>",
)
# Create the agent using the client and the assistant definition
agent = AzureAssistantAgent(
client=client,
definition=definition,
)
或
# OpenAI Assistant Agent
# Create the client using OpenAI resources and configuration
client, model = OpenAIAssistantAgent.setup_resources()
# Create the assistant definition
definition = await client.beta.assistants.create(
model=model,
instructions="<instructions>",
name="<name>",
)
# Create the agent using the client and the assistant definition
agent = OpenAIAssistantAgent(
client=client,
definition=definition,
)
2.建立線程
舊方式
thread_id = await agent.create_thread()
新方法
from semantic_kernel.agents AssistantAgentThread, AzureAssistantAgent
client, model = AzureAssistantAgent.setup_resources()
# You may create a thread based on an existing thread id
# thread = AssistantAgentThread(client=client, thread_id="existing-thread-id")
# Otherwise, if not specified, a thread will be created during the first invocation
# and returned as part of the response
thread = None
async for response in agent.invoke(messages="user input", thread=thread):
# handle response
print(response)
thread = response.thread
3.處理外掛程式
舊方式
# Create the instance of the Kernel
kernel = Kernel()
# Add the sample plugin to the kernel
kernel.add_plugin(plugin=MenuPlugin(), plugin_name="menu")
agent = await AzureAssistantAgent.create(
kernel=kernel,
name="<name>",
instructions="<instructions>"
)
注意:仍可透過核心管理外掛程式。 如果您未提供核心,則會在代理程式建立期間自動建立核心,並將外掛程式新增至該實例。
新方法
# Create the client using Azure OpenAI resources and configuration
client, model = AzureAssistantAgent.setup_resources()
# Create the assistant definition
definition = await client.beta.assistants.create(
model=model,
instructions="<instructions>",
name="<name>",
)
# Create the agent with plugins passed in as a list
agent = AzureAssistantAgent(
client=client,
definition=definition,
plugins=[MenuPlugin()],
)
如需完整詳細數據,請參閱 範例實作 。
4.使用程式代碼解釋器工具
舊方式
csv_file_path = ...
agent = await AzureAssistantAgent.create(
kernel=kernel,
name="<name>",
instructions="<instructions>",
enable_code_interpreter=True,
code_interpreter_filenames=[csv_file_path],
)
新方法
# Create the client using Azure OpenAI resources and configuration
client, model = AzureAssistantAgent.setup_resources()
csv_file_path = ...
# Load the CSV file as a FileObject
with open(csv_file_path, "rb") as file:
file = await client.files.create(file=file, purpose="assistants")
# Get the code interpreter tool and resources
code_interpreter_tool, code_interpreter_tool_resource = AzureAssistantAgent.configure_code_interpreter_tool(file.id)
# Create the assistant definition
definition = await client.beta.assistants.create(
model=model,
name="<name>",
instructions="<instructions>.",
tools=code_interpreter_tool,
tool_resources=code_interpreter_tool_resource,
)
# Create the AzureAssistantAgent instance using the client and the assistant definition
agent = AzureAssistantAgent(
client=client,
definition=definition,
)
如需完整詳細數據,請參閱 範例實作 。
5.使用檔案搜尋工具
舊方式
pdf_file_path = ...
agent = await AzureAssistantAgent.create(
kernel=kernel,
service_id=service_id,
name=AGENT_NAME,
instructions=AGENT_INSTRUCTIONS,
enable_file_search=True,
vector_store_filenames=[pdf_file_path],
)
新方法
# Create the client using Azure OpenAI resources and configuration
client, model = AzureAssistantAgent.setup_resources()
pdf_file_path = ...
# Load the employees PDF file as a FileObject
with open(pdf_file_path, "rb") as file:
file = await client.files.create(file=file, purpose="assistants")
# Create a vector store specifying the file ID to be used for file search
vector_store = await client.beta.vector_stores.create(
name="step4_assistant_file_search",
file_ids=[file.id],
)
file_search_tool, file_search_tool_resources = AzureAssistantAgent.configure_file_search_tool(vector_store.id)
# Create the assistant definition
definition = await client.beta.assistants.create(
model=model,
instructions="Find answers to the user's questions in the provided file.",
name="FileSearch",
tools=file_search_tool,
tool_resources=file_search_tool_resources,
)
# Create the AzureAssistantAgent instance using the client and the assistant definition
agent = AzureAssistantAgent(
client=client,
definition=definition,
)
如需完整詳細數據,請參閱 範例實作 。
6.將聊天訊息新增至線程
舊方式
await agent.add_chat_message(
thread_id=thread_id,
message=ChatMessageContent(role=AuthorRole.USER, content=user_input)
)
新方法
注意:如果您傳入 ChatMessageContent,舊方法仍可運作,但您現在可以傳遞簡單的字串。
await agent.add_chat_message(
thread_id=thread_id,
message=user_input,
)
7. 清除資源
舊方式
await agent.delete_file(file_id)
await agent.delete_thread(thread_id)
await agent.delete()
新方法
await client.files.delete(file_id)
await thread.delete()
await client.beta.assistants.delete(agent.id)
處理結構化輸出
舊方式
舊方法無法使用
新方法
# Define a Pydantic model that represents the structured output from the OpenAI service
class ResponseModel(BaseModel):
response: str
items: list[str]
# Create the client using Azure OpenAI resources and configuration
client, model = AzureAssistantAgent.setup_resources()
# Create the assistant definition
definition = await client.beta.assistants.create(
model=model,
name="<name>",
instructions="<instructions>",
response_format=AzureAssistantAgent.configure_response_format(ResponseModel),
)
# Create the AzureAssistantAgent instance using the client and the assistant definition
agent = AzureAssistantAgent(
client=client,
definition=definition,
)
如需完整詳細數據,請參閱 範例實作 。
此移轉指南應協助您將程式代碼更新為新的實作,並利用用戶端型設定和增強功能。
Java 中無法使用代理程式。