共用方式為


探索語意核心 OpenAIAssistantAgent

這很重要

單一代理程式功能,例如 OpenAIAssistantAgent,位於候選版階段。 這些功能幾乎完整且一般穩定,不過在達到完整正式運作之前,它們可能會經歷輕微的精簡或優化。

小提示

如需此討論的詳細 API 檔,請參閱:

小提示

如需此討論的詳細 API 檔,請參閱:

Java 中目前無法使用的功能。

什麼是助理?

OpenAI Assistants API 是專為更進階和互動式 AI 功能而設計的特製化介面,可讓開發人員建立個人化和多步驟的工作導向代理程式。 與專注於簡單交談交換的聊天完成 API 不同,小幫手 API 允許動態、目標導向的互動與程式代碼解釋器和檔案搜尋等其他功能互動。

準備您的開發環境

若要繼續開發 OpenAIAssistantAgent,請使用適當的套件來設定您的開發環境。

Microsoft.SemanticKernel.Agents.OpenAI 套件新增至您的專案:

dotnet add package Microsoft.SemanticKernel.Agents.OpenAI --prerelease

您可能也想要包含 Azure.Identity 套件:

dotnet add package Azure.Identity

安裝 semantic-kernel 套件:

pip install semantic-kernel

Java 中目前無法使用的功能。

建立新的OpenAIAssistantAgent

建立OpenAIAssistant需要先建立一個用戶端,以便與遠端服務進行通訊。

AssistantClient client = OpenAIAssistantAgent.CreateAzureOpenAIClient(...).GetAssistantClient();
Assistant assistant =
    await client.CreateAssistantAsync(
        "<model name>",
        "<agent name>",
        instructions: "<agent instructions>");
OpenAIAssistantAgent agent = new(assistant, client);
from semantic_kernel.agents import AssistantAgentThread, AzureAssistantAgent, OpenAIAssistantAgent
from semantic_kernel.connectors.ai.open_ai import AzureOpenAISettings, OpenAISettings

# Set up the client and model using Azure OpenAI Resources
client = AzureAssistantAgent.create_client()

# Define the assistant definition
definition = await client.beta.assistants.create(
    model=AzureOpenAISettings().chat_deployment_name,
    instructions="<instructions>",
    name="<agent name>",
)

# Create the AzureAssistantAgent instance using the client and the assistant definition
agent = AzureAssistantAgent(
    client=client,
    definition=definition,
)

# or

# Set up the client and model using OpenAI Resources
client = OpenAIAssistantAgent.create_client()

# Define the assistant definition
definition = await client.beta.assistants.create(
    model=OpenAISettings().chat_model_id,
    instructions="<instructions>",
    name="<agent name>",
)

# Create the OpenAIAssistantAgent instance using the client and the assistant definition
agent = OpenAIAssistantAgent(
    client=client,
    definition=definition,
)

Java 中目前無法使用的功能。

擷取一個 OpenAIAssistantAgent

建立之後,可以透過其識別碼來存取助理的識別碼。 此標識碼可用來從現有的助理定義生成 OpenAIAssistantAgent

針對 .NET,代理程式識別碼會透過任何代理程式所定義的 屬性公開為 string

AssistantClient client = OpenAIAssistantAgent.CreateAzureOpenAIClient(...).GetAssistantClient();
Assistant assistant = await client.GetAssistantAsync("<assistant id>");
OpenAIAssistantAgent agent = new(assistant, client);
# Using Azure OpenAI Resources

# Create the client using Azure OpenAI resources and configuration
client = AzureAssistantAgent.create_client()

# Create the assistant definition
definition = await client.beta.assistants.create(
    model=AzureOpenAISettings().chat_deployment_name,
    name="<agent name>",
    instructions="<instructions>",
)

# Store the assistant ID
assistant_id = definition.id

# Retrieve the assistant definition from the server based on the assistant ID
new_asst_definition = await client.beta.assistants.retrieve(assistant_id)

# Create the AzureAssistantAgent instance using the client and the assistant definition
agent = AzureAssistantAgent(
    client=client,
    definition=new_asst_definition,
)

Java 中目前無法使用的功能。

使用 OpenAIAssistantAgent

如同小幫手 API 的所有層面,交談會在遠端儲存。 每個對話稱為線索,並由唯一的string標識符識別。 與您的 OpenAIAssistantAgent 互動會與這個特定的線程標識相關。 助手 API 執行緒的特定細節是透過 OpenAIAssistantAgentThread 類別抽象化,該類別是 AgentThread 的一個實作。

OpenAIAssistantAgent目前只支援 類型OpenAIAssistantAgentThread為的線程。

您可以調用 OpenAIAssistantAgent,而不指定 AgentThread,以啟動新的線程,一個新的 AgentThread 將會回傳作為回應的一部分。


// Define agent
OpenAIAssistantAgent agent = ...;
AgentThread? agentThread = null;

// Generate the agent response(s)
await foreach (AgentResponseItem<ChatMessageContent> response in agent.InvokeAsync(new ChatMessageContent(AuthorRole.User, "<user input>")))
{
  // Process agent response(s)...
  agentThread = response.Thread;
}

// Delete the thread if no longer needed
if (agentThread is not null)
{
    await agentThread.DeleteAsync();
}

您也可以使用您建立的 OpenAIAssistantAgent 來叫用 AgentThread

// Define agent
OpenAIAssistantAgent agent = ...;

// Create a thread with some custom metadata.
AgentThread agentThread = new OpenAIAssistantAgentThread(client, metadata: myMetadata);

// Generate the agent response(s)
await foreach (ChatMessageContent response in agent.InvokeAsync(new ChatMessageContent(AuthorRole.User, "<user input>"), agentThread))
{
  // Process agent response(s)...
}

// Delete the thread when it is no longer needed
await agentThread.DeleteAsync();

您也可以建立一個 OpenAIAssistantAgentThread ,通過識別碼來恢復先前的對話。

// Create a thread with an existing thread id.
AgentThread agentThread = new OpenAIAssistantAgentThread(client, "existing-thread-id");
from semantic_kernel.agents import AssistantAgentThread, AzureAssistantAgent

# Define agent
openai_agent = await ...

# Create a thread for the agent conversation
thread: AssistantAgentThread = None

# Generate the agent response(s)
async for response in agent.invoke(messages="user input", thread=thread):
  # process agent response(s)...
  thread = response.thread

# Delete the thread when it is no longer needed
await thread.delete() if thread else None

Java 中目前無法使用的功能。

刪除 OpenAIAssistantAgent

由於助理的定義會從遠端儲存,因此若未刪除,則會保存該定義。
刪除助理定義可以直接在用戶端上進行。

注意:嘗試在刪除後使用代理程序實例會導致服務例外狀況。

針對 .NET,代理識別碼會透過任何代理程式所定義的string屬性公開為Agent.Id

AssistantClient client = OpenAIAssistantAgent.CreateAzureOpenAIClient(...).GetAssistantClient();
await client.DeleteAssistantAsync("<assistant id>");
await client.beta.assistants.delete(agent.id)

Java 中目前無法使用的功能。

處理包含OpenAIAssistantAgent的中繼訊息

Semantic Kernel OpenAIAssistantAgent 的設計目的是叫用可滿足使用者查詢或問題的代理程式。 在叫用期間,代理程式可能會執行工具來衍生最終答案。 若要存取此過程中產生的中繼訊息,呼叫者可以提供一個處理FunctionCallContentFunctionResultContent實例的回呼函式。

OpenAIAssistantAgent 的回呼文件即將推出。

on_intermediate_messageagent.invoke(...) 內設定 agent.invoke_stream(...) 回呼,可以讓呼叫方在制定代理人的最終回應過程中接收到產生的中間訊息。

import asyncio
from typing import Annotated

from semantic_kernel.agents import AssistantAgentThread, AzureAssistantAgent
from semantic_kernel.connectors.ai.open_ai import AzureOpenAISettings
from semantic_kernel.contents import AuthorRole, ChatMessageContent, FunctionCallContent, FunctionResultContent
from semantic_kernel.functions import kernel_function


# Define a sample plugin for the sample
class MenuPlugin:
    """A sample Menu Plugin used for the concept sample."""

    @kernel_function(description="Provides a list of specials from the menu.")
    def get_specials(self) -> Annotated[str, "Returns the specials from the menu."]:
        return """
        Special Soup: Clam Chowder
        Special Salad: Cobb Salad
        Special Drink: Chai Tea
        """

    @kernel_function(description="Provides the price of the requested menu item.")
    def get_item_price(
        self, menu_item: Annotated[str, "The name of the menu item."]
    ) -> Annotated[str, "Returns the price of the menu item."]:
        return "$9.99"


# This callback function will be called for each intermediate message,
# which will allow one to handle FunctionCallContent and FunctionResultContent.
# If the callback is not provided, the agent will return the final response
# with no intermediate tool call steps.
async def handle_intermediate_steps(message: ChatMessageContent) -> None:
    for item in message.items or []:
        if isinstance(item, FunctionResultContent):
            print(f"Function Result:> {item.result} for function: {item.name}")
        elif isinstance(item, FunctionCallContent):
            print(f"Function Call:> {item.name} with arguments: {item.arguments}")
        else:
            print(f"{item}")


async def main():
    # Create the client using Azure OpenAI resources and configuration
    client = AzureAssistantAgent.create_client()

    # Define the assistant definition
    definition = await client.beta.assistants.create(
        model=AzureOpenAISettings().chat_deployment_name,
        name="Host",
        instructions="Answer questions about the menu.",
    )

    # Create the AzureAssistantAgent instance using the client and the assistant definition and the defined plugin
    agent = AzureAssistantAgent(
        client=client,
        definition=definition,
        plugins=[MenuPlugin()],
    )

    # 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: AssistantAgentThread = None

    user_inputs = [
        "Hello",
        "What is the special soup?",
        "What is the special drink?",
        "How much is that?",
        "Thank you",
    ]

    try:
        for user_input in user_inputs:
            print(f"# {AuthorRole.USER}: '{user_input}'")
            async for response in agent.invoke(
                messages=user_input,
                thread=thread,
                on_intermediate_message=handle_intermediate_steps,
            ):
                print(f"# {response.role}: {response}")
                thread = response.thread
    finally:
        await thread.delete() if thread else None
        await client.beta.assistants.delete(assistant_id=agent.id)


if __name__ == "__main__":
    asyncio.run(main())

下列示範來自代理程式調用程式的範例輸出:

AuthorRole.USER: 'Hello'
AuthorRole.ASSISTANT: Hello! How can I assist you today?
AuthorRole.USER: 'What is the special soup?'
Function Call:> MenuPlugin-get_specials with arguments: {}
Function Result:> 
        Special Soup: Clam Chowder
        Special Salad: Cobb Salad
        Special Drink: Chai Tea
        for function: MenuPlugin-get_specials
AuthorRole.ASSISTANT: The special soup is Clam Chowder. Would you like to know more about the specials or 
    anything else?
AuthorRole.USER: 'What is the special drink?'
AuthorRole.ASSISTANT: The special drink is Chai Tea. If you have any more questions, feel free to ask!
AuthorRole.USER: 'How much is that?'
Function Call:> MenuPlugin-get_item_price with arguments: {"menu_item":"Chai Tea"}
Function Result:> $9.99 for function: MenuPlugin-get_item_price
AuthorRole.ASSISTANT: The Chai Tea is priced at $9.99. If there's anything else you'd like to know, 
    just let me know!
AuthorRole.USER: 'Thank you'
AuthorRole.ASSISTANT: You're welcome! If you have any more questions or need further assistance, feel free to 
    ask. Enjoy your day!

Java 中目前無法使用的功能。

宣告式規格

即將推出的使用宣告式規格的文件。

這很重要

這項功能處於實驗階段。 在這個階段的功能正在開發中,在前進到預覽或發行候選階段之前,可能會變更。

OpenAIAssistantAgent支援從 YAML 宣告式規範進行實例化。 宣告式方法可讓您在單一可稽核的文件中定義代理程序的屬性、指示、模型組態、工具和其他選項。 這可讓代理程式組合可攜式且輕鬆地跨環境進行管理。

備註

宣告式 YAML 中列出的任何工具、函式或外掛程式,都必須在建構階段提供給代理程式使用。 對於以核心為基礎的外掛程式,這表示必須在核心中註冊它們。 針對程式代碼解釋器或檔案搜尋等內建工具,必須提供正確的組態和認證。 代理程式載入器不會從頭開始建立函式。 如果缺少必要的元件,代理程式建立將會失敗。

如何使用宣告式規格

本節不列舉每個可能的 YAML 組態,而是概述主要原則,並提供概念範例的連結,這些範例會顯示每個工具類型的完整程序代碼。 請參閱這些示範範例,來了解具有宣告式規格的OpenAIAssistantAgent端對端實作。

AzureAssistantAgent 樣品:

OpenAIAssistantAgent 樣品:

範例:從 YAML 建立 AzureAIAgent

最小 YAML 宣告式規格看起來可能如下所示:

type: openai_assistant
name: Host
instructions: Respond politely to the user's questions.
model:
  id: ${OpenAI:ChatModelId}
tools:
  - id: MenuPlugin.get_specials
    type: function
  - id: MenuPlugin.get_item_price
    type: function

如需如何連接代理程式的詳細資訊,請參閱上述的完整程式碼範例。

重點

  • 宣告式規格允許在 YAML 中定義代理程式結構、工具和行為。
  • 所有參考的工具和外掛程式都必須在運行時間註冊或存取。
  • Bing、檔案搜尋和程式代碼解釋器等內建工具需要適當的組態和認證(通常是透過環境變數或明確自變數)。
  • 如需完整的範例,請參閱提供的範例連結,其中示範實際案例,包括外掛程式註冊、Azure 身分識別組態和進階工具使用。

此功能無法使用。

操作指南

如需 OpenAIAssistantAgent的端對端範例,請參閱:

後續步驟