Remarque
L’accès à cette page nécessite une autorisation. Vous pouvez essayer de vous connecter ou de modifier des répertoires.
L’accès à cette page nécessite une autorisation. Vous pouvez essayer de modifier des répertoires.
Note
Cet article fait référence à la version classique de l’API agents.
Utilisez cet article pour rechercher des instructions pas à pas et des exemples de code pour utiliser des outils OpenAPI.
Accédez au portail Microsoft Foundry. Dans l’écran Agents ou l’espace de jeu des agents, sélectionnez votre agent.
Faites défiler le volet Configuration jusqu’à la section Action. Ensuite, cliquez sur Ajouter.
Sélectionnez l’outil spécifié OpenAPI 3.0.
Donnez à votre outil un nom (obligatoire) et une description (facultatif). La description est utilisée par le modèle pour décider quand et comment utiliser l’outil.
Sélectionnez Suivant et sélectionnez votre méthode d’authentification.
- Si vous choisissez
connection, sélectionnez la connexion personnalisée avec une clé API. - Si vous choisissez
managed identity, entrez la valeur Audience . L’audience est l’identificateur de ressource OAuth2 de l’API que vous appelez. Pour obtenir des conseils et des valeurs d’audience courantes sur la recherche de la valeur correcte pour votre API, consultez S’authentifier avec une identité managée. Vérifiez que vous avez déjà configuré l’authentification et l’attribution de rôle comme décrit dans cette section.
- Si vous choisissez
Copiez et collez votre spécification OpenAPI dans la zone de texte.
Vérifiez et ajoutez l’outil à votre agent.
Initialisation
Configurez les importations nécessaires et initialisez le client AI Project.
# Import necessary libraries
import os
import jsonref
from azure.ai.projects import AIProjectClient
from azure.identity import DefaultAzureCredential
# import the following
from azure.ai.agents.models import OpenApiTool, OpenApiAnonymousAuthDetails
# use the following for connection auth
# from azure.ai.agents.models import OpenApiTool, OpenApiConnectionAuthDetails, OpenApiConnectionSecurityScheme
# use the following for managed identity auth
# from azure.ai.agents.models import OpenApiTool, OpenApiManagedAuthDetails, OpenApiManagedSecurityScheme
endpoint = os.environ["PROJECT_ENDPOINT"]
model_deployment_name = os.environ["MODEL_DEPLOYMENT_NAME"]
# Initialize the project client using the endpoint and default credentials
with AIProjectClient(
endpoint=endpoint,
credential=DefaultAzureCredential(exclude_interactive_browser_credential=False),
) as project_client:
Configuration de l’outil
Chargez la spécification OpenAPI à partir de weather.json. Créez un objet d’authentification anonyme (OpenApiAnonymousAuthDetails), car cette API spécifique ne nécessite pas d’authentification dans cet exemple. Vous trouverez un exemple de spécification OpenAPI sur GitHub.
# Load the OpenAPI specification for the weather service from a local JSON file
with open(os.path.join(os.path.dirname(__file__), "weather.json"), "r") as f:
openapi_weather = jsonref.loads(f.read())
# Create Auth object for the OpenApiTool (note: using anonymous auth here; connection or managed identity requires additional setup)
auth = OpenApiAnonymousAuthDetails()
# for connection setup
# auth = OpenApiConnectionAuthDetails(security_scheme=OpenApiConnectionSecurityScheme(connection_id=os.environ["CONNECTION_ID"]))
# for managed identity set up
# auth = OpenApiManagedAuthDetails(security_scheme=OpenApiManagedSecurityScheme(audience="https://your_identity_scope.com"))
# Initialize the main OpenAPI tool definition for weather
openapi_tool = OpenApiTool(
name="get_weather", spec=openapi_weather, description="Retrieve weather information for a location", auth=auth
)
Création de l’agent
Créez un agent à l’aide de la project_client.agents.create_agent méthode.
# Create an agent configured with the combined OpenAPI tool definitions
agent = project_client.agents.create_agent(
model=os.environ["MODEL_DEPLOYMENT_NAME"],
name="my-agent",
instructions="You are a helpful agent",
tools=openapi_tool.definitions,
)
print(f"Created agent, ID: {agent.id}")
Gestion des threads
Créez le thread et ajoutez le message utilisateur initial.
# Create a new conversation thread for the interaction
thread = project_client.agents.threads.create()
print(f"Created thread, ID: {thread.id}")
# Create the initial user message in the thread
message = project_client.agents.messages.create(
thread_id=thread.id,
role="user",
content="What's the weather in Seattle?",
)
print(f"Created message, ID: {message.id}")
Créer une exécution et vérifier la sortie
Créez l’exécution, vérifiez la sortie et examinez les outils qui ont été appelés pendant l’exécution.
# Create and automatically process the run, handling tool calls internally
run = project_client.agents.runs.create_and_process(thread_id=thread.id, agent_id=agent.id)
print(f"Run finished with status: {run.status}")
if run.status == "failed":
print(f"Run failed: {run.last_error}")
# Retrieve the steps taken during the run for analysis
run_steps = project_client.agents.run_steps.list(thread_id=thread.id, run_id=run.id)
# Loop through each step to display information
for step in run_steps:
print(f"Step {step['id']} status: {step['status']}")
tool_calls = step.get("step_details", {}).get("tool_calls", [])
for call in tool_calls:
print(f" Tool Call ID: {call.get('id')}")
print(f" Type: {call.get('type')}")
function_details = call.get("function", {})
if function_details:
print(f" Function name: {function_details.get('name')}")
print(f" function output: {function_details.get('output')}")
print()
Nettoyage
Une fois l’interaction terminée, le script nettoie en supprimant la ressource de l’agent créé à l’aide agents_client.delete_agent() d’éviter de laisser des ressources inutilisées. Il extrait et imprime également l’intégralité de l’historique des messages du thread en utilisant agents_client.messages.list() pour la révision ou la journalisation.
# Delete the agent resource to clean up
project_client.agents.delete_agent(agent.id)
print("Deleted agent")
# Fetch and log all messages exchanged during the conversation thread
messages = project_client.agents.messages.list(thread_id=thread.id)
for msg in messages:
print(f"Message ID: {msg.id}, Role: {msg.role}, Content: {msg.content}")
Créer un client de projet
Créez un objet client qui contient le point de terminaison pour la connexion à votre projet IA et à d’autres ressources.
const { AgentsClient, isOutputOfType, ToolUtility } = require("@azure/ai-agents");
const { delay } = require("@azure/core-util");
const { DefaultAzureCredential } = require("@azure/identity");
const fs = require("fs");
require("dotenv/config");
const projectEndpoint = process.env["PROJECT_ENDPOINT"];
// Create an Azure AI Client
const client = new AgentsClient(projectEndpoint, new DefaultAzureCredential());
Lire dans la spécification OpenAPI
Vous trouverez un exemple de spécification OpenAPI sur GitHub.
// Read in OpenApi spec
const filePath = "./data/weatherOpenApi.json";
const openApiSpec = JSON.parse(fs.readFileSync(filePath, "utf-8"));
// Define OpenApi function
const openApiFunction = {
name: "getWeather",
spec: openApiSpec,
description: "Retrieve weather information for a location",
auth: {
type: "anonymous",
},
default_params: ["format"], // optional
};
Créer un agent et activer l’outil OpenAPI
// Create OpenApi tool
const openApiTool = ToolUtility.createOpenApiTool(openApiFunction);
// Create agent with OpenApi tool
const agent = await client.createAgent(modelDeploymentName, {
name: "myAgent",
instructions: "You are a helpful agent",
tools: [openApiTool.definition],
});
console.log(`Created agent, agent ID: ${agent.id}`);
Créer un thread
// Create a thread
const thread = await client.threads.create();
console.log(`Created thread, thread ID: ${thread.id}`);
// Create a message
const message = await client.messages.create(thread.id, "user", "What's the weather in Seattle?");
console.log(`Created message, message ID: ${message.id}`);
Créer une exécution et vérifier la sortie
// Create and execute a run
let run = await client.runs.create(thread.id, agent.id);
while (run.status === "queued" || run.status === "in_progress") {
await delay(1000);
run = await client.runs.get(thread.id, run.id);
}
if (run.status === "failed") {
// Check if you got "Rate limit is exceeded.", then you want to get more quota
console.log(`Run failed: ${run.lastError}`);
}
console.log(`Run finished with status: ${run.status}`);
// Get most recent message from the assistant
const messagesIterator = client.messages.list(thread.id);
const messages = [];
for await (const m of messagesIterator) {
messages.push(m);
}
const assistantMessage = messages.find((msg) => msg.role === "assistant");
if (assistantMessage) {
const textContent = assistantMessage.content.find((content) => isOutputOfType(content, "text"));
if (textContent) {
console.log(`Last message: ${textContent.text.value}`);
}
}
// Delete the agent once done
await client.deleteAgent(agent.id);
console.log(`Deleted agent, agent ID: ${agent.id}`);
Configurer l’outil client et OpenAPI
Tout d’abord, récupérez les détails de configuration et créez un PersistentAgentsClient, puis définissez le OpenApiToolDefinition en utilisant la spécification OpenAPI. Vous trouverez un exemple de spécification OpenAPI sur GitHub.
using Azure;
using Azure.AI.Agents.Persistent;
using Azure.Identity;
using Microsoft.Extensions.Configuration;
IConfigurationRoot configuration = new ConfigurationBuilder()
.SetBasePath(AppContext.BaseDirectory)
.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
.Build();
var projectEndpoint = configuration["ProjectEndpoint"];
var modelDeploymentName = configuration["ModelDeploymentName"];
var openApiSpec = configuration["OpenApiSpec"];
PersistentAgentsClient client = new(projectEndpoint, new DefaultAzureCredential());
BinaryData spec = BinaryData.FromBytes(File.ReadAllBytes(openApiSpec));
// Using anonymous auth for this example
OpenApiAnonymousAuthDetails openApiAnonAuth = new();
// Define the OpenAPI tool
OpenApiToolDefinition openApiToolDef = new(
name: "get_weather",
description: "Retrieve weather information for a location",
spec: spec,
openApiAuthentication: openApiAnonAuth,
defaultParams: ["format"]
);
Créer un agent
Ensuite, créez un PersistentAgent avec le déploiement de modèle nécessaire, le nom, les instructions et l’outil OpenAPI précédemment défini.
PersistentAgent agent = client.Administration.CreateAgent(
model: modelDeploymentName,
name: "Open API Tool Calling Agent",
instructions: "You are a helpful agent.",
tools: [openApiToolDef]
);
Créer un thread, un message et exécuter
Créez une PersistentAgentThread conversation, ajoutez un message utilisateur à celui-ci, puis créez-en un ThreadRun pour traiter le message, en attendant sa fin.
PersistentAgentThread thread = client.Threads.CreateThread();
client.Messages.CreateMessage(
thread.Id,
MessageRole.User,
"What's the weather in Seattle?");
ThreadRun run = client.Runs.CreateRun(
thread.Id,
agent.Id);
// Poll for the run's completion status
do
{
Thread.Sleep(TimeSpan.FromMilliseconds(500));
run = client.Runs.GetRun(thread.Id, run.Id);
}
while (run.Status == RunStatus.Queued
|| run.Status == RunStatus.InProgress
|| run.Status == RunStatus.RequiresAction);
Afficher les messages de conversation
Récupérez et imprimez tous les messages du thread vers la console par ordre chronologique pour afficher le flux de conversation.
Pageable<PersistentThreadMessage> messages = client.Messages.GetMessages(
threadId: thread.Id,
order: ListSortOrder.Ascending);
foreach (PersistentThreadMessage threadMessage in messages)
{
foreach (MessageContent content in threadMessage.ContentItems)
{
switch (content)
{
case MessageTextContent textItem:
Console.WriteLine($"[{threadMessage.Role}]: {textItem.Text}");
break;
}
}
Nettoyer les ressources
Enfin, supprimez les éléments PersistentAgentThread et PersistentAgent créés pour nettoyer les ressources utilisées dans cet exemple.
client.Threads.DeleteThread(thread.Id);
client.Administration.DeleteAgent(agent.Id);
Suivez le guide de démarrage rapide de l’API REST pour définir les valeurs appropriées pour les variables AGENT_TOKENd’environnement, AZURE_AI_FOUNDRY_PROJECT_ENDPOINTet API_VERSION.
Créer la définition de l’outil Spec OpenAPI, l’agent et le thread
Vous voudrez peut-être stocker la spécification OpenAPI dans un autre fichier et importer le contenu pour initialiser l’outil. Les exemples suivants montrent comment utiliser anonymous et connection (clé API) les types d’authentification. Vous trouverez un exemple de spécification OpenAPI sur GitHub.
Authentification anonyme
Cet exemple utilise anonymous comme type d’authentification pour les API qui ne nécessitent pas d’authentification.
curl --request POST \
--url $AZURE_AI_FOUNDRY_PROJECT_ENDPOINT/assistants?api-version=$API_VERSION \
-H "Authorization: Bearer $AGENT_TOKEN" \
-H "Content-Type: application/json" \
-d '{
"instructions": "You are a weather bot. Use the provided functions to answer questions about the weather.",
"model": "gpt-4o",
"tools": [{
"type": "openapi",
"openapi": {
"name": "weatherapp",
"description": "Tool to get weather data",
"auth": {
"type": "anonymous"
},
"spec": {
"openapi": "3.1.0",
"info": {
"title": "get weather data",
"description": "Retrieves current weather data for a location.",
"version": "v1.0.0"
},
"servers": [{
"url": "https://wttr.in"
}],
"auth": [],
"paths": {
"/{location}": {
"get": {
"description": "Get weather information for a specific location",
"operationId": "GetCurrentWeather",
"parameters": [
{
"name": "location",
"in": "path",
"description": "City or location to retrieve the weather for",
"required": true,
"schema": {
"type": "string"
}
},
{
"name": "format",
"in": "query",
"description": "Format in which to return data. Always use 3.",
"required": true,
"schema": {
"type": "integer",
"default": 3
}
}
],
"responses": {
"200": {
"description": "Successful response",
"content": {
"text/plain": {
"schema": {
"type": "string"
}
}
}
},
"404": {
"description": "Location not found"
}
},
"deprecated": false
}
}
},
"components": {
"schemes": { }
}
}
}
}]
}'
Authentification par clé API
Cet exemple utilise connection comme type d’authentification pour les API qui nécessitent une clé API. Avant d’utiliser cet exemple, vous devez créer une connexion de clés personnalisées pour stocker votre clé API. Pour obtenir des instructions, consultez Authentifier avec la clé API.
Remplacez {connection-id} par l’ID de ressource complet de votre connexion, qui suit ce format : /subscriptions/{subscription-id}/resourceGroups/{resource-group}/providers/Microsoft.MachineLearningServices/workspaces/{project-name}/connections/{connection-name}.
curl --request POST \
--url $AZURE_AI_FOUNDRY_PROJECT_ENDPOINT/assistants?api-version=$API_VERSION \
-H "Authorization: Bearer $AGENT_TOKEN" \
-H "Content-Type: application/json" \
-d '{
"instructions": "You are a helpful assistant that can retrieve data from an external API.",
"model": "gpt-4o",
"tools": [{
"type": "openapi",
"openapi": {
"name": "my_api_tool",
"description": "Tool to interact with an API that requires authentication",
"auth": {
"type": "connection",
"connection_id": "{connection-id}"
},
"spec": {
"openapi": "3.1.0",
"info": {
"title": "Example API",
"description": "An example API that requires API key authentication.",
"version": "v1.0.0"
},
"servers": [{
"url": "https://api.example.com"
}],
"security": [
{
"apiKeyHeader": []
}
],
"paths": {
"/data": {
"get": {
"description": "Retrieve data from the API",
"operationId": "GetData",
"responses": {
"200": {
"description": "Successful response",
"content": {
"application/json": {
"schema": {
"type": "object"
}
}
}
},
"401": {
"description": "Unauthorized"
}
},
"deprecated": false
}
}
},
"components": {
"securitySchemes": {
"apiKeyHeader": {
"type": "apiKey",
"name": "x-api-key",
"in": "header"
}
}
}
}
}
}]
}'
Créer une exécution et vérifier la sortie
Créez une exécution et observez que le modèle utilise l’outil spécifié OpenAPI pour fournir une réponse à la question de l’utilisateur.
Créer un thread
curl --request POST \
--url $AZURE_AI_FOUNDRY_PROJECT_ENDPOINT/threads?api-version=$API_VERSION \
-H "Authorization: Bearer $AGENT_TOKEN" \
-H "Content-Type: application/json" \
-d ''
Ajouter une question utilisateur au thread
curl curl --request POST \
--url $AZURE_AI_FOUNDRY_PROJECT_ENDPOINT/threads/thread_abc123/messages?api-version=$API_VERSION \
-H "Authorization: Bearer $AGENT_TOKEN" \
-H "Content-Type: application/json" \
-d '{
"role": "user",
"content": "What is the weather in Seattle?"
}'
Exécuter le thread
curl --request POST \
--url $AZURE_AI_FOUNDRY_PROJECT_ENDPOINT/threads/thread_abc123/runs?api-version=$API_VERSION \
-H "Authorization: Bearer $AGENT_TOKEN" \
-H "Content-Type: application/json" \
-d '{
"assistant_id": "asst_abc123",
}'
Récupérer l’état de l’exécution
curl --request GET \
--url $AZURE_AI_FOUNDRY_PROJECT_ENDPOINT/threads/thread_abc123/runs/run_abc123?api-version=$API_VERSION \
-H "Authorization: Bearer $AGENT_TOKEN"
Récupérer la réponse de l’agent
curl --request GET \
--url $AZURE_AI_FOUNDRY_PROJECT_ENDPOINT/threads/thread_abc123/messages?api-version=$API_VERSION \
-H "Authorization: Bearer $AGENT_TOKEN"
Exemple de code
Le code d’exemple suivant utilise une fonction OpenAPI d’exemple dans un fichier nommé weather_openapi.json. Vous trouverez la définition de la fonction sur GitHub.
package com.example.agents;
import com.azure.ai.agents.persistent.MessagesClient;
import com.azure.ai.agents.persistent.PersistentAgentsAdministrationClient;
import com.azure.ai.agents.persistent.PersistentAgentsClient;
import com.azure.ai.agents.persistent.PersistentAgentsClientBuilder;
import com.azure.ai.agents.persistent.RunsClient;
import com.azure.ai.agents.persistent.ThreadsClient;
import com.azure.ai.agents.persistent.models.CreateAgentOptions;
import com.azure.ai.agents.persistent.models.CreateRunOptions;
import com.azure.ai.agents.persistent.models.MessageImageFileContent;
import com.azure.ai.agents.persistent.models.MessageRole;
import com.azure.ai.agents.persistent.models.MessageTextContent;
import com.azure.ai.agents.persistent.models.OpenApiAnonymousAuthDetails;
import com.azure.ai.agents.persistent.models.OpenApiFunctionDefinition;
import com.azure.ai.agents.persistent.models.OpenApiToolDefinition;
import com.azure.ai.agents.persistent.models.PersistentAgent;
import com.azure.ai.agents.persistent.models.PersistentAgentThread;
import com.azure.ai.agents.persistent.models.RunStatus;
import com.azure.ai.agents.persistent.models.ThreadMessage;
import com.azure.ai.agents.persistent.models.ThreadRun;
import com.azure.ai.agents.persistent.models.MessageContent;
import com.azure.core.http.rest.PagedIterable;
import com.azure.core.util.BinaryData;
import com.azure.identity.DefaultAzureCredentialBuilder;
import com.azure.json.JsonProviders;
import com.azure.json.JsonReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Arrays;
public class AgentExample {
public static void main(String[] args) throws IOException, URISyntaxException {
// variables for authenticating requests to the agent service
String projectEndpoint = System.getenv("PROJECT_ENDPOINT");
String modelName = System.getenv("MODEL_DEPLOYMENT_NAME");
PersistentAgentsClientBuilder clientBuilder = new PersistentAgentsClientBuilder().endpoint(projectEndpoint)
.credential(new DefaultAzureCredentialBuilder().build());
PersistentAgentsClient agentsClient = clientBuilder.buildClient();
PersistentAgentsAdministrationClient administrationClient = agentsClient.getPersistentAgentsAdministrationClient();
ThreadsClient threadsClient = agentsClient.getThreadsClient();
MessagesClient messagesClient = agentsClient.getMessagesClient();
RunsClient runsClient = agentsClient.getRunsClient();
Path filePath = getFile("weather_openapi.json");
JsonReader reader = JsonProviders.createReader(Files.readAllBytes(filePath));
OpenApiAnonymousAuthDetails oaiAuth = new OpenApiAnonymousAuthDetails();
OpenApiToolDefinition openApiTool = new OpenApiToolDefinition(new OpenApiFunctionDefinition(
"openapitool",
reader.getNullable(nonNullReader -> BinaryData.fromObject(nonNullReader.readUntyped())),
oaiAuth
));
String agentName = "openAPI_example";
CreateAgentOptions createAgentOptions = new CreateAgentOptions(modelName)
.setName(agentName)
.setInstructions("You are a helpful agent")
.setTools(Arrays.asList(openApiTool));
PersistentAgent agent = administrationClient.createAgent(createAgentOptions);
PersistentAgentThread thread = threadsClient.createThread();
ThreadMessage createdMessage = messagesClient.createMessage(
thread.getId(),
MessageRole.USER,
"What's the weather in seattle?");
try {
//run agent
CreateRunOptions createRunOptions = new CreateRunOptions(thread.getId(), agent.getId())
.setAdditionalInstructions("");
ThreadRun threadRun = runsClient.createRun(createRunOptions);
waitForRunCompletion(thread.getId(), threadRun, runsClient);
printRunMessages(messagesClient, thread.getId());
} catch (InterruptedException e) {
throw new RuntimeException(e);
} finally {
//cleanup
threadsClient.deleteThread(thread.getId());
administrationClient.deleteAgent(agent.getId());
}
}
private static Path getFile(String fileName) throws FileNotFoundException, URISyntaxException {
URL resource = AgentExample.class.getClassLoader().getResource(fileName);
if (resource == null) {
throw new FileNotFoundException("File not found");
}
File file = new File(resource.toURI());
return file.toPath();
}
// A helper function to print messages from the agent
public static void printRunMessages(MessagesClient messagesClient, String threadId) {
PagedIterable<ThreadMessage> runMessages = messagesClient.listMessages(threadId);
for (ThreadMessage message : runMessages) {
System.out.print(String.format("%1$s - %2$s : ", message.getCreatedAt(), message.getRole()));
for (MessageContent contentItem : message.getContent()) {
if (contentItem instanceof MessageTextContent) {
System.out.print((((MessageTextContent) contentItem).getText().getValue()));
} else if (contentItem instanceof MessageImageFileContent) {
String imageFileId = (((MessageImageFileContent) contentItem).getImageFile().getFileId());
System.out.print("Image from ID: " + imageFileId);
}
System.out.println();
}
}
}
// a helper function to wait until a run has completed running
public static void waitForRunCompletion(String threadId, ThreadRun threadRun, RunsClient runsClient)
throws InterruptedException {
do {
Thread.sleep(500);
threadRun = runsClient.getRun(threadId, threadRun.getId());
}
while (
threadRun.getStatus() == RunStatus.QUEUED
|| threadRun.getStatus() == RunStatus.IN_PROGRESS
|| threadRun.getStatus() == RunStatus.REQUIRES_ACTION);
if (threadRun.getStatus() == RunStatus.FAILED) {
System.out.println(threadRun.getLastError().getMessage());
}
}
}