Explorando o kernel semântico AzureAIAgent
Importante
Esse recurso está em estágio experimental. As funcionalidades nesta fase ainda estão em desenvolvimento e estão sujeitas a alterações antes de avançarem para a fase de pré-visualização ou candidato a lançamento.
A documentação detalhada da API relacionada a esta discussão está disponível em:
A documentação atualizada da API do Semantic Kernel em Python estará disponível em breve.
No momento, os agentes não estão disponíveis em Java.
O que é um AzureAIAgent
?
Um AzureAIAgent
é um agente especializado dentro da estrutura do Semantic Kernel, projetado para fornecer capacidades conversacionais avançadas com integração perfeita de ferramentas. Ele automatiza a chamada de ferramenta, eliminando a necessidade de análise manual e invocação. O agente também gerencia com segurança o histórico de conversas usando threads, reduzindo a sobrecarga de manutenção do estado. Além disso, o AzureAIAgent
dá suporte a uma variedade de ferramentas internas, incluindo recuperação de arquivo, execução de código e interação de dados por meio do Bing, Azure AI Search, Azure Functions e OpenAPI.
Para utilizar um AzureAIAgent
, é necessário usar um Projeto do Azure AI Foundry. Os artigos a seguir fornecem uma visão geral do Azure AI Foundry, como criar e configurar um projeto e o serviço do agente:
- o que é o Azure AI Foundry?
- o SDK do Azure AI Foundry
- O que é o Serviço do Agente de IA do Azure
- Início Rápido : Criar um novo agente
Preparando seu ambiente de desenvolvimento
Para continuar desenvolvendo um AzureAIAgent
, configure seu ambiente de desenvolvimento com os pacotes apropriados.
Adicione o pacote de Microsoft.SemanticKernel.Agents.AzureAI
ao seu projeto:
dotnet add package Microsoft.SemanticKernel.Agents.AzureAI --prerelease
Talvez você também queira incluir o pacote Azure.Identity
:
dotnet add package Azure.Identity
Instale o pacote semantic-kernel
com as dependências opcionais do Azure:
pip install semantic-kernel[azure]
No momento, os agentes não estão disponíveis em Java.
Configurando o cliente de projeto de IA
O acesso a um AzureAIAgent
requer primeiro a criação de um cliente de projeto configurado especificamente para um Projeto do Foundry, geralmente por meio do fornecimento de uma cadeia de conexão (O SDK do Azure AI Foundry: Introdução aos Projetos).
AIProjectClient client = AzureAIAgent.CreateAzureAIClient("<your connection-string>", new AzureCliCredential());
O AgentsClient
pode ser acessado do AIProjectClient
:
AgentsClient agentsClient = client.GetAgentsClient();
Modifique o arquivo .env
no diretório raiz para incluir:
AZURE_AI_AGENT_PROJECT_CONNECTION_STRING = "<example-connection-string>"
AZURE_AI_AGENT_MODEL_DEPLOYMENT_NAME = "<example-model-deployment-name>"
ou
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>"
Depois que a configuração for definida, o cliente poderá ser criado:
async with (
DefaultAzureCredential() as creds,
AzureAIAgent.create_client(credential=creds) as client,
):
# Your operational code here
No momento, os agentes não estão disponíveis em Java.
Criando um AzureAIAgent
Para criar um AzureAIAgent
, comece configurando e inicializando o projeto do agente por meio do serviço de IA do Azure e, em seguida, integre-o ao Kernel Semântico:
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,
)
No momento, os agentes não estão disponíveis em Java.
Interagindo com um AzureAIAgent
A interação com o AzureAIAgent
é simples. O agente mantém o histórico de conversas automaticamente usando um thread:
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)
Opcionalmente, um agente pode ser invocado como:
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)
Um agente também pode produzir uma resposta transmitida em fluxo:
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)
No momento, os agentes não estão disponíveis em Java.
Usando plug-ins com um AzureAIAgent
O Kernel Semântico dá suporte à extensão de um AzureAIAgent
com plug-ins personalizados para funcionalidade aprimorada:
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()]
)
No momento, os agentes não estão disponíveis em Java.
Recursos avançados
Um AzureAIAgent
pode aproveitar ferramentas avançadas como:
Interpretador de Código
O Interpretador de Código permite que os agentes escrevam e executem código Python em um ambiente de execução isolado (Interpretador de Código do Serviço de Agente de IA do Azure).
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,
)
No momento, os agentes não estão disponíveis em Java.
Pesquisa de Arquivo
A pesquisa de arquivos oferece aos agentes conhecimentos externos ao seu modelo (Ferramenta de Pesquisa de Arquivos do Serviço de Agente de IA do Azure).
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,
)
No momento, os agentes não estão disponíveis em Java.
Integração do OpenAPI
Conecta seu agente a uma API externa (Como usar o Serviço de Agente de IA do Azure com Ferramentas Especificadas no 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,
)
No momento, os agentes não estão disponíveis em Java.
Integração do AzureAI Search
Usar um índice existente do Azure AI Search com seu agente (Usar um índice existente do 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"},
)
No momento, os agentes não estão disponíveis em Java.
Recuperando um AzureAIAgent
existente
Um agente existente pode ser recuperado e reutilizado ao especificar o ID do assistente:
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)
No momento, os agentes não estão disponíveis em Java.
Excluindo um AzureAIAgent
Os agentes e seus threads associados podem ser excluídos quando não forem mais necessários:
await agentsClient.DeleteThreadAsync(thread.Id);
await agentsClient.DeleteAgentAsync(agent.Id);
await client.agents.delete_thread(thread.id)
await client.agents.delete_agent(agent.id)
Se estiver trabalhando com um repositório de vetores ou arquivos, eles também poderão ser excluídos:
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)
No momento, os agentes não estão disponíveis em Java.
Mais informações sobre a ferramenta de pesquisa de arquivos é descrita no artigo ferramenta de pesquisa de arquivos do Serviço do Agente de IA do Azure artigo.
How-To
Para obter exemplos práticos de como usar um AzureAIAgent
, consulte nossos exemplos de código no GitHub:
No momento, os agentes não estão disponíveis em Java.
Colaboração do agente no de chat do agente