共用方式為


探索語意核心 OpenAIResponsesAgent

這很重要

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

OpenAIResponsesAgent即將來臨。

小提示

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

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

什麼是回應代理程式?

OpenAI 回應 API 是 OpenAI 產生模型回應的最進階介面。 它支援文字和影像輸入,以及文字輸出。 您可以使用先前響應的輸出做為輸入,建立與模型的具狀態互動。 您也可以使用內建工具來擴充模型的功能,以進行檔案搜尋、Web 搜尋、計算機使用等等。

準備您的開發環境

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

OpenAIResponsesAgent即將來臨。

安裝 semantic-kernel 套件:

pip install semantic-kernel

這很重要

支援OpenAIResponsesAgent的語意核心 Python 套件從 1.27.0 版及更新的版本開始。

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

建立新的OpenAIResponsesAgent

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

OpenAIResponsesAgent即將來臨。

若要設定 OpenAI 或 Azure OpenAI 回應 API 所使用的模型,會引進新的環境變數:

OPENAI_RESPONSES_MODEL_ID=""
AZURE_OPENAI_RESPONSES_DEPLOYMENT_NAME=""

根據您使用的提供者,設定適當的變數。

小提示

允許的 Azure OpenAI API 版本下限為 2025-03-01-preview。 請流覽下列 連結 ,以檢視區域可用性、模型支援,以及進一步的詳細數據。

若要建立 AzureResponsesAgent 與 Azure OpenAI 模型搭配使用的 :

from semantic_kernel.agents import AzureResponsesAgent
from semantic_kernel.connectors.ai.open_ai import AzureOpenAISettings, OpenAISettings


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

# Create the AzureResponsesAgent instance using the client and the model
agent = AzureResponsesAgent(
    ai_model_id=AzureOpenAISettings().responses_deployment_name,
    client=client,
    instructions="your instructions",
    name="name",
)

或者,若要建立 OpenAIResponsesAgent 與 OpenAI 模型搭配使用的 :

from semantic_kernel.agents import OpenAIResponsesAgent

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

# Create the OpenAIResponsesAgent instance using the client and the model
agent = OpenAIResponsesAgent(
    ai_model_id=OpenAISettings().responses_model_id,
    client=client,
    instructions="your instructions",
    name="name",
)

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

使用 OpenAIResponsesAgent

OpenAIResponsesAgent即將來臨。

OpenAI 回應 API 支援選擇性遠端儲存交談。 根據預設,使用 ResponsesAgentThread時,回應會從遠端儲存。 這可讓您使用 Responses API 的 previous_response_id 在調用之間保持上下文。

每個交談都會被視為線程,由唯一字串標識碼識別。 所有與您 OpenAIResponsesAgent 互動的範圍都限於此線程標識碼。

回應 API 線程的基礎機制由實作 ResponsesAgentThread 介面的 AgentThread 類別所抽象化。

OpenAIResponsesAgent目前只支援 類型ResponsesAgentThread為的線程。

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

from semantic_kernel.agents import AzureResponsesAgent

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

# Create the AzureResponsesAgent instance using the client and the model
agent = AzureResponsesAgent(
    ai_model_id=AzureOpenAISettings().responses_deployment_name,
    client=client,
    instructions="your instructions",
    name="name",
)

USER_INPUTS = [
    "My name is John Doe.",
    "Tell me a joke",
    "Explain why this is funny.",
    "What have we been talking about?",
]

thread = None

# Generate the agent response(s)
for user_input in USER_INPUTS:
    print(f"# User: '{user_input}'")
    # Invoke the agent for the current message and print the response
    response = await agent.get_response(messages=user_input, thread=thread)
    print(f"# {response.name}: {response.content}")
    # Update the thread so the previous response id is used
    thread = response.thread

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

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

處理包含OpenAIResponsesAgent的中繼訊息

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

OpenAIResponsesAgent即將來臨。

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

import asyncio
from typing import Annotated

from semantic_kernel.agents import AzureResponsesAgent
from semantic_kernel.contents import AuthorRole, FunctionCallContent, FunctionResultContent
from semantic_kernel.contents.chat_message_content import ChatMessageContent
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():
    # 1. Create the client using Azure OpenAI resources and configuration
    client = AzureResponsesAgent.create_client()

    # 2. Create a Semantic Kernel agent for the OpenAI Responses API
    agent = AzureResponsesAgent(
        ai_model_id=AzureOpenAISettings().responses_deployment_name,
        client=client,
        name="Host",
        instructions="Answer questions about the menu.",
        plugins=[MenuPlugin()],
    )

    # 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 = 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,
            ):
                thread = response.thread
                print(f"# {response.name}: {response.content}")
    finally:
        await thread.delete() if thread else None


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

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

AuthorRole.USER: 'Hello'
Host: Hi there! How can I assist you with the menu 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
Host: The special soup is Clam Chowder. Would you like to know more about any other specials?
AuthorRole.USER: 'What is the special drink?'
Host: The special drink is Chai Tea. Would you like any more information?
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
Host: The Chai Tea is $9.99. Is there anything else you would like to know?
AuthorRole.USER: 'Thank you'
Host: You're welcome! If you have any more questions, feel free to ask. Enjoy your day!

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

宣告式規格

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

這很重要

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

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

備註

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

如何使用宣告式規格

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

AzureResponsesAgent 樣品:

OpenAIResponsesAgent 樣品:

範例:從 YAML 建立 AzureAIAgent

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

type: openai_responses
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 身分識別組態和進階工具使用。

此功能無法使用。

後續步驟