Zkoumání sémantického jádra AzureAIAgent
Důležitý
Tato funkce je v experimentální fázi. Funkce v této fázi jsou stále ve vývoji a před přechodem do fáze Preview nebo verze Candidate se můžou změnit.
Podrobná dokumentace k rozhraní API související s touto diskuzí je k dispozici na adrese:
Brzy bude k dispozici aktualizovaná dokumentace k rozhraní PYTHON API pro sémantické jádro.
Agenti momentálně nejsou v Javě k dispozici.
Co je AzureAIAgent
?
AzureAIAgent
je specializovaný agent v rámci architektury sémantického jádra navržený tak, aby poskytoval pokročilé konverzační funkce s bezproblémovou integrací nástrojů. Automatizuje volání nástrojů, eliminuje potřebu ruční analýzy a vyvolání. Agent také bezpečně spravuje historii konverzací pomocí vláken a snižuje režii při údržbě stavu. Kromě toho AzureAIAgent
podporuje celou řadu integrovaných nástrojů, včetně načítání souborů, spouštění kódu a interakce dat prostřednictvím Bingu, Azure AI Search, Azure Functions a OpenAPI.
Pokud chcete použít AzureAIAgent
, musí být použit projekt Azure AI Foundry. Následující články obsahují přehled azure AI Foundry, jak vytvořit a nakonfigurovat projekt a službu agenta:
- Co je Azure AI Foundry?
- Azure AI Foundry SDK
- co je služba agenta Azure AI
- Rychlý start : Vytvoření nového agenta
Příprava vývojového prostředí
Pokud chcete pokračovat v vývoji AzureAIAgent
, nakonfigurujte vývojové prostředí s příslušnými balíčky.
Přidejte do projektu balíček Microsoft.SemanticKernel.Agents.AzureAI
:
dotnet add package Microsoft.SemanticKernel.Agents.AzureAI --prerelease
Můžete také zahrnout balíček Azure.Identity
:
dotnet add package Azure.Identity
Nainstalujte balíček semantic-kernel
s volitelnými závislostmi Azure:
pip install semantic-kernel[azure]
Agenti momentálně nejsou v Javě k dispozici.
Konfigurace klienta projektu AI
Přístup k AzureAIAgent
nejprve vyžaduje vytvoření klienta projektu, který je nakonfigurovaný pro konkrétní projekt Foundry, nejčastěji zadáním připojovacího řetězce (Sada Azure AI Foundry SDK: Začínáme s projekty).
AIProjectClient client = AzureAIAgent.CreateAzureAIClient("<your connection-string>", new AzureCliCredential());
K AgentsClient
lze přistupovat z AIProjectClient
:
AgentsClient agentsClient = client.GetAgentsClient();
Upravte soubor .env
v kořenovém adresáři tak, aby zahrnoval:
AZURE_AI_AGENT_PROJECT_CONNECTION_STRING = "<example-connection-string>"
AZURE_AI_AGENT_MODEL_DEPLOYMENT_NAME = "<example-model-deployment-name>"
nebo
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>"
Po definování konfigurace může být klient vytvořen:
async with (
DefaultAzureCredential() as creds,
AzureAIAgent.create_client(credential=creds) as client,
):
# Your operational code here
Agenti momentálně nejsou v Javě k dispozici.
Vytvoření AzureAIAgent
Pokud chcete vytvořit AzureAIAgent
, začněte tím, že nakonfigurujete a inicializujete projekt agenta prostřednictvím služby Azure AI a pak ho integrujete se sémantickým jádrem:
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,
)
Agenti momentálně nejsou v Javě k dispozici.
Interakce s objektem AzureAIAgent
Interakce s AzureAIAgent
je jednoduchá. Agent udržuje historii konverzací automaticky pomocí vlákna:
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)
Volitelně může být agent vyvolán takto:
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)
Agent může také vytvořit streamovanou odpověď:
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)
Agenti momentálně nejsou v Javě k dispozici.
Použití modulů plug-in s AzureAIAgent
Sémantické jádro podporuje rozšíření AzureAIAgent
s vlastními pluginy pro vylepšené funkce.
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()]
)
Agenti momentálně nejsou v Javě k dispozici.
Pokročilé funkce
AzureAIAgent
může využívat pokročilé nástroje, jako jsou:
Interpret kódu
Interpret kódu umožňuje agentům zapisovat a spouštět kód Pythonu v izolovaném prostředí (interpret kódu služby agenta 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,
)
Agenti momentálně nejsou v Javě k dispozici.
Hledání souborů
Vyhledávání souborů obohacuje agenty o znalosti mimo jejich model (nástroj Vyhledávání souborů služby Azure AI Agent).
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,
)
Agenti momentálně nejsou v Javě k dispozici.
Integrace OpenAPI
Připojí vašeho agenta k externímu rozhraní API (Jak používat službu agenta Azure AI se zadanými nástroji 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,
)
Agenti momentálně nejsou v Javě k dispozici.
Integrace služby AzureAI Search
Použijte existující index Azure AI Search se svým agentem (Použijte existující index Azure AI Search).
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"},
)
Agenti momentálně nejsou v Javě k dispozici.
Načtení existujícího AzureAIAgent
Existujícího agenta je možné načíst a znovu použít zadáním ID jeho asistenta:
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)
Agenti momentálně nejsou v Javě k dispozici.
Odstranění AzureAIAgent
Agenty a jejich přidružené vlákna je možné odstranit, pokud už je nepotřebujete:
await agentsClient.DeleteThreadAsync(thread.Id);
await agentsClient.DeleteAgentAsync(agent.Id);
await client.agents.delete_thread(thread.id)
await client.agents.delete_agent(agent.id)
Pokud pracujete s úložištěm vektorů nebo soubory, mohou být také odstraněny:
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)
Agenti momentálně nejsou v Javě k dispozici.
Další informace o nástroji pro vyhledávání souborů jsou popsány v článku o nástroji pro vyhledávání souborů služby Azure AI Agent .
How-To
Praktické příklady použití AzureAIAgent
najdete v našich ukázkách kódu na GitHubu:
Agenti momentálně nejsou v Javě k dispozici.
spolupráce agenta v chatu agentů