共用方式為


語意核心到代理程式架構移轉指南

Microsoft Agent Framework 的優點

  • 簡化的 API: 降低複雜性和樣板代碼。
  • 更好的效能:優化物件建立和記憶體使用。
  • 統一界面: 不同 AI 提供商之間的一致模式。
  • 增強的開發人員體驗:更直觀且可發現的 API。

下列各節摘要說明語意核心代理程式架構與 Microsoft 代理程式架構之間的主要差異,以協助您移轉程式碼。

1. 命名空間更新

語意核心

using Microsoft.SemanticKernel;
using Microsoft.SemanticKernel.Agents;

代理架構

代理程式架構命名空間位於 Microsoft.Agents.AI。 代理程式架構使用核心 AI 訊息和內容類型 Microsoft.Extensions.AI 進行元件之間的通訊。

using Microsoft.Extensions.AI;
using Microsoft.Agents.AI;

2. 代理創建簡化

語意核心

語義核心中的每個代理都依賴於一個 Kernel 實例,如果未提供,則有一個空的 Kernel

 Kernel kernel = Kernel
    .AddOpenAIChatClient(modelId, apiKey)
    .Build();

 ChatCompletionAgent agent = new() { Instructions = ParrotInstructions, Kernel = kernel };

Azure AI Foundry 需要先在雲端中建立代理程式資源,才能建立使用它的本機代理程式類別。

PersistentAgentsClient azureAgentClient = AzureAIAgent.CreateAgentsClient(azureEndpoint, new AzureCliCredential());

PersistentAgent definition = await azureAgentClient.Administration.CreateAgentAsync(
    deploymentName,
    instructions: ParrotInstructions);

AzureAIAgent agent = new(definition, azureAgentClient);

代理架構

透過所有主要提供者提供的擴充功能,在代理程式架構中建立代理程式變得更加簡單。

AIAgent openAIAgent = chatClient.CreateAIAgent(instructions: ParrotInstructions);
AIAgent azureFoundryAgent = await persistentAgentsClient.CreateAIAgentAsync(instructions: ParrotInstructions);
AIAgent openAIAssistantAgent = await assistantClient.CreateAIAgentAsync(instructions: ParrotInstructions);

此外,對於託管代理程式提供者,您也可以使用該 GetAIAgent 方法從現有託管代理程式擷取代理程式。

AIAgent azureFoundryAgent = await persistentAgentsClient.GetAIAgentAsync(agentId);

3. 代理執行緒建立

語意核心

呼叫端必須知道執行緒類型並手動建立它。

// Create a thread for the agent conversation.
AgentThread thread = new OpenAIAssistantAgentThread(this.AssistantClient);
AgentThread thread = new AzureAIAgentThread(this.Client);
AgentThread thread = new OpenAIResponseAgentThread(this.Client);

代理架構

代理程式負責建立執行緒。

// New.
AgentThread thread = agent.GetNewThread();

4. 託管代理線程清理

此案例僅適用於少數仍提供託管線程的 AI 提供者。

語意核心

執行緒有 self 刪除方法。

OpenAI 助理提供者:

await thread.DeleteAsync();

代理架構

備註

OpenAI Responses 引入了一種新的對話模型,簡化了對話的處理方式。 與現已棄用的 OpenAI Assistants 模型相比,此變更簡化了託管執行緒管理。 如需詳細資訊,請參閱 OpenAI 助理移轉指南

代理程式架構的類型中 AgentThread 沒有執行緒刪除 API,因為並非所有提供者都支援託管執行緒或執行緒刪除。 隨著越來越多的提供者轉向基於回應的架構,這種設計將變得更加普遍。

如果您需要刪除執行緒,且提供者允許,呼叫端 應該 追蹤所建立的執行緒,並在必要時稍後透過提供者的 SDK 刪除它們。

OpenAI 助理提供者:

await assistantClient.DeleteThreadAsync(thread.ConversationId);

5. 工具註冊

語意核心

若要將函式公開為工具,您必須:

  1. 使用屬性來 [KernelFunction] 修飾函式。
  2. 有一個 Plugin 類別或使用 來 KernelPluginFactory 包裝函數。
  3. 有一個 Kernel 可以添加您的插件。
  4. 將 傳遞 Kernel 給代理程式。
KernelFunction function = KernelFunctionFactory.CreateFromMethod(GetWeather);
KernelPlugin plugin = KernelPluginFactory.CreateFromFunctions("KernelPluginName", [function]);
Kernel kernel = ... // Create kernel
kernel.Plugins.Add(plugin);

ChatCompletionAgent agent = new() { Kernel = kernel, ... };

代理架構

在 Agent Framework 中,您可以在單個呼叫中直接在代理程式建立過程中註冊工具。

AIAgent agent = chatClient.CreateAIAgent(tools: [AIFunctionFactory.Create(GetWeather)]);

6. 代理程式非串流呼叫

主要差異可以在 to Invoke、傳回類型和參數Run的方法AgentRunOptions名稱中看到。

語意核心

非串流使用串流模式 IAsyncEnumerable<AgentResponseItem<ChatMessageContent>> 來傳回多個代理程式訊息。

await foreach (AgentResponseItem<ChatMessageContent> result in agent.InvokeAsync(userInput, thread, agentOptions))
{
    Console.WriteLine(result.Message);
}

代理架構

非串流會傳回一個具有代理程式回應的單一 AgentRunResponse 訊息,該回應可以包含多個訊息。 執行的文字結果可在 或 AgentRunResponse.Text中找到AgentRunResponse.ToString()。 作為回應一部分建立的所有訊息都會傳回清單中 AgentRunResponse.Messages 。 這可能包括工具呼叫訊息、函數結果、推理更新和最終結果。

AgentRunResponse agentResponse = await agent.RunAsync(userInput, thread);

7. 代理程式串流呼叫

主要差異在於 to Invoke、傳回類型和參數Run的方法AgentRunOptions名稱。

語意核心

await foreach (StreamingChatMessageContent update in agent.InvokeStreamingAsync(userInput, thread))
{
    Console.Write(update);
}

代理架構

代理程式架構具有類似的串流 API 模式,主要區別在於它每次更新都會傳回 AgentRunResponseUpdate 包含更多代理程式相關資訊的物件。

任何 AIAgent 基礎服務所產生的所有更新都會傳回。 代理程式的文字結果可透過串連 AgentRunResponse.Text 值來取得。

await foreach (AgentRunResponseUpdate update in agent.RunStreamingAsync(userInput, thread))
{
    Console.Write(update); // Update is ToString() friendly
}

8. 工具功能簽名

問題:語意核心外掛程式方法需要 [KernelFunction] 屬性。

public class MenuPlugin
{
    [KernelFunction] // Required.
    public static MenuItem[] GetMenu() => ...;
}

解決方案:代理框架可以直接使用沒有屬性的方法。

public class MenuTools
{
    [Description("Get menu items")] // Optional description.
    public static MenuItem[] GetMenu() => ...;
}

9. 選項配置

問題:語意核心中的複雜選項設定。

OpenAIPromptExecutionSettings settings = new() { MaxTokens = 1000 };
AgentInvokeOptions options = new() { KernelArguments = new(settings) };

解決方案:簡化代理程式架構中的選項。

ChatClientAgentRunOptions options = new(new() { MaxOutputTokens = 1000 });

這很重要

此範例顯示將實作特定選項傳遞至 ChatClientAgent. 並非所有支持AIAgentsChatClientAgentRunOptions ChatClientAgent 提供以基於底層推論服務構建代理,因此支持推理選項,例如 MaxOutputTokens

10. 依賴注入

語意核心

需要在服務容器中註冊 Kernel 才能建立代理程式,因為每個代理程式抽象都需要使用屬性進行 Kernel 初始化。

語意核心使用 Agent 類型作為代理程式的基本抽象類別。

services.AddKernel().AddProvider(...);
serviceContainer.AddKeyedSingleton<SemanticKernel.Agents.Agent>(
    TutorName,
    (sp, key) =>
        new ChatCompletionAgent()
        {
            // Passing the kernel is required.
            Kernel = sp.GetRequiredService<Kernel>(),
        });

代理架構

代理程式架構提供 AIAgent 類型作為基本抽象類別。

services.AddKeyedSingleton<AIAgent>(() => client.CreateAIAgent(...));

11. 代理類型整合

語意核心

語意核心為各種服務提供特定的代理程式類別,例如:

  • ChatCompletionAgent 用於聊天完成型推論服務。
  • OpenAIAssistantAgent 與 OpenAI Assistants 服務一起使用。
  • AzureAIAgent 與 Azure AI Foundry 代理程式服務搭配使用。

代理架構

代理程式架構透過單一代理程式類型 ChatClientAgent支援所有上述服務。

ChatClientAgent 可用來使用任何提供實作 IChatClient 介面之 SDK 的基礎服務來建置代理程式。

主要差異

以下是語意核心代理程式架構與 Microsoft 代理程式架構之間主要差異的摘要,以協助您移轉程式碼。

1. 打包和匯入更新

語意核心

語意核心套件會以 的身分semantic-kernel安裝和匯入。semantic_kernel 該軟件包還包含許多 extras 您可以安裝的軟件包,以安裝不同 AI 提供商的不同依賴項和其他功能。

from semantic_kernel import Kernel
from semantic_kernel.agents import ChatCompletionAgent

代理架構

代理程式架構套件會以 的身分 agent-framework 安裝並匯入為 agent_framework。 代理框架的建構方式不同,它有一個包含核心功能的核心套件agent-framework-core,然後有多個套件依賴該核心套件,例如 agent-framework-azure-ai、 、 agent-framework-mem0agent-framework-copilotstudio等。當您運行pip install agent-framework --pre時,它將安裝核心包和所有包,以便您可以快速開始使用所有功能。 當您準備好減少套件數目時,因為您知道需要什麼,您可以只安裝您需要的套件,因此,例如,如果您只打算使用 Azure AI Foundry 和 Mem0,則只能安裝這兩個套件: pip install agent-framework-azure-ai agent-framework-mem0 --preagent-framework-core 是這兩個套件的相依性,因此會自動安裝。

即使套件是分開的,匯入的都是來自 agent_framework或它的模組。 因此,例如,若要匯入 Azure AI Foundry 的用戶端,您會執行下列動作:

from agent_framework.azure import AzureAIAgentClient

許多最常用的類型是直接從以下位置匯 agent_framework入的:

from agent_framework import ChatMessage, ChatAgent

2. 代理類型合併

語意核心

語意核心為各種服務提供了特定的代理類別,例如ChatCompletionAgent、AzureAIAgent、OpenAIAssistantAgent等。請參閱 語意核心中的代理程式類型

代理架構

在代理程式架構中,大部分的代理程式都是使用 ChatAgent 可與所有 ChatClient 基礎服務搭配使用的 ,例如 Azure AI Foundry、OpenAI ChatCompletion 和 OpenAI 回應。 還有兩個額外的代理: CopilotStudioAgent 用於 Copilot Studio 和 A2AAgent 用於 A2A。

所有內建代理程式都以 BaseAgent (from agent_framework import BaseAgent) 為基礎。 並且所有代理都與 AgentProtocolfrom agent_framework import AgentProtocol)介面一致。

3. 代理建立簡化

語意核心

語意核心中的每個代理程式都依賴於一個 Kernel 實例,如果未提供,則會有一個空的 Kernel

from semantic_kernel.agents import ChatCompletionAgent
from semantic_kernel.connectors.ai.open_ai import OpenAIChatCompletion

agent = ChatCompletionAgent(
    service=OpenAIChatCompletion(),
    name="Support",
    instructions="Answer in one sentence.",
)

代理架構

在代理程式架構中建立代理程式可以透過兩種方式直接完成:

from agent_framework.azure import AzureAIAgentClient
from agent_framework import ChatMessage, ChatAgent

agent = ChatAgent(chat_client=AzureAIAgentClient(credential=AzureCliCredential()), instructions="You are a helpful assistant")

或者,透過聊天用戶端提供的便利方法:

from agent_framework.azure import AzureOpenAIChatClient
from azure.identity import AzureCliCredential
agent = AzureOpenAIChatClient(credential=AzureCliCredential()).create_agent(instructions="You are a helpful assistant")

直接方法會公開您可以為客服專員設定的所有可能參數。 雖然便利方法有一個子集,但您仍然可以傳入相同的參數集,因為它會在內部呼叫直接方法。

4. 代理線程創建

語意核心

呼叫端必須知道執行緒類型並手動建立它。

from semantic_kernel.agents import ChatHistoryAgentThread

thread = ChatHistoryAgentThread()

代理架構

可以要求代理程式為您建立新執行緒。

agent = ...
thread = agent.get_new_thread()

然後,會以下列三種方式之一建立執行緒:

  1. 如果代理程式已 thread_id 設定 (或 conversation_id 類似) ,則會在基礎服務中建立具有該識別碼的執行緒。 一旦執行緒有了 service_thread_id,就不能再使用它來在記憶體中儲存訊息。 這僅適用於具有服務端執行緒概念的代理程式。 例如 Azure AI Foundry 代理和 OpenAI 助手。
  2. 如果代理程式有 chat_message_store_factory 集合,它會使用該 Factory 來建立訊息存放區,並使用它來建立記憶體內執行緒。 然後,它就不能再與參數設定為 store的代理程式True搭配使用。
  3. 如果未設定上述任何設定,則會考慮 uninitialized 它,並視其使用方式而定,它會成為記憶體內部執行緒或服務執行緒。

代理架構

備註

OpenAI Responses 引入了一種新的對話模型,簡化了對話的處理方式。 與現已棄用的 OpenAI Assistants 模型相比,這簡化了託管線程管理。 如需詳細資訊,請參閱 OpenAI 助理移轉指南

代理程式架構的類型中 AgentThread 沒有執行緒刪除 API,因為並非所有提供者都支援託管執行緒或執行緒刪除,而且隨著越來越多的提供者轉向以回應為基礎的架構,這將變得更加普遍。

如果您需要刪除執行緒,且提供者允許這樣做,呼叫端 應該 追蹤建立的執行緒,並在必要時稍後透過提供者的 SDK 刪除它們。

OpenAI 助理提供者:

# OpenAI Assistants threads have self-deletion method in Semantic Kernel
await thread.delete_async()

5. 工具註冊

語意核心

若要將函式公開為工具,您必須:

  1. 用裝飾器裝飾 @kernel_function 功能。
  2. 有一個 Plugin 類別或使用核心外掛程式工廠來包裝函數。
  3. 有一個 Kernel 可以添加您的插件。
  4. 將 傳遞 Kernel 給代理程式。
from semantic_kernel.functions import kernel_function

class SpecialsPlugin:
    @kernel_function(name="specials", description="List daily specials")
    def specials(self) -> str:
        return "Clam chowder, Cobb salad, Chai tea"

agent = ChatCompletionAgent(
    service=OpenAIChatCompletion(),
    name="Host",
    instructions="Answer menu questions accurately.",
    plugins=[SpecialsPlugin()],
)

代理架構

在一次通話中,您可以直接在客服專員建立過程中註冊工具。 Agent Framework 沒有用於包裝多個函數的插件的概念,但如果需要,您仍然可以這樣做。

建立工具最簡單的方法就是建立一個Python函數:

def get_weather(location: str) -> str:
    """Get the weather for a given location."""
    return f"The weather in {location} is sunny."

agent = chat_client.create_agent(tools=get_weather)

備註

tools參數存在於代理創建、和runrun_stream方法get_response以及和get_streaming_response方法上,它允許您以列表或單個函數的形式提供工具。

函數的名稱將成為工具的名稱,文檔字串將成為工具的描述,您也可以在參數中添加描述:

from typing import Annotated

def get_weather(location: Annotated[str, "The location to get the weather for."]) -> str:
    """Get the weather for a given location."""
    return f"The weather in {location} is sunny."

最後,可以使用裝飾器進一步自訂工具的名稱和描述:

from typing import Annotated
from agent_framework import ai_function

@ai_function(name="weather_tool", description="Retrieves weather information for any location")
def get_weather(location: Annotated[str, "The location to get the weather for."])
    """Get the weather for a given location."""
    return f"The weather in {location} is sunny."

當您使用多個工具作為方法建立類別時,這也有效。

建立代理程式時,您現在可以透過將函數工具傳遞給 tools 參數來將函數工具提供給代理程式。

class Plugin:

    def __init__(self, initial_state: str):
        self.state: list[str] = [initial_state]

    def get_weather(self, location: Annotated[str, "The location to get the weather for."]) -> str:
        """Get the weather for a given location."""
        self.state.append(f"Requested weather for {location}. ")
        return f"The weather in {location} is sunny."

    def get_weather_details(self, location: Annotated[str, "The location to get the weather details for."]) -> str:
        """Get detailed weather for a given location."""
        self.state.append(f"Requested detailed weather for {location}. ")
        return f"The weather in {location} is sunny with a high of 25°C and a low of 15°C."

plugin = Plugin("Initial state")
agent = chat_client.create_agent(tools=[plugin.get_weather, plugin.get_weather_details])

... # use the agent

print("Plugin state:", plugin.state)

備註

類別內的函數也可以進行裝飾, @ai_function 以自訂工具的名稱和描述。

此機制對於需要 LLM 無法提供的額外輸入的工具也很有用,例如連線、秘密等。

相容性:使用 KernelFunction 作為代理框架工具

如果您有現有的語意核心程式碼, KernelFunction 其中包含執行個體 (來自提示或方法),您可以使用該 .as_agent_framework_tool 方法將它們轉換為代理程式架構工具。

這很重要

此功能需要 semantic-kernel 1.38 或更高版本。

從提示範本使用 KernelFunction

from semantic_kernel import Kernel
from semantic_kernel.functions import KernelFunctionFromPrompt
from semantic_kernel.connectors.ai.open_ai import OpenAIChatCompletion, OpenAIChatPromptExecutionSettings
from semantic_kernel.prompt_template import KernelPromptTemplate, PromptTemplateConfig
from agent_framework.openai import OpenAIResponsesClient

# Create a kernel with services and plugins
kernel = Kernel()
# will get the api_key and model_id from the environment
kernel.add_service(OpenAIChatCompletion(service_id="default"))

# Create a function from a prompt template that uses plugin functions
function_definition = """
Today is: {{time.date}}
Current time is: {{time.time}}

Answer to the following questions using JSON syntax, including the data used.
Is it morning, afternoon, evening, or night (morning/afternoon/evening/night)?
Is it weekend time (weekend/not weekend)?
"""

prompt_template_config = PromptTemplateConfig(template=function_definition)
prompt_template = KernelPromptTemplate(prompt_template_config=prompt_template_config)

# Create a KernelFunction from the prompt
kernel_function = KernelFunctionFromPrompt(
    description="Determine the kind of day based on the current time and date.",
    plugin_name="TimePlugin",
    prompt_execution_settings=OpenAIChatPromptExecutionSettings(service_id="default", max_tokens=100),
    function_name="kind_of_day",
    prompt_template=prompt_template,
)

# Convert the KernelFunction to an Agent Framework tool
agent_tool = kernel_function.as_agent_framework_tool(kernel=kernel)

# Use the tool with an Agent Framework agent
agent = OpenAIResponsesClient(model_id="gpt-4o").create_agent(tools=agent_tool)
response = await agent.run("What kind of day is it?")
print(response.text)

從方法使用 KernelFunction

from semantic_kernel.functions import kernel_function
from agent_framework.openai import OpenAIResponsesClient

# Create a plugin class with kernel functions
@kernel_function(name="get_weather", description="Get the weather for a location")
def get_weather(self, location: str) -> str:
    return f"The weather in {location} is sunny."

# Get the KernelFunction and convert it to an Agent Framework tool
agent_tool = get_weather.as_agent_framework_tool()

# Use the tool with an Agent Framework agent
agent = OpenAIResponsesClient(model_id="gpt-4o").create_agent(tools=agent_tool)
response = await agent.run("What's the weather in Seattle?")
print(response.text)

將 VectorStore 與 create_search_function 一起使用

您也可以使用語意核心的 VectorStore 與代理程式架構的整合。 create_search_function向量存放區集合中的方法會傳回可KernelFunction轉換為代理程式架構工具的方法。

from semantic_kernel import Kernel
from semantic_kernel.connectors.ai.open_ai import OpenAITextEmbedding
from semantic_kernel.connectors.azure_ai_search import AzureAISearchCollection
from semantic_kernel.functions import KernelParameterMetadata
from agent_framework.openai import OpenAIResponsesClient

# Define your data model
class HotelSampleClass:
    HotelId: str
    HotelName: str
    Description: str
    # ... other fields

# Create an Azure AI Search collection
collection = AzureAISearchCollection[str, HotelSampleClass](
    record_type=HotelSampleClass,
    embedding_generator=OpenAITextEmbedding()
)

async with collection:
    await collection.ensure_collection_exists()
    # Load your records into the collection
    # await collection.upsert(records)

    # Create a search function from the collection
    search_function = collection.create_search_function(
        description="A hotel search engine, allows searching for hotels in specific cities.",
        search_type="keyword_hybrid",
        filter=lambda x: x.Address.Country == "USA",
        parameters=[
            KernelParameterMetadata(
                name="query",
                description="What to search for.",
                type="str",
                is_required=True,
                type_object=str,
            ),
            KernelParameterMetadata(
                name="city",
                description="The city that you want to search for a hotel in.",
                type="str",
                type_object=str,
            ),
            KernelParameterMetadata(
                name="top",
                description="Number of results to return.",
                type="int",
                default_value=5,
                type_object=int,
            ),
        ],
        string_mapper=lambda x: f"(hotel_id: {x.record.HotelId}) {x.record.HotelName} - {x.record.Description}",
    )

    # Convert the search function to an Agent Framework tool
    search_tool = search_function.as_agent_framework_tool()

    # Use the tool with an Agent Framework agent
    agent = OpenAIResponsesClient(model_id="gpt-4o").create_agent(
        instructions="You are a travel agent that helps people find hotels.",
        tools=search_tool
    )
    response = await agent.run("Find me a hotel in Seattle")
    print(response.text)

此模式適用於任何語意核心 VectorStore 連接器 (Azure AI 搜尋服務、Qdrant、Pinecone 等),可讓您利用現有的向量搜尋基礎結構搭配代理程式架構。

此相容性層可讓您逐步將程式碼從語義核心遷移到代理框架,重複使用現有 KernelFunction 的實現,同時利用代理框架簡化的代理建立和執行模式。

6. 代理程式非串流呼叫

主要差異可以在方法名稱 from invoke to run、傳回類型 (例如 AgentRunResponse) 和參數中看到。

語意核心

非串流叫用會使用非同步反覆運算器模式來傳回多個代理程式訊息。

async for response in agent.invoke(
    messages=user_input,
    thread=thread,
):
    print(f"# {response.role}: {response}")
    thread = response.thread

並且有一個方便的方法可以得到最終的回應:

response = await agent.get_response(messages="How do I reset my bike tire?", thread=thread)
print(f"# {response.role}: {response}")

代理架構

非串流執行會傳回一個具有代理程式回應的單一 AgentRunResponse 訊息,該回應可以包含多個訊息。 執行的文字結果可在 或 response.text中找到str(response)。 作為回應一部分建立的所有訊息都會傳回清單中 response.messages 。 這可能包括工具呼叫訊息、函數結果、推理更新和最終結果。

agent = ...

response = await agent.run(user_input, thread)
print("Agent response:", response.text)

7. 代理程式串流呼叫

方法 名稱 從 invokerun_stream、傳回類型 (AgentRunResponseUpdate) 及參數的主要差異。

語意核心

async for update in agent.invoke_stream(
    messages="Draft a 2 sentence blurb.",
    thread=thread,
):
    if update.message:
        print(update.message.content, end="", flush=True)

代理架構

類似的串流 API 模式,主要差異在於它會傳回 AgentRunResponseUpdate 物件,其中包含每個更新的更多代理程式相關資訊。

代理程式基礎的任何服務所產生的所有內容都會傳回。 代理程式的最終結果可透過將值組合成 update 單一回應來取得。

from agent_framework import AgentRunResponse
agent = ...
updates = []
async for update in agent.run_stream(user_input, thread):
    updates.append(update)
    print(update.text)

full_response = AgentRunResponse.from_agent_run_response_updates(updates)
print("Full agent response:", full_response.text)

您甚至可以直接執行此操作:

from agent_framework import AgentRunResponse
agent = ...
full_response = AgentRunResponse.from_agent_response_generator(agent.run_stream(user_input, thread))
print("Full agent response:", full_response.text)

8. 選項配置

問題:語意核心中的複雜選項設定

from semantic_kernel.connectors.ai.open_ai import OpenAIPromptExecutionSettings

settings = OpenAIPromptExecutionSettings(max_tokens=1000)
arguments = KernelArguments(settings)

response = await agent.get_response(user_input, thread=thread, arguments=arguments)

解決方案:代理程式架構中的簡化選項

代理程式架構允許將所有參數直接傳遞至相關方法,因此除非您願意,否則您不必匯入任何額外的內容或建立任何選項物件。 在內部,它使用 and ChatOptionsChatClients對象,ChatAgents如果需要,您也可以建立並傳入該物件。 這也是在 a ChatAgent 中建立的,以保存選項,並且可以在每個呼叫中覆蓋。

agent = ...

response = await agent.run(user_input, thread, max_tokens=1000, frequency_penalty=0.5)

備註

以上是 特有的 ChatAgent,因為其他代理程式可能有不同的選項,因此它們都應該接受 messages 作為參數,因為這是在 中 AgentProtocol定義的。

後續步驟