Exploration du noyau sémantique AzureAIAgent
Important
Cette fonctionnalité est à l’étape expérimentale. Les fonctionnalités à ce stade sont toujours en cours de développement et soumises à des modifications avant de passer à la phase de préversion ou de version candidate.
La documentation détaillée de l’API relative à cette discussion est disponible à l’adresse suivante :
Les documents de l’API Python du noyau sémantique mis à jour seront bientôt disponibles.
Les agents sont actuellement indisponibles en Java.
Qu’est-ce qu’un AzureAIAgent
?
Un AzureAIAgent
est un agent spécialisé dans l’infrastructure de noyau sémantique, conçu pour fournir des fonctionnalités conversationnelles avancées avec une intégration transparente des outils. Il automatise l’appel d’outils, éliminant ainsi la nécessité d’analyser et d’appeler manuellement. L’agent gère également en toute sécurité l’historique des conversations à l’aide de threads, réduisant ainsi la charge de la gestion de l'état. En outre, le AzureAIAgent
prend en charge un large éventail d’outils intégrés, notamment la récupération de fichiers, l’exécution du code et l’interaction des données via Bing, Azure AI Search, Azure Functions et OpenAPI.
Pour utiliser un AzureAIAgent
, un projet Azure AI Foundry doit être utilisé. Les articles suivants fournissent une vue d’ensemble d’Azure AI Foundry, de la création et de la configuration d’un projet et du service d’agent :
- Qu’est-ce qu’Azure AI Foundry ?
- le Kit de développement logiciel (SDK) Azure AI Foundry
- Qu’est-ce qu’azure AI Agent Service
- Démarrage rapide : Créer un nouvel agent
Préparation de votre environnement de développement
Pour poursuivre le développement d’un AzureAIAgent
, configurez votre environnement de développement avec les packages appropriés.
Ajoutez le package Microsoft.SemanticKernel.Agents.AzureAI
à votre projet :
dotnet add package Microsoft.SemanticKernel.Agents.AzureAI --prerelease
Vous pouvez également inclure le package Azure.Identity
:
dotnet add package Azure.Identity
Installez le package semantic-kernel
avec les dépendances Azure facultatives :
pip install semantic-kernel[azure]
Les agents sont actuellement indisponibles en Java.
Configuration du client de projet IA
L’accès à un AzureAIAgent
nécessite d’abord la création d’un client de projet configuré pour un projet Foundry spécifique, le plus souvent en fournissant une chaîne de connexion (Le Kit de développement logiciel (SDK) Azure AI Foundry : Prise en main des projets).
AIProjectClient client = AzureAIAgent.CreateAzureAIClient("<your connection-string>", new AzureCliCredential());
Le AgentsClient
est accessible à partir du AIProjectClient
:
AgentsClient agentsClient = client.GetAgentsClient();
Modifiez le fichier .env
dans le répertoire racine pour inclure :
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>"
Une fois la configuration définie, le client peut être créé :
async with (
DefaultAzureCredential() as creds,
AzureAIAgent.create_client(credential=creds) as client,
):
# Your operational code here
Les agents sont actuellement indisponibles en Java.
Création d’un AzureAIAgent
Pour créer un AzureAIAgent
, vous commencez par configurer et initialiser le projet d’agent via le service Azure AI, puis l’intégrer au noyau sémantique :
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,
)
Les agents sont actuellement indisponibles en Java.
Interaction avec un AzureAIAgent
L’interaction avec le AzureAIAgent
est simple. L’agent gère automatiquement l’historique des conversations à l’aide d’un 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)
Si vous le souhaitez, un agent peut être appelé comme suit :
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)
Un agent peut également produire une réponse diffusée en continu :
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)
Les agents sont actuellement indisponibles en Java.
Utilisation de plug-ins avec un AzureAIAgent
Le noyau sémantique prend en charge l’extension d’un AzureAIAgent
avec des plug-ins personnalisés pour des fonctionnalités améliorées :
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()]
)
Les agents sont actuellement indisponibles en Java.
Fonctionnalités avancées
Un AzureAIAgent
peut tirer parti d’outils avancés tels que :
Interpréteur de code
L’interpréteur de code permet aux agents d’écrire et d’exécuter du code Python dans un environnement d’exécution en bac à sable (interpréteur de code du service 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 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,
)
Les agents sont actuellement indisponibles en Java.
Recherche de fichiers
La recherche de fichiers enrichit les agents avec des connaissances extérieures à leur modèle (Outil de recherche de fichiers du service 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,
)
Les agents sont actuellement indisponibles en Java.
Intégration OpenAPI
Connecte votre agent à une API externe (How to use Azure AI Agent Service with OpenAPI Specified Tools).
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,
)
Les agents sont actuellement indisponibles en Java.
Intégration de recherche AzureAI
Utiliser un index Azure AI Search existant avec votre agent (Utiliser un index Azure AI Search existant).
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"},
)
Les agents sont actuellement indisponibles en Java.
Récupération d’un AzureAIAgent
existant
Un agent existant peut être récupéré et réutilisé en spécifiant son ID d’assistant :
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)
Les agents sont actuellement indisponibles en Java.
Suppression d’un AzureAIAgent
Les agents et leurs threads associés peuvent être supprimés lorsqu'ils ne sont plus nécessaires.
await agentsClient.DeleteThreadAsync(thread.Id);
await agentsClient.DeleteAgentAsync(agent.Id);
await client.agents.delete_thread(thread.id)
await client.agents.delete_agent(agent.id)
Si vous utilisez un magasin de vecteurs ou des fichiers, ils peuvent également être supprimés :
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)
Les agents sont actuellement indisponibles en Java.
Pour plus d’informations sur l’outil de recherche de fichiers , consultez l’article 'outil de recherche de fichiers azure AI Agent service.
How-To
Pour obtenir des exemples pratiques d’utilisation d’un AzureAIAgent
, consultez nos exemples de code sur GitHub :
- bien démarrer avec les agents Azure AI
- exemples de code d’agent Azure AI avancés
- bien démarrer avec les agents Azure AI
- exemples de code d’agent Azure AI avancés
Les agents sont actuellement indisponibles en Java.
Collaboration des agents dans le chat des agents