Explorando o Kernel Semântico AzureAIAgent
Importante
Esta característica encontra-se em fase experimental. Os recursos neste estágio ainda estão em desenvolvimento e sujeitos a alterações antes de avançar para o estágio de pré-visualização ou candidato a lançamento.
A documentação detalhada da API relacionada a esta discussão está disponível em:
Documentos atualizados da API Python do Kernel Semântico estão chegando em breve.
Os agentes estão atualmente indisponíveis em Java.
O que é um AzureAIAgent
?
Um AzureAIAgent
é um agente especializado dentro da estrutura do Kernel Semântico, projetado para fornecer recursos avançados de conversação com integração perfeita de ferramentas. Ele automatiza a chamada de ferramentas, 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
suporta uma variedade de ferramentas internas, incluindo recuperação de ficheiros, execução de código e interação de dados através do Bing, Azure AI Search, Azure Functions e OpenAPI.
Para usar um AzureAIAgent
, um Projeto de Fundição de IA do Azure deve ser utilizado. Os artigos a seguir fornecem uma visão geral do Azure AI Foundry, como criar e configurar um projeto e o serviço de agente:
- O que é o Azure AI Foundry?
- o SDK do Azure AI Foundry
- O que é o Azure AI Agent Service
- Guia de início rápido: criar um novo agente
Preparando seu ambiente de desenvolvimento
Para prosseguir com o desenvolvimento de um AzureAIAgent
, configure seu ambiente de desenvolvimento com os pacotes apropriados.
Adicione o pacote Microsoft.SemanticKernel.Agents.AzureAI
ao seu projeto:
dotnet add package Microsoft.SemanticKernel.Agents.AzureAI --prerelease
Você também pode 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]
Os agentes estão atualmente indisponíveis em Java.
Configurando o AI Project Client
O acesso a um AzureAIAgent
requer primeiro a criação de um cliente de projeto que seja configurado para um projeto específico do Foundry, normalmente fornecendo uma cadeia de conexão (O SDK do Azure AI Foundry: Introdução aos Projetos).
AIProjectClient client = AzureAIAgent.CreateAzureAIClient("<your connection-string>", new AzureCliCredential());
A AgentsClient
pode ser acedida a partir 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>"
Uma vez definida a configuração, o cliente pode ser criado:
async with (
DefaultAzureCredential() as creds,
AzureAIAgent.create_client(credential=creds) as client,
):
# Your operational code here
Os agentes estão atualmente indisponíveis em Java.
Criando uma 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,
)
Os agentes estão atualmente indisponí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 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)
Os agentes estão atualmente indisponíveis em Java.
Usando complementos com o AzureAIAgent
O Semantic Kernel suporta a extensão de um AzureAIAgent
com plugins 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()]
)
Os agentes estão atualmente indisponíveis em Java.
Funcionalidades avançadas
Um AzureAIAgent
pode tirar partido de ferramentas avançadas, tais como:
Intérprete de código
O Interpretador de Código permite que os agentes escrevam e executem código Python em um ambiente de execução em área restrita (Azure AI Agent Service Code Interpreter).
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,
)
Os agentes estão atualmente indisponíveis em Java.
Pesquisa de Ficheiros
A pesquisa de arquivos amplia o conhecimento dos agentes além do seu modelo (Azure AI Agent Service File Search Tool).
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,
)
Os agentes estão atualmente indisponíveis em Java.
Integração OpenAPI
Conecta seu agente a uma API externa (Como usar o Serviço de Agente de IA do Azure com Ferramentas Especificadas 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,
)
Os agentes estão atualmente indisponíveis em Java.
Integração de pesquisa do AzureAI
Usar um índice existente do Azure AI Search com seu agente (Usar um índice de Pesquisa de IA existente).
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"},
)
Os agentes estão atualmente indisponíveis em Java.
Recuperando um AzureAIAgent
existente
Um agente existente pode ser recuperado e reutilizado especificando seu ID de 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)
Os agentes estão atualmente indisponíveis em Java.
Eliminar 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 armazenamento vetorial ou arquivos, eles também podem 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)
Os agentes estão atualmente indisponíveis em Java.
Mais informações sobre a ferramenta de pesquisa de arquivos são descritas no artigo ferramenta de pesquisa de arquivos do Azure AI Agent Service.
How-To
Para obter exemplos práticos de como usar um AzureAIAgent
, consulte nossos exemplos de código no GitHub:
Os agentes estão atualmente indisponíveis em Java.