共用方式為


探索語意核心 AzureAIAgent

重要

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

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

即將推出已更新的語意核心 Python API 檔。

代理程式目前無法在Java中使用。

什麼是 AzureAIAgent

AzureAIAgent 是語意核心架構內的特製化代理程式,其設計目的是提供具有無縫工具整合的進階交談功能。 它能自動進行工具調用,省去手動解析和啟動的需求。 代理程式也會使用線程安全地管理交談歷程記錄,減少維護狀態的額外負荷。 此外,AzureAIAgent 支援各種不同的內建工具,包括透過 Bing、Azure AI 搜尋、Azure Functions 和 OpenAPI 進行檔案擷取、程式代碼執行和數據互動。

若要使用 AzureAIAgent,必須使用 Azure AI Foundry 專案。 下列文章提供 Azure AI Foundry 的概觀、如何建立和設定專案,以及代理程式服務:

準備開發環境

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

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

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

您也可以包含 Azure.Identity 套件:

dotnet add package Azure.Identity

使用附加的 Azure 依賴套件安裝 semantic-kernel 套件:

pip install semantic-kernel[azure]

代理程式目前無法在Java中使用。

設定 AI 專案用戶端

先存取 AzureAIAgent 需要建立針對特定 Foundry 專案設定的專案用戶端,通常是藉由提供連接字串來建立專案用戶端(Azure AI Foundry SDK:開始使用專案)。

AIProjectClient client = AzureAIAgent.CreateAzureAIClient("<your connection-string>", new AzureCliCredential());

您可以從 AIProjectClient存取 AgentsClient

AgentsClient agentsClient = client.GetAgentsClient();

修改您在根目錄中的 .env 檔案,以包含:

AZURE_AI_AGENT_PROJECT_CONNECTION_STRING = "<example-connection-string>"
AZURE_AI_AGENT_MODEL_DEPLOYMENT_NAME = "<example-model-deployment-name>"

AZURE_AI_AGENT_ENDPOINT = "<example-endpoint>"
AZURE_AI_AGENT_SUBSCRIPTION_ID = "<example-subscription-id>"
AZURE_AI_AGENT_RESOURCE_GROUP_NAME = "<example-resource-group-name>"
AZURE_AI_AGENT_PROJECT_NAME = "<example-project-name>"
AZURE_AI_AGENT_MODEL_DEPLOYMENT_NAME = "<example-model-deployment-name>"

定義組態之後,就可以建立用戶端:

async with (
    DefaultAzureCredential() as creds,
    AzureAIAgent.create_client(credential=creds) as client,
):
    # Your operational code here

代理程式目前無法在Java中使用。

建立 AzureAIAgent

若要建立 AzureAIAgent,您可以從透過 Azure AI 服務設定和初始化代理程式項目開始,然後將其與語意核心整合:

AIProjectClient client = AzureAIAgent.CreateAzureAIClient("<your connection-string>", new AzureCliCredential());
AgentsClient agentsClient = client.GetAgentsClient();

// 1. Define an agent on the Azure AI agent service
Agent definition = agentsClient.CreateAgentAsync(
    "<name of the the model used by the agent>",
    name: "<agent name>",
    description: "<agent description>",
    instructions: "<agent instructions>");

// 2. Create a Semantic Kernel agent based on the agent definition
AzureAIAgent agent = new(definition, agentsClient);
from azure.identity.aio import DefaultAzureCredential
from semantic_kernel.agents.azure_ai import AzureAIAgent, AzureAIAgentSettings

ai_agent_settings = AzureAIAgentSettings.create()

async with (
    DefaultAzureCredential() as creds,
    AzureAIAgent.create_client(credential=creds) as client,
):
    # 1. Define an agent on the Azure AI agent service
    agent_definition = await client.agents.create_agent(
        model=ai_agent_settings.model_deployment_name,
        name="<name>",
        instructions="<instructions>",
    )

    # 2. Create a Semantic Kernel agent based on the agent definition
    agent = AzureAIAgent(
        client=client,
        definition=agent_definition,
    )

代理程式目前無法在Java中使用。

AzureAIAgent 互動

AzureAIAgent 的互動很簡單。 代理程式會使用線程自動維護交談歷程記錄:

AgentThread thread = await agentsClient.CreateThreadAsync();
try
{
    ChatMessageContent message = new(AuthorRole.User, "<your user input>");
    await agent.AddChatMessageAsync(threadId, message);
    await foreach (ChatMessageContent response in agent.InvokeAsync(thread.Id))
    {
        Console.WriteLine(response.Content);
    }
}
finally
{
    await this.AgentsClient.DeleteThreadAsync(thread.Id);
    await this.AgentsClient.DeleteAgentAsync(agent.Id);
}
USER_INPUTS = ["Hello", "What's your name?"]

thread = await client.agents.create_thread()

try:
    for user_input in USER_INPUTS:
        await agent.add_chat_message(thread_id=thread.id, message=user_input)
        response = await agent.get_response(thread_id=thread.id)
        print(response)
finally:
    await client.agents.delete_thread(thread.id)

或者,代理程式可以叫用為:

for user_input in USER_INPUTS:
    await agent.add_chat_message(thread_id=thread.id, message=user_input)
    async for content in agent.invoke(thread_id=thread.id):
        print(content.content)

代理也可能產生串流回應:

ChatMessageContent message = new(AuthorRole.User, "<your user input>");
await agent.AddChatMessageAsync(threadId, message);
await foreach (StreamingChatMessageContent response in agent.InvokeStreamingAsync(thread.Id))
{
    Console.Write(response.Content);
}
for user_input in USER_INPUTS:
    await agent.add_chat_message(thread_id=thread.id, message=user_input)
    async for content in agent.invoke_stream(thread_id=thread.id):
        print(content.content, end="", flush=True)

代理程式目前無法在Java中使用。

搭配 AzureAIAgent 使用外掛程式

Semantic Kernel 支援使用自定義外掛程式擴充 AzureAIAgent,以提升功能:

Plugin plugin = KernelPluginFactory.CreateFromType<YourPlugin>();
AIProjectClient client = AzureAIAgent.CreateAzureAIClient("<your connection-string>", new AzureCliCredential());
AgentsClient agentsClient = client.GetAgentsClient();

Agent definition = agentsClient.CreateAgentAsync(
    "<name of the the model used by the agent>",
    name: "<agent name>",
    description: "<agent description>",
    instructions: "<agent instructions>");

AzureAIAgent agent = new(definition, agentsClient, plugins: [plugin]);
from semantic_kernel.functions import kernel_function

class SamplePlugin:
    @kernel_function(description="Provides sample data.")
    def get_data(self) -> str:
        return "Sample data"

ai_agent_settings = AzureAIAgentSettings.create()

async with (
        DefaultAzureCredential() as creds,
        AzureAIAgent.create_client(credential=creds) as client,
    ):
        agent_definition = await client.agents.create_agent(
            model=ai_agent_settings.model_deployment_name,
        )

        agent = AzureAIAgent(
            client=client,
            definition=agent_definition,
            plugins=[SamplePlugin()]
        )

代理程式目前無法在Java中使用。

進階功能

AzureAIAgent 可以利用進階工具,例如:

程式代碼解釋器

程式代碼解釋器可讓代理程式在沙盒化執行環境中撰寫和執行 Python 程式代碼(Azure AI 代理程式服務程式代碼解釋器)。

AIProjectClient client = AzureAIAgent.CreateAzureAIClient("<your connection-string>", new AzureCliCredential());
AgentsClient agentsClient = client.GetAgentsClient();

Agent definition = agentsClient.CreateAgentAsync(
    "<name of the the model used by the agent>",
    name: "<agent name>",
    description: "<agent description>",
    instructions: "<agent instructions>",
    tools: [new CodeInterpreterToolDefinition()],
    toolResources:
        new()
        {
            CodeInterpreter = new()
            {
                FileIds = { ... },
            }
        }));

AzureAIAgent agent = new(definition, agentsClient);
from azure.ai.projects.models import CodeInterpreterTool

async with (
        DefaultAzureCredential() as creds,
        AzureAIAgent.create_client(credential=creds) as client,
    ):
        code_interpreter = CodeInterpreterTool()
        agent_definition = await client.agents.create_agent(
            model=ai_agent_settings.model_deployment_name,
            tools=code_interpreter.definitions,
            tool_resources=code_interpreter.resources,
        )

代理程式目前無法在Java中使用。

檔案搜尋會增強來自其模型外部知識的代理程式(Azure AI 代理程式服務檔案搜尋工具)。

AIProjectClient client = AzureAIAgent.CreateAzureAIClient("<your connection-string>", new AzureCliCredential());
AgentsClient agentsClient = client.GetAgentsClient();

Agent definition = agentsClient.CreateAgentAsync(
    "<name of the the model used by the agent>",
    name: "<agent name>",
    description: "<agent description>",
    instructions: "<agent instructions>",
    tools: [new FileSearchToolDefinition()],
    toolResources:
        new()
        {
            FileSearch = new()
            {
                VectorStoreIds = { ... },
            }
        }));

AzureAIAgent agent = new(definition, agentsClient);
from azure.ai.projects.models import FileSearchTool

async with (
        DefaultAzureCredential() as creds,
        AzureAIAgent.create_client(credential=creds) as client,
    ):
        file_search = FileSearchTool(vector_store_ids=[vector_store.id])
        agent_definition = await client.agents.create_agent(
            model=ai_agent_settings.model_deployment_name,
            tools=file_search.definitions,
            tool_resources=file_search.resources,
        )

代理程式目前無法在Java中使用。

OpenAPI 整合

將代理程式連線到外部 API(如何使用 Azure AI 代理程式服務搭配 OpenAPI 指定工具)。

AIProjectClient client = AzureAIAgent.CreateAzureAIClient("<your connection-string>", new AzureCliCredential());
AgentsClient agentsClient = client.GetAgentsClient();

string apiJsonSpecification = ...; // An Open API JSON specification

Agent definition = agentsClient.CreateAgentAsync(
    "<name of the the model used by the agent>",
    name: "<agent name>",
    description: "<agent description>",
    instructions: "<agent instructions>",
    tools: [
        new OpenApiToolDefinition(
            "<api name>", 
            "<api description>", 
            BinaryData.FromString(apiJsonSpecification), 
            new OpenApiAnonymousAuthDetails())
    ],
);

AzureAIAgent agent = new(definition, agentsClient);
from azure.ai.projects.models import OpenApiTool, OpenApiAnonymousAuthDetails

async with (
        DefaultAzureCredential() as creds,
        AzureAIAgent.create_client(credential=creds) as client,
    ):
        openapi_spec_file_path = "sample/filepath/..."
        with open(os.path.join(openapi_spec_file_path, "spec_one.json")) as file_one:
            openapi_spec_one = json.loads(file_one.read())
        with open(os.path.join(openapi_spec_file_path, "spec_two.json")) as file_two:
            openapi_spec_two = json.loads(file_two.read())

        # Note that connection or managed identity auth setup requires additional setup in Azure
        auth = OpenApiAnonymousAuthDetails()
        openapi_tool_one = OpenApiTool(
            name="<name>",
            spec=openapi_spec_one,
            description="<description>",
            auth=auth,
        )
        openapi_tool_two = OpenApiTool(
            name="<name>",
            spec=openapi_spec_two,
            description="<description>",
            auth=auth,
        )

        agent_definition = await client.agents.create_agent(
            model=ai_agent_settings.model_deployment_name,
            tools=openapi_tool_one.definitions + openapi_tool_two.definitions,
        )

代理程式目前無法在Java中使用。

AzureAI 搜尋整合

搭配您的代理程式使用現有的 Azure AI 搜尋索引 (使用現有的 AI 搜尋索引)。

AIProjectClient client = AzureAIAgent.CreateAzureAIClient("<your connection-string>", new AzureCliCredential());
AgentsClient agentsClient = client.GetAgentsClient();

ConnectionsClient cxnClient = client.GetConnectionsClient();
ListConnectionsResponse searchConnections = await cxnClient.GetConnectionsAsync(AzureAIP.ConnectionType.AzureAISearch);
ConnectionResponse searchConnection = searchConnections.Value[0];

Agent definition = agentsClient.CreateAgentAsync(
    "<name of the the model used by the agent>",
    name: "<agent name>",
    description: "<agent description>",
    instructions: "<agent instructions>",
    tools: [new AzureAIP.AzureAISearchToolDefinition()],
    toolResources: new()
    {
        AzureAISearch = new()
        {
            IndexList = { new AzureAIP.IndexResource(searchConnection.Id, "<your index name>") }
        }
    });

AzureAIAgent agent = new(definition, agentsClient);
from azure.ai.projects.models import AzureAISearchTool, ConnectionType

async with (
        DefaultAzureCredential() as creds,
        AzureAIAgent.create_client(credential=creds) as client,
    ):
        conn_list = await client.connections.list()

        ai_search_conn_id = ""
        for conn in conn_list:
            if conn.connection_type == ConnectionType.AZURE_AI_SEARCH:
                ai_search_conn_id = conn.id
                break

        ai_search = AzureAISearchTool(
            index_connection_id=ai_search_conn_id, 
            index_name=AZURE_AI_SEARCH_INDEX_NAME,
        )

        agent_definition = await client.agents.create_agent(
            model=ai_agent_settings.model_deployment_name,
            instructions="Answer questions using your index.",
            tools=ai_search.definitions,
            tool_resources=ai_search.resources,
            headers={"x-ms-enable-preview": "true"},
        )

代理程式目前無法在Java中使用。

擷取現有的 AzureAIAgent

您可以藉由指定其助理識別碼來擷取及重複使用現有的代理程式:

Agent definition = agentsClient.GetAgentAsync("<your agent id>");
AzureAIAgent agent = new(definition, agentsClient);
agent_definition = await client.agents.get_agent(assistant_id="your-agent-id")
agent = AzureAIAgent(client=client, definition=agent_definition)

代理程式目前無法在Java中使用。

刪除 AzureAIAgent

不再需要代理程式及其相關聯的線程時,可以刪除:

await agentsClient.DeleteThreadAsync(thread.Id);
await agentsClient.DeleteAgentAsync(agent.Id);
await client.agents.delete_thread(thread.id)
await client.agents.delete_agent(agent.id)

如果使用向量存放區或檔案,也可以刪除它們:

await agentsClient.DeleteVectorStoreAsync("<your store id>");
await agentsClient.DeleteFileAsync("<your file id>");
await client.agents.delete_file(file_id=file.id)
await client.agents.delete_vector_store(vector_store_id=vector_store.id)

代理程式目前無法在Java中使用。

如需 檔案搜尋 工具的詳細資訊,請參閱 azure AI 代理程式服務檔案搜尋工具 一文。

How-To

如需使用 AzureAIAgent的實際範例,請參閱 GitHub 上的程式碼範例:

代理程式目前無法在Java中使用。