Nota:
El acceso a esta página requiere autorización. Puede intentar iniciar sesión o cambiar directorios.
El acceso a esta página requiere autorización. Puede intentar cambiar los directorios.
Exploración del kernel semántico
Importante
Esta característica está en la fase experimental. Las características de esta fase están en desarrollo y están sujetas a cambios antes de avanzar a la fase de versión preliminar o candidata para lanzamiento.
Sugerencia
La documentación detallada de la API relacionada con esta discusión está disponible en:
Sugerencia
La documentación detallada de la API relacionada con esta discusión está disponible en:
Característica actualmente no disponible en Java.
¿Qué es un AzureAIAgent?
Un AzureAIAgent es un agente especializado dentro del marco de kernel semántico, diseñado para proporcionar funcionalidades de conversación avanzadas con integración de herramientas sin problemas. Automatiza las llamadas a herramientas, lo que elimina la necesidad de analizar e invocar manualmente. El agente también administra de forma segura el historial de conversaciones mediante subprocesos, lo que reduce la sobrecarga de gestionar el estado. Además, el AzureAIAgent admite una variedad de herramientas integradas, como la recuperación de archivos, la ejecución de código y la interacción de datos a través de Bing, Azure AI Search, Azure Functions y OpenAPI.
Para utilizar un AzureAIAgent, se debe emplear un proyecto de Azure AI Foundry. En los artículos siguientes se proporciona información general sobre Azure AI Foundry, cómo crear y configurar un proyecto y el servicio del agente:
- ¿Qué es Azure AI Foundry?
- el SDK de Azure AI Foundry
- ¿Qué es azure AI Agent Service
- Inicio rápido : Crear un nuevo agente
Preparación del entorno de desarrollo
Para continuar con el desarrollo de un AzureAIAgent, configure el entorno de desarrollo con los paquetes adecuados.
Agregue el paquete Microsoft.SemanticKernel.Agents.AzureAI al proyecto:
dotnet add package Microsoft.SemanticKernel.Agents.AzureAI --prerelease
Puede que también desee incluir el paquete Azure.Identity.
dotnet add package Azure.Identity
Instala el paquete semantic-kernel:
pip install semantic-kernel
Característica actualmente no disponible en Java.
Configuración del cliente de proyecto de IA
El acceso a un AzureAIAgent primero requiere la creación de un cliente configurado para un proyecto de Foundry específico, normalmente proporcionando el punto de conexión del proyecto (El SDK de Azure AI Foundry: Introducción a proyectos).
PersistentAgentsClient client = AzureAIAgent.CreateAgentsClient("<your endpoint>", new AzureCliCredential());
Modifique el archivo .env en el directorio raíz para incluir:
AZURE_AI_AGENT_ENDPOINT = "<example-endpoint>"
AZURE_AI_AGENT_MODEL_DEPLOYMENT_NAME = "<example-model-deployment-name>"
Una vez definida la configuración, se puede crear el cliente:
from semantic_kernel.agents import AzureAIAgent
async with (
DefaultAzureCredential() as creds,
AzureAIAgent.create_client(credential=creds) as client,
):
# Your operational code here
Los ajustes subyacentes endpoint serán recogidos por la configuración de Pydantic si están configurados. De lo contrario, puede pasarlo al método create_client() de forma explícita.
from semantic_kernel.agents import AzureAIAgent
async with (
DefaultAzureCredential() as creds,
AzureAIAgent.create_client(credential=creds, endpoint="<your-endpoint>") as client,
):
# Your operational code here
Característica actualmente no disponible en Java.
Creación de un AzureAIAgent
Para crear un AzureAIAgent, empiece por configurar e inicializar el proyecto Foundry a través del servicio Agente de Azure y, a continuación, integrarlo con kernel semántico:
PersistentAgentsClient client = AzureAIAgent.CreateAgentsClient("<your endpoint>", new AzureCliCredential());
// 1. Define an agent on the Azure AI agent service
PersistentAgent definition = await agentsClient.Administration.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 import AzureAIAgent, AzureAIAgentSettings
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=AzureAIAgentSettings().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,
)
Característica actualmente no disponible en Java.
Interactuar con un AzureAIAgent
La interacción con el AzureAIAgent es sencilla. El agente mantiene automáticamente el historial de conversaciones mediante un hilo.
Los detalles del subproceso del agente de Azure AI se abstraen a través de la clase Microsoft.SemanticKernel.Agents.AzureAI.AzureAIAgentThread, que es una implementación de Microsoft.SemanticKernel.Agents.AgentThread.
Importante
Tenga en cuenta que el SDK de Azure AI Agents tiene la PersistentAgentThread clase . No debe confundirse con Microsoft.SemanticKernel.Agents.AgentThread, que es la abstracción común de los agentes del kernel semántico para todos los tipos de hilos.
Actualmente, el AzureAIAgent solo admite subprocesos de tipo AzureAIAgentThread.
AzureAIAgentThread agentThread = new(agent.Client);
try
{
ChatMessageContent message = new(AuthorRole.User, "<your user input>");
await foreach (ChatMessageContent response in agent.InvokeAsync(message, agentThread))
{
Console.WriteLine(response.Content);
}
}
finally
{
await agentThread.DeleteAsync();
await agent.Client.DeleteAgentAsync(agent.Id);
}
Los detalles del subproceso del agente de Azure AI se abstraen a través de la clase AzureAIAgentThread, que es una implementación de AgentThread.
USER_INPUTS = ["Hello", "What's your name?"]
thread: AzureAIAgentThread = AzureAIAgentThread()
try:
for user_input in USER_INPUTS:
response = await agent.get_response(messages=user_inputs, thread=thread)
print(response)
thread = response.thread
finally:
await thread.delete() if thread else None
Opcionalmente, se puede invocar un agente como:
for user_input in USER_INPUTS:
async for content in agent.invoke(messages=user_input, thread=thread):
print(content.content)
thread = response.thread
También puede pasar una lista de mensajes a los métodos get_response(...), invoke(...) o invoke_stream(...).
USER_INPUTS = ["Hello", "What's your name?"]
thread: AzureAIAgentThread = AzureAIAgentThread()
try:
for user_input in USER_INPUTS:
response = await agent.get_response(messages=USER_INPUTS, thread=thread)
print(response)
thread = response.thread
finally:
await thread.delete() if thread else None
Un agente también puede producir una respuesta transmitida:
ChatMessageContent message = new(AuthorRole.User, "<your user input>");
await foreach (StreamingChatMessageContent response in agent.InvokeStreamingAsync(message, agentThread))
{
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)
Característica actualmente no disponible en Java.
Uso de complementos con un AzureAIAgent
El kernel semántico admite la extensión de un AzureAIAgent con complementos personalizados para mejorar la funcionalidad:
KernelPlugin plugin = KernelPluginFactory.CreateFromType<YourPlugin>();
PersistentAgentsClient client = AzureAIAgent.CreateAgentsClient("<your endpoint>", new AzureCliCredential());
PersistentAgent definition = await agentsClient.Administration.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"
async with (
DefaultAzureCredential() as creds,
AzureAIAgent.create_client(credential=creds) as client,
):
agent_definition = await client.agents.create_agent(
model=AzureAIAgentSettings().model_deployment_name,
)
agent = AzureAIAgent(
client=client,
definition=agent_definition,
plugins=[SamplePlugin()]
)
Característica actualmente no disponible en Java.
Características avanzadas
Un AzureAIAgent puede aprovechar herramientas avanzadas como:
- Intérprete de código
- Búsqueda de archivos
- integración de OpenAPI
- Integración de Azure AI Search
- Bing Grounding
Intérprete de código
El intérprete de código permite que los agentes escriban y ejecuten código de Python en un entorno de ejecución de espacio aislado (intérprete de código de servicio del agente de Azure AI).
PersistentAgentsClient client = AzureAIAgent.CreateAgentsClient("<your endpoint>", new AzureCliCredential());
PersistentAgent definition = await 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.agents.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,
)
Característica actualmente no disponible en Java.
Búsqueda de archivos
La búsqueda de archivos proporciona a los agentes conocimiento desde más allá de su modelo (Herramienta de búsqueda de archivos del servicio agente de Azure AI).
PersistentAgentsClient client = AzureAIAgent.CreateAgentsClient("<your endpoint>", new AzureCliCredential());
PersistentAgent definition = await 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.agents.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,
)
Característica actualmente no disponible en Java.
Integración de OpenAPI
Conecta el agente a una API externa (Uso del servicio agente de Azure AI con las herramientas especificadas de OpenAPI).
PersistentAgentsClient client = AzureAIAgent.CreateAgentsClient("<your endpoint>", new AzureCliCredential());
string apiJsonSpecification = ...; // An Open API JSON specification
PersistentAgent definition = await 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.agents.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,
)
Característica actualmente no disponible en Java.
Integración de AzureAI Search
Use un índice de Azure AI Search existente con el agente (Use un índice de AI Search existente).
PersistentAgentsClient client = AzureAIAgent.CreateAgentsClient("<your endpoint>", new AzureCliCredential());
PersistentAgent definition = await agentsClient.CreateAgentAsync(
"<name of the the model used by the agent>",
name: "<agent name>",
description: "<agent description>",
instructions: "<agent instructions>",
tools: [new AzureAISearchToolDefinition()],
toolResources: new()
{
AzureAISearch = new()
{
IndexList = { new AISearchIndexResource("<your connection id>", "<your index name>") }
}
});
AzureAIAgent agent = new(definition, agentsClient);
from azure.ai.agents.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"},
)
Característica actualmente no disponible en Java.
Bing Grounding
Ejemplo próximamente.
from azure.ai.agents.models import BingGroundingTool
from azure.identity.aio import DefaultAzureCredential
from semantic_kernel.agents import AzureAIAgent, AzureAIAgentSettings
async with (
DefaultAzureCredential() as creds,
AzureAIAgent.create_client(credential=creds) as client,
):
# 1. Enter your Bing Grounding Connection Name
bing_connection = await client.connections.get(connection_name="<your-bing-grounding-connection-name>")
conn_id = bing_connection.id
# 2. Initialize agent bing tool and add the connection id
bing_grounding = BingGroundingTool(connection_id=conn_id)
# 3. Create an agent with Bing grounding on the Azure AI agent service
agent_definition = await client.agents.create_agent(
name="BingGroundingAgent",
instructions="Use the Bing grounding tool to answer the user's question.",
model=AzureAIAgentSettings().model_deployment_name,
tools=bing_grounding.definitions,
)
# 4. Create a Semantic Kernel agent for the Azure AI agent
agent = AzureAIAgent(
client=client,
definition=agent_definition,
)
Al usar la herramienta Bing Grounding, el FunctionCallContent pasado a la on_intermediate_message devolución de llamada tendrá su nombre de función establecido como "bing_grounding". Una vez completada la ejecución, ChatMessageContent.items incluirá bien AnnotationContent o bien StreamingAnnotationContent, en función de si la invocación es estándar o de streaming. Estos elementos de anotación contienen información sobre los vínculos que visitó el agente durante la respuesta, similar a la información presente en .FunctionCallContent
Para obtener más información, consulte los siguientes ejemplos de concepto:
Característica actualmente no disponible en Java.
Recuperación de un AzureAIAgent existente
Un agente existente se puede recuperar y reutilizar especificando su identificador de asistente:
PersistentAgent definition = await agentsClient.Administration.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)
Característica actualmente no disponible en Java.
Eliminación de un AzureAIAgent
Los agentes y sus subprocesos asociados se pueden eliminar cuando ya no sean necesarios:
await agentThread.DeleteAsync();
await agentsClient.Administration.DeleteAgentAsync(agent.Id);
await client.agents.delete_thread(thread.id)
await client.agents.delete_agent(agent.id)
Si trabaja con un almacenamiento de vectores o archivos, también se pueden eliminar.
await agentsClient.VectorStores.DeleteVectorStoreAsync("<your store id>");
await agentsClient.Files.DeleteFileAsync("<your file id>");
await client.agents.files.delete(file_id=file.id)
await client.agents.vector_stores.delete(vector_store_id=vector_store.id)
Característica actualmente no disponible en Java.
Para obtener más información sobre la herramienta de búsqueda de archivos , consulte el artículo titulado "Herramienta de búsqueda de archivos del servicio de agente de Azure AI" .
Procedimiento
Para obtener ejemplos prácticos de uso de un AzureAIAgent, consulte nuestros ejemplos de código en GitHub:
Característica actualmente no disponible en Java.
Gestión de mensajes intermedios con un AzureAIAgent
El kernel AzureAIAgent semántico está diseñado para invocar un agente que cumpla las consultas o preguntas del usuario. Durante la invocación, el agente puede ejecutar herramientas para derivar la respuesta final. Para acceder a los mensajes intermedios generados durante este proceso, los autores de llamadas pueden proporcionar una función de devolución de llamada que controla las instancias de FunctionCallContent o FunctionResultContent.
La documentación del callback de
AzureAIAgentestará disponible pronto.
La configuración de la devolución de llamada dentro de on_intermediate_message o agent.invoke(...) permite a la persona que llama recibir mensajes intermedios generados durante el proceso de formulación de la respuesta final del agente.
import asyncio
from typing import Annotated
from azure.identity.aio import DefaultAzureCredential
from semantic_kernel.agents import AzureAIAgent, AzureAIAgentSettings, AzureAIAgentThread
from semantic_kernel.contents import 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() -> None:
ai_agent_settings = AzureAIAgentSettings()
async with (
DefaultAzureCredential() as creds,
AzureAIAgent.create_client(credential=creds, endpoint=ai_agent_settings.endpoint) as client,
):
AGENT_NAME = "Host"
AGENT_INSTRUCTIONS = "Answer questions about the menu."
# Create agent definition
agent_definition = await client.agents.create_agent(
model=ai_agent_settings.deployment_name,
name=AGENT_NAME,
instructions=AGENT_INSTRUCTIONS,
)
# Create the AzureAI Agent
agent = AzureAIAgent(
client=client,
definition=agent_definition,
plugins=[MenuPlugin()], # add the sample plugin to the agent
)
# Create a thread for the agent
# If no thread is provided, a new thread will be
# created and returned with the initial response
thread: AzureAIAgentThread = None
user_inputs = [
"Hello",
"What is the special soup?",
"How much does that cost?",
"Thank you",
]
try:
for user_input in user_inputs:
print(f"# User: '{user_input}'")
async for response in agent.invoke(
messages=user_input,
thread=thread,
on_intermediate_message=handle_intermediate_steps,
):
print(f"# Agent: {response}")
thread = response.thread
finally:
# Cleanup: Delete the thread and agent
await thread.delete() if thread else None
await client.agents.delete_agent(agent.id)
if __name__ == "__main__":
asyncio.run(main())
A continuación se muestra la salida de ejemplo del proceso de invocación del agente:
User: 'Hello'
Agent: Hi there! How can I assist you today?
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
Agent: The special soup is Clam Chowder. Would you like to know anything else about the menu?
User: 'How much does that cost?'
Function Call:> MenuPlugin-get_item_price with arguments: {"menu_item":"Clam Chowder"}
Function Result:> $9.99 for function: MenuPlugin-get_item_price
Agent: The Clam Chowder costs $9.99. Let me know if you would like assistance with anything else!
User: 'Thank you'
Agent: You're welcome! Enjoy your meal! 😊
Característica actualmente no disponible en Java.
Especificación declarativa
La documentación sobre el uso de especificaciones declarativas estará disponible próximamente.
Importante
Esta característica está en la fase experimental. Las características de esta fase están en desarrollo y están sujetas a cambios antes de avanzar a la fase de versión preliminar o candidata para lanzamiento.
AzureAIAgent permite la instanciación desde una especificación declarativa YAML. El enfoque declarativo permite definir las propiedades, instrucciones, configuración del modelo, herramientas y otras opciones del agente en un único documento auditable. Esto hace que la composición del agente sea portátil y fácil de administrar entre entornos.
Nota:
Las herramientas, funciones o complementos enumerados en el YAML declarativo deben estar disponibles para el agente en tiempo de construcción. En el caso de los complementos basados en kernel, esto significa que deben registrarse en el kernel. Para las herramientas integradas, como Bing Grounding, File Search o OpenAPI, se deben proporcionar la configuración y las credenciales correctas. El cargador del agente no creará funciones desde cero. Si falta un componente necesario, se producirá un error en la creación del agente.
Cómo usar la especificación declarativa
En lugar de enumerar todas las configuraciones de YAML posibles, en esta sección se describen los principios clave y se proporcionan vínculos a ejemplos de concepto que muestran código completo para cada tipo de herramienta. Consulte estos ejemplos de concepto para implementaciones de un extremo a otro de una AzureAIAgent clase con especificaciones declarativas:
- Plugin de Funciones
- Plugin de función a partir de un archivo
- Búsqueda de IA
- Bing Grounding
- Intérprete de código
- Búsqueda de archivos
- OpenAPI
- Plantilla de solicitud
- Cargar desde un ID de agente existente
Ejemplo: Creación de una instancia de AzureAIAgent a partir de YAML
Una especificación declarativa de YAML mínima podría ser similar a la siguiente:
type: foundry_agent
name: MyAgent
instructions: Respond politely to the user's questions.
model:
id: ${AzureAI:ChatModelId}
tools:
- id: MenuPlugin.get_specials
type: function
- id: MenuPlugin.get_item_price
type: function
Para obtener más información sobre cómo conectar el agente, consulte los ejemplos de código completos anteriores.
Puntos clave
- Las especificaciones declarativas permiten definir la estructura del agente, las herramientas y el comportamiento en YAML.
- Todas las herramientas y complementos a los que se hace referencia deben estar registradas o accesibles en tiempo de ejecución.
- Las herramientas integradas, como Bing, File Search y Code Interpreter, requieren una configuración y credenciales adecuadas (a menudo a través de variables de entorno o argumentos explícitos).
- Para obtener ejemplos completos, consulte los vínculos de ejemplo proporcionados que muestran escenarios prácticos, como el registro de complementos, la configuración de identidad de Azure y el uso avanzado de herramientas.
Esta característica no está disponible.