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
Las características de agente único, como OpenAIAssistantAgent, se encuentran en la fase candidata para lanzamiento. Estas características son casi completas y, por lo general, estables, aunque pueden sufrir pequeños refinamientos o optimizaciones antes de alcanzar la disponibilidad general completa.
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 asistente?
OpenAI Assistants API es una interfaz especializada diseñada para funcionalidades de inteligencia artificial más avanzadas e interactivas, lo que permite a los desarrolladores crear agentes personalizados y orientados a tareas de varios pasos. A diferencia de la API de finalización de chat, que se centra en intercambios conversacionales simples, la API assistant permite interacciones dinámicas controladas por objetivos con características adicionales, como el intérprete de código y la búsqueda de archivos.
Preparación del entorno de desarrollo
Para continuar con el desarrollo de un OpenAIAssistantAgent, configure el entorno de desarrollo con los paquetes adecuados.
Agregue el paquete Microsoft.SemanticKernel.Agents.OpenAI al proyecto:
dotnet add package Microsoft.SemanticKernel.Agents.OpenAI --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.
Creación de un OpenAIAssistantAgent
La creación de un OpenAIAssistant elemento requiere crear primero un cliente para poder comunicarse con un servicio remoto.
AssistantClient client = OpenAIAssistantAgent.CreateAzureOpenAIClient(...).GetAssistantClient();
Assistant assistant =
await client.CreateAssistantAsync(
"<model name>",
"<agent name>",
instructions: "<agent instructions>");
OpenAIAssistantAgent agent = new(assistant, client);
from semantic_kernel.agents import AssistantAgentThread, AzureAssistantAgent, OpenAIAssistantAgent
from semantic_kernel.connectors.ai.open_ai import AzureOpenAISettings, OpenAISettings
# Set up the client and model using Azure OpenAI Resources
client = AzureAssistantAgent.create_client()
# Define the assistant definition
definition = await client.beta.assistants.create(
model=AzureOpenAISettings().chat_deployment_name,
instructions="<instructions>",
name="<agent name>",
)
# Create the AzureAssistantAgent instance using the client and the assistant definition
agent = AzureAssistantAgent(
client=client,
definition=definition,
)
# or
# Set up the client and model using OpenAI Resources
client = OpenAIAssistantAgent.create_client()
# Define the assistant definition
definition = await client.beta.assistants.create(
model=OpenAISettings().chat_model_id,
instructions="<instructions>",
name="<agent name>",
)
# Create the OpenAIAssistantAgent instance using the client and the assistant definition
agent = OpenAIAssistantAgent(
client=client,
definition=definition,
)
Característica actualmente no disponible en Java.
Recuperar un OpenAIAssistantAgent
Una vez creado, se puede acceder al asistente mediante su identificador. Este identificador se puede usar para crear una OpenAIAssistantAgent a partir de una definición de asistente existente.
Para .NET, el identificador del agente se expone como string a través de la propiedad definida por cualquier agente.
AssistantClient client = OpenAIAssistantAgent.CreateAzureOpenAIClient(...).GetAssistantClient();
Assistant assistant = await client.GetAssistantAsync("<assistant id>");
OpenAIAssistantAgent agent = new(assistant, client);
# Using Azure OpenAI Resources
# Create the client using Azure OpenAI resources and configuration
client = AzureAssistantAgent.create_client()
# Create the assistant definition
definition = await client.beta.assistants.create(
model=AzureOpenAISettings().chat_deployment_name,
name="<agent name>",
instructions="<instructions>",
)
# Store the assistant ID
assistant_id = definition.id
# Retrieve the assistant definition from the server based on the assistant ID
new_asst_definition = await client.beta.assistants.retrieve(assistant_id)
# Create the AzureAssistantAgent instance using the client and the assistant definition
agent = AzureAssistantAgent(
client=client,
definition=new_asst_definition,
)
Característica actualmente no disponible en Java.
Utilización de un OpenAIAssistantAgent
Al igual que con todos los aspectos de la API assistant, las conversaciones se almacenan de forma remota. Cada conversación se conoce como un subproceso y se identifica mediante un identificador único string . Las interacciones con su OpenAIAssistantAgent están vinculadas a este identificador de subproceso específico. Los detalles del subproceso de la API Assistant se abstraen a través de la clase OpenAIAssistantAgentThread, que es una implementación de AgentThread.
Actualmente, el OpenAIAssistantAgent solo admite subprocesos de tipo OpenAIAssistantAgentThread.
Puede invocar el OpenAIAssistantAgent sin especificar un AgentThread, para iniciar un nuevo subproceso y se devolverá un nuevo AgentThread como parte de la respuesta.
// Define agent
OpenAIAssistantAgent agent = ...;
AgentThread? agentThread = null;
// Generate the agent response(s)
await foreach (AgentResponseItem<ChatMessageContent> response in agent.InvokeAsync(new ChatMessageContent(AuthorRole.User, "<user input>")))
{
// Process agent response(s)...
agentThread = response.Thread;
}
// Delete the thread if no longer needed
if (agentThread is not null)
{
await agentThread.DeleteAsync();
}
También puede invocar el OpenAIAssistantAgent con un AgentThread que creó.
// Define agent
OpenAIAssistantAgent agent = ...;
// Create a thread with some custom metadata.
AgentThread agentThread = new OpenAIAssistantAgentThread(client, metadata: myMetadata);
// Generate the agent response(s)
await foreach (ChatMessageContent response in agent.InvokeAsync(new ChatMessageContent(AuthorRole.User, "<user input>"), agentThread))
{
// Process agent response(s)...
}
// Delete the thread when it is no longer needed
await agentThread.DeleteAsync();
También puede crear un OpenAIAssistantAgentThread que reanude una conversación anterior por identificador.
// Create a thread with an existing thread id.
AgentThread agentThread = new OpenAIAssistantAgentThread(client, "existing-thread-id");
from semantic_kernel.agents import AssistantAgentThread, AzureAssistantAgent
# Define agent
openai_agent = await ...
# Create a thread for the agent conversation
thread: AssistantAgentThread = None
# Generate the agent response(s)
async for response in agent.invoke(messages="user input", thread=thread):
# process agent response(s)...
thread = response.thread
# Delete the thread when it is no longer needed
await thread.delete() if thread else None
Característica actualmente no disponible en Java.
Eliminación de un OpenAIAssistantAgent
Dado que la definición del asistente se almacena de forma remota, se conservará si no se elimina.
La eliminación de una definición de asistente se puede realizar directamente con el cliente.
Nota: Al intentar usar una instancia de agente después de eliminarse, se producirá una excepción de servicio.
Para .NET, el identificador del agente se expone como string a través de la Agent.Id propiedad definida por cualquier agente.
AssistantClient client = OpenAIAssistantAgent.CreateAzureOpenAIClient(...).GetAssistantClient();
await client.DeleteAssistantAsync("<assistant id>");
await client.beta.assistants.delete(agent.id)
Característica actualmente no disponible en Java.
Gestión de mensajes intermedios con un OpenAIAssistantAgent
El kernel OpenAIAssistantAgent 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
OpenAIAssistantAgentestará 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 semantic_kernel.agents import AssistantAgentThread, AzureAssistantAgent
from semantic_kernel.connectors.ai.open_ai import AzureOpenAISettings
from semantic_kernel.contents import AuthorRole, ChatMessageContent, FunctionCallContent, FunctionResultContent
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():
# Create the client using Azure OpenAI resources and configuration
client = AzureAssistantAgent.create_client()
# Define the assistant definition
definition = await client.beta.assistants.create(
model=AzureOpenAISettings().chat_deployment_name,
name="Host",
instructions="Answer questions about the menu.",
)
# Create the AzureAssistantAgent instance using the client and the assistant definition and the defined plugin
agent = AzureAssistantAgent(
client=client,
definition=definition,
plugins=[MenuPlugin()],
)
# Create a new thread for use with the assistant
# If no thread is provided, a new thread will be
# created and returned with the initial response
thread: AssistantAgentThread = None
user_inputs = [
"Hello",
"What is the special soup?",
"What is the special drink?",
"How much is that?",
"Thank you",
]
try:
for user_input in user_inputs:
print(f"# {AuthorRole.USER}: '{user_input}'")
async for response in agent.invoke(
messages=user_input,
thread=thread,
on_intermediate_message=handle_intermediate_steps,
):
print(f"# {response.role}: {response}")
thread = response.thread
finally:
await thread.delete() if thread else None
await client.beta.assistants.delete(assistant_id=agent.id)
if __name__ == "__main__":
asyncio.run(main())
A continuación se muestra la salida de ejemplo del proceso de invocación del agente:
AuthorRole.USER: 'Hello'
AuthorRole.ASSISTANT: Hello! How can I assist you today?
AuthorRole.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
AuthorRole.ASSISTANT: The special soup is Clam Chowder. Would you like to know more about the specials or
anything else?
AuthorRole.USER: 'What is the special drink?'
AuthorRole.ASSISTANT: The special drink is Chai Tea. If you have any more questions, feel free to ask!
AuthorRole.USER: 'How much is that?'
Function Call:> MenuPlugin-get_item_price with arguments: {"menu_item":"Chai Tea"}
Function Result:> $9.99 for function: MenuPlugin-get_item_price
AuthorRole.ASSISTANT: The Chai Tea is priced at $9.99. If there's anything else you'd like to know,
just let me know!
AuthorRole.USER: 'Thank you'
AuthorRole.ASSISTANT: You're welcome! If you have any more questions or need further assistance, feel free to
ask. Enjoy your day!
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.
OpenAIAssistantAgent 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 el intérprete de código o la búsqueda de archivos, 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 OpenAIAssistantAgent clase con especificaciones declarativas:
AzureAssistantAgent Muestras:
- Intérprete de código
- Búsqueda de archivos
- Complemento de función desde un archivo
- Cargar desde un ID de Asistente existente
- Plantilla de solicitud
OpenAIAssistantAgent Muestras:
- Intérprete de código
- Búsqueda de archivos
- Plugin de Funciones
- Complemento de función desde un archivo
- Cargar desde un ID de Asistente existente
- Plantilla de solicitud
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: openai_assistant
name: Host
instructions: Respond politely to the user's questions.
model:
id: ${OpenAI: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.
Procedimiento
Para obtener un ejemplo de principio a fin para una OpenAIAssistantAgent, consulte:
- cómo hacerlo:
OpenAIAssistantAgentintérprete de código OpenAIAssistantAgentBúsqueda de archivos