Nota
L'accesso a questa pagina richiede l'autorizzazione. È possibile provare ad accedere o modificare le directory.
L'accesso a questa pagina richiede l'autorizzazione. È possibile provare a modificare le directory.
Gli agenti Foundry di Microsoft supportano la chiamata a funzioni, un funzionamento che consente di estendere gli agenti con funzionalità personalizzate. Definire una funzione con il suo nome, i parametri e la descrizione, così il modello Foundry dell'agente può richiedere alla tua app di chiamarla. L'app esegue la funzione e restituisce l'output. L'agente usa quindi il risultato per continuare la conversazione con dati accurati e in tempo reale dai sistemi.
Importante
Le esecuzioni scadono 10 minuti dopo la creazione. Invia gli output dello strumento prima della scadenza.
È possibile eseguire agenti con strumenti per le funzioni nel portale di Microsoft Foundry. Tuttavia, il portale non supporta l'aggiunta, la rimozione o l'aggiornamento delle definizioni di funzione in un agente. Usare l'SDK o l'API REST per configurare gli strumenti per le funzioni.
Supporto per l'utilizzo
La tabella seguente illustra il supporto dell'SDK e della configurazione.
| Supporto Foundry di Microsoft | PYTHON SDK | C# SDK | JavaScript SDK | JAVA SDK | REST API | Configurazione dell'agente di base | Configurazione dell'agente standard |
|---|---|---|---|---|---|---|---|
| ✔️ | ✔️ | ✔️ | ✔️ | ✔️ | ✔️ | ✔️ | ✔️ |
Prerequisiti
Prima di iniziare, assicurarsi di avere:
Un progetto Foundry e un modello distribuito.
Pacchetto SDK per la lingua:
- Python:
azure-ai-projects(versione più recente) - .NET:
Azure.AI.Extensions.OpenAI - TypeScript:
@azure/ai-projects(ultima versione) - Java:
azure-ai-agents
Per la procedura di installazione e autenticazione, vedere la guida introduttiva.
- Python:
Suggerimento
Se si usa DefaultAzureCredential, accedere usando az login prima di eseguire gli esempi.
Creare un agente con gli strumenti per le funzioni
La chiamata di funzione segue questo modello:
- Definire gli strumenti per le funzioni : descrivere il nome, i parametri e lo scopo di ogni funzione.
- Creare un agente : registrare l'agente con le definizioni di funzione.
- Invia un prompt — l'agente analizza il prompt e richiede chiamate di funzione, se necessario.
- Esegui e restituisce : l'app esegue la funzione e invia di nuovo l'output all'agente.
- Ottenere la risposta finale: l'agente usa l'output della funzione per completare la risposta.
Usare l'esempio di codice seguente per creare un agente, gestire una chiamata di funzione e restituire l'output dello strumento all'agente.
import json
from azure.ai.projects import AIProjectClient
from azure.ai.projects.models import PromptAgentDefinition, Tool, FunctionTool
from azure.identity import DefaultAzureCredential
from openai.types.responses.response_input_param import FunctionCallOutput, ResponseInputParam
def get_horoscope(sign: str) -> str:
"""Generate a horoscope for the given astrological sign."""
return f"{sign}: Next Tuesday you will befriend a baby otter."
# Format: "https://resource_name.ai.azure.com/api/projects/project_name"
PROJECT_ENDPOINT = "your_project_endpoint"
project = AIProjectClient(
endpoint=PROJECT_ENDPOINT,
credential=DefaultAzureCredential(),
)
openai = project.get_openai_client()
# Create a conversation for multi-turn interaction
conversation = openai.conversations.create()
# Define a function tool for the model to use
func_tool = FunctionTool(
name="get_horoscope",
parameters={
"type": "object",
"properties": {
"sign": {
"type": "string",
"description": "An astrological sign like Taurus or Aquarius",
},
},
"required": ["sign"],
"additionalProperties": False,
},
description="Get today's horoscope for an astrological sign.",
strict=True,
)
tools: list[Tool] = [func_tool]
agent = project.agents.create_version(
agent_name="MyAgent",
definition=PromptAgentDefinition(
model="gpt-4.1-mini",
instructions="You are a helpful assistant that can use function tools.",
tools=tools,
),
)
# Prompt the model with tools defined
response = openai.responses.create(
input="What is my horoscope? I am an Aquarius.",
conversation=conversation.id,
extra_body={"agent_reference": {"name": agent.name, "type": "agent_reference"}},
)
input_list: ResponseInputParam = []
# Process function calls
for item in response.output:
if item.type == "function_call":
if item.name == "get_horoscope":
# Execute the function logic for get_horoscope
horoscope = get_horoscope(**json.loads(item.arguments))
# Provide function call results to the model
input_list.append(
FunctionCallOutput(
type="function_call_output",
call_id=item.call_id,
output=json.dumps({"horoscope": horoscope}),
)
)
# Submit function results and get the final response
response = openai.responses.create(
input=input_list,
conversation=conversation.id,
extra_body={"agent_reference": {"name": agent.name, "type": "agent_reference"}},
)
print(f"Agent response: {response.output_text}")
# Clean up resources
project.agents.delete_version(agent_name=agent.name, agent_version=agent.version)
openai.conversations.delete(conversation_id=conversation.id)
Output previsto
L'esempio seguente mostra l'output previsto:
Agent response: Your horoscope for Aquarius: Next Tuesday you will befriend a baby otter.
Usare agenti con funzioni di esempio
In questo esempio si usano funzioni locali con gli agenti. Usare le funzioni per fornire all'agente informazioni specifiche in risposta a una domanda dell'utente. Il codice in questo esempio è sincrono. Per un esempio asincrono, vedere l'esempio di codice sample nell'Azure SDK per .NET repository in GitHub.
using System;
using Azure.AI.Projects;
using Azure.AI.Extensions.OpenAI;
using Azure.Identity;
class FunctionCallingDemo
{
// Define three functions:
// 1. GetUserFavoriteCity always returns "Seattle, WA".
// 2. GetCityNickname handles only "Seattle, WA"
// and throws an exception for other city names.
// 3. GetWeatherAtLocation returns the weather in Seattle, WA.
/// Example of a function that defines no parameters but
/// returns the user's favorite city.
private static string GetUserFavoriteCity() => "Seattle, WA";
/// <summary>
/// Example of a function with a single required parameter
/// </summary>
/// <param name="location">The location to get nickname for.</param>
/// <returns>The city nickname.</returns>
/// <exception cref="NotImplementedException"></exception>
private static string GetCityNickname(string location) => location switch
{
"Seattle, WA" => "The Emerald City",
_ => throw new NotImplementedException(),
};
/// <summary>
/// Example of a function with one required and one optional, enum parameter
/// </summary>
/// <param name="location">Get weather for location.</param>
/// <param name="temperatureUnit">"c" or "f"</param>
/// <returns>The weather in selected location.</returns>
/// <exception cref="NotImplementedException"></exception>
public static string GetWeatherAtLocation(string location, string temperatureUnit = "f") => location switch
{
"Seattle, WA" => temperatureUnit == "f" ? "70f" : "21c",
_ => throw new NotImplementedException()
};
// For each function, create FunctionTool, which defines the function name, description, and parameters.
public static readonly FunctionTool getUserFavoriteCityTool = ResponseTool.CreateFunctionTool(
functionName: "getUserFavoriteCity",
functionDescription: "Gets the user's favorite city.",
functionParameters: BinaryData.FromString("{}"),
strictModeEnabled: false
);
public static readonly FunctionTool getCityNicknameTool = ResponseTool.CreateFunctionTool(
functionName: "getCityNickname",
functionDescription: "Gets the nickname of a city, e.g. 'LA' for 'Los Angeles, CA'.",
functionParameters: BinaryData.FromObjectAsJson(
new
{
Type = "object",
Properties = new
{
Location = new
{
Type = "string",
Description = "The city and state, e.g. San Francisco, CA",
},
},
Required = new[] { "location" },
},
new JsonSerializerOptions() { PropertyNamingPolicy = JsonNamingPolicy.CamelCase }
),
strictModeEnabled: false
);
private static readonly FunctionTool getCurrentWeatherAtLocationTool = ResponseTool.CreateFunctionTool(
functionName: "getCurrentWeatherAtLocation",
functionDescription: "Gets the current weather at a provided location.",
functionParameters: BinaryData.FromObjectAsJson(
new
{
Type = "object",
Properties = new
{
Location = new
{
Type = "string",
Description = "The city and state, e.g. San Francisco, CA",
},
Unit = new
{
Type = "string",
Enum = new[] { "c", "f" },
},
},
Required = new[] { "location" },
},
new JsonSerializerOptions() { PropertyNamingPolicy = JsonNamingPolicy.CamelCase }
),
strictModeEnabled: false
);
// Create the method GetResolvedToolOutput.
// It runs the preceding functions and wraps the output in a ResponseItem object.
private static FunctionCallOutputResponseItem GetResolvedToolOutput(FunctionCallResponseItem item)
{
if (item.FunctionName == getUserFavoriteCityTool.FunctionName)
{
return ResponseItem.CreateFunctionCallOutputItem(item.CallId, GetUserFavoriteCity());
}
using JsonDocument argumentsJson = JsonDocument.Parse(item.FunctionArguments);
if (item.FunctionName == getCityNicknameTool.FunctionName)
{
string locationArgument = argumentsJson.RootElement.GetProperty("location").GetString();
return ResponseItem.CreateFunctionCallOutputItem(item.CallId, GetCityNickname(locationArgument));
}
if (item.FunctionName == getCurrentWeatherAtLocationTool.FunctionName)
{
string locationArgument = argumentsJson.RootElement.GetProperty("location").GetString();
if (argumentsJson.RootElement.TryGetProperty("unit", out JsonElement unitElement))
{
string unitArgument = unitElement.GetString();
return ResponseItem.CreateFunctionCallOutputItem(item.CallId, GetWeatherAtLocation(locationArgument, unitArgument));
}
return ResponseItem.CreateFunctionCallOutputItem(item.CallId, GetWeatherAtLocation(locationArgument));
}
return null;
}
// Format: "https://resource_name.ai.azure.com/api/projects/project_name"
private const string ProjectEndpoint = "your_project_endpoint";
public static void Main()
{
AIProjectClient projectClient = new(endpoint: new Uri(ProjectEndpoint), tokenProvider: new DefaultAzureCredential());
// Create an agent version with the defined functions as tools.
DeclarativeAgentDefinition agentDefinition = new(model: "gpt-4.1-mini")
{
Instructions = "You are a weather bot. Use the provided functions to help answer questions. "
+ "Customize your responses to the user's preferences as much as possible and use friendly "
+ "nicknames for cities whenever possible.",
Tools = { getUserFavoriteCityTool, getCityNicknameTool, getCurrentWeatherAtLocationTool }
};
AgentVersion agentVersion = projectClient.AgentAdministrationClient.CreateAgentVersion(
agentName: "myAgent",
options: new(agentDefinition));
// If the local function call is required, the response item is of type FunctionCallResponseItem.
// It contains the function name needed by the Agent. In this case, use the helper method
// GetResolvedToolOutput to get the FunctionCallOutputResponseItem with the function call result.
// To provide the right answer, supply all the response items to the CreateResponse call.
// At the end, output the function's response.
ResponsesClient responseClient = projectClient.ProjectOpenAIClient.GetProjectResponsesClientForAgent(agentVersion.Name);
ResponseItem request = ResponseItem.CreateUserMessageItem("What's the weather like in my favorite city?");
var inputItems = new List<ResponseItem> { request };
string previousResponseId = null;
bool functionCalled = false;
ResponseResult response;
do
{
response = responseClient.CreateResponse(
previousResponseId: previousResponseId,
inputItems: inputItems);
previousResponseId = response.Id;
inputItems.Clear();
functionCalled = false;
foreach (ResponseItem responseItem in response.OutputItems)
{
inputItems.Add(responseItem);
if (responseItem is FunctionCallResponseItem functionToolCall)
{
Console.WriteLine($"Calling {functionToolCall.FunctionName}...");
inputItems.Add(GetResolvedToolOutput(functionToolCall));
functionCalled = true;
}
}
} while (functionCalled);
Console.WriteLine(response.GetOutputText());
// Remove all the resources created in this sample.
projectClient.AgentAdministrationClient.DeleteAgentVersion(agentName: agentVersion.Name, agentVersion: agentVersion.Version);
}
}
Output previsto
L'esempio seguente mostra l'output previsto:
Calling getUserFavoriteCity...
Calling getCityNickname...
Calling getCurrentWeatherAtLocation...
Your favorite city, Seattle, WA, is also known as The Emerald City. The current weather there is 70f.
Esistono due modi per usare la chiamata di funzione nel Servizio Agente Foundry.
- Creare un oggetto
response. Quando è necessario che l'agente chiami di nuovo le funzioni, devi creare un altroresponseoggetto. - Crea un
conversationoggetto, poi crea diversi elementi di conversazione. Ogni elemento della conversazione corrisponde a un elementoresponse.
Impostare le variabili di ambiente seguenti prima di eseguire gli esempi:
export AGENT_TOKEN=$(az account get-access-token --scope "https://ai.azure.com/.default" --query accessToken -o tsv)
Definire una funzione che l'agente deve chiamare
Per iniziare, definire una funzione che l'agente chiamerà. Quando si crea una funzione che un agente deve chiamare, descrivere la sua struttura e tutti i parametri necessari in una docstring. Per le funzioni di esempio, vedere gli altri linguaggi SDK.
Creare un agente
curl -X POST "$FOUNDRY_PROJECT_ENDPOINT/agents?api-version=v1" \
-H "Content-Type: application/json" \
-H "Authorization: Bearer $AGENT_TOKEN" \
-d '{
"name": "<AGENT_NAME>-function-calling",
"description": "Agent with function calling",
"definition": {
"kind": "prompt",
"model": "<MODEL_DEPLOYMENT>",
"instructions": "You are a helpful agent.",
"tools": [
{
"type": "function",
"name": "getCurrentWeather",
"description": "Get the current weather in a location",
"parameters": {
"type": "object",
"properties": {
"location": {"type": "string", "description": "The city and state e.g. San Francisco, CA"},
"unit": {"type": "string", "enum": ["c", "f"]}
},
"required": ["location"]
}
}
]
}
}'
Creare una conversazione
curl -X POST "$FOUNDRY_PROJECT_ENDPOINT/openai/v1/conversations" \
-H "Content-Type: application/json" \
-H "Authorization: Bearer $AGENT_TOKEN" \
-d '{
"items": [
{
"type": "message",
"role": "user",
"content": [
{
"type": "input_text",
"text": "What'\''s the weather in Dar es Salaam, Tanzania?"
}
]
}
]
}'
Salvare l'ID conversazione restituito (conv_xyz...) per il passaggio successivo.
Creare una risposta
Sostituire <CONVERSATION_ID> con l'ID del passaggio precedente.
curl -X POST "$FOUNDRY_PROJECT_ENDPOINT/openai/v1/responses" \
-H "Content-Type: application/json" \
-H "Authorization: Bearer $AGENT_TOKEN" \
-d '{
"agent": {"type": "agent_reference", "name": "<AGENT_NAME>-function-calling"},
"conversation": "<CONVERSATION_ID>",
"input": []
}'
Output previsto
La risposta contiene un elemento di chiamata di funzione che è necessario elaborare:
{
"output": [
{
"type": "function_call",
"call_id": "call_xyz789",
"name": "getCurrentWeather",
"arguments": "{\"location\": \"Dar es Salaam, Tanzania\", \"unit\": \"c\"}"
}
]
}
Dopo aver elaborato la chiamata alla funzione e aver restituito l'output all'agente, la risposta finale include le informazioni meteo in linguaggio naturale.
Inviare l'output delle chiamate di funzione
Dopo aver elaborato la chiamata di funzione in locale, inviare il risultato all'agente:
curl -X POST "$FOUNDRY_PROJECT_ENDPOINT/openai/v1/responses" \
-H "Content-Type: application/json" \
-H "Authorization: Bearer $AGENT_TOKEN" \
-d '{
"agent": {"type": "agent_reference", "name": "<AGENT_NAME>-function-calling"},
"conversation": "<CONVERSATION_ID>",
"input": [
{
"type": "function_call_output",
"call_id": "<CALL_ID>",
"output": "{\"temperature\": \"30\", \"unit\": \"c\", \"description\": \"Sunny\"}"
}
]
}'
Sostituire <CALL_ID> con il call_id valore della chiamata di funzione nella risposta precedente. L'agente usa l'output della funzione per generare una risposta in linguaggio naturale.
Usare l'esempio di codice seguente per creare un agente con strumenti per le funzioni, gestire le chiamate di funzione dal modello e fornire i risultati della funzione per ottenere la risposta finale.
import { DefaultAzureCredential } from "@azure/identity";
import { AIProjectClient } from "@azure/ai-projects";
// Format: "https://resource_name.ai.azure.com/api/projects/project_name"
const projectEndpoint = "your_project_endpoint";
/**
* Define a function tool for the model to use
*/
const funcTool = {
type: "function" as const,
name: "get_horoscope",
description: "Get today's horoscope for an astrological sign.",
strict: true,
parameters: {
type: "object",
properties: {
sign: {
type: "string",
description: "An astrological sign like Taurus or Aquarius",
},
},
required: ["sign"],
additionalProperties: false,
},
};
/**
* Generate a horoscope for the given astrological sign.
*/
function getHoroscope(sign: string): string {
return `${sign}: Next Tuesday you will befriend a baby otter.`;
}
export async function main(): Promise<void> {
// Create AI Project client
const project = new AIProjectClient(projectEndpoint, new DefaultAzureCredential());
const openai = project.getOpenAIClient();
// Create a conversation for multi-turn interaction
const conversation = await openai.conversations.create();
// Create agent with function tools
const agent = await project.agents.createVersion("function-tool-agent", {
kind: "prompt",
model: "gpt-4.1-mini",
instructions: "You are a helpful assistant that can use function tools.",
tools: [funcTool],
});
// Prompt the model with tools defined
const response = await openai.responses.create(
{
input: [
{
type: "message",
role: "user",
content: "What is my horoscope? I am an Aquarius.",
},
],
conversation: conversation.id,
},
{
body: { agent: { name: agent.name, type: "agent_reference" } },
},
);
console.log(`Response output: ${response.output_text}`);
// Process function calls
const inputList: Array<{
type: "function_call_output";
call_id: string;
output: string;
}> = [];
for (const item of response.output) {
if (item.type === "function_call") {
if (item.name === "get_horoscope") {
// Parse the function arguments
const args = JSON.parse(item.arguments);
// Execute the function logic for get_horoscope
const horoscope = getHoroscope(args.sign);
// Provide function call results to the model
inputList.push({
type: "function_call_output",
call_id: item.call_id,
output: JSON.stringify({ horoscope }),
});
}
}
}
// Submit function results to get final response
const finalResponse = await openai.responses.create(
{
input: inputList,
conversation: conversation.id,
},
{
body: { agent: { name: agent.name, type: "agent_reference" } },
},
);
// Print the final response
console.log(finalResponse.output_text);
// Clean up
await project.agents.deleteVersion(agent.name, agent.version);
await openai.conversations.delete(conversation.id);
}
main().catch((err) => {
console.error("The sample encountered an error:", err);
});
Output previsto
L'esempio seguente mostra l'output previsto:
Response output:
Your horoscope for Aquarius: Next Tuesday you will befriend a baby otter.
Usare la chiamata di funzione in un agente Java
Configurare
Aggiungi la dipendenza a pom.xml:
<dependency>
<groupId>com.azure</groupId>
<artifactId>azure-ai-agents</artifactId>
<version>2.0.0</version>
</dependency>
Creare un agente con gli strumenti per le funzioni
import com.azure.ai.agents.AgentsClient;
import com.azure.ai.agents.AgentsClientBuilder;
import com.azure.ai.agents.ResponsesClient;
import com.azure.ai.agents.models.AgentReference;
import com.azure.ai.agents.models.AgentVersionDetails;
import com.azure.ai.agents.models.AzureCreateResponseOptions;
import com.azure.ai.agents.models.FunctionTool;
import com.azure.ai.agents.models.PromptAgentDefinition;
import com.azure.core.util.BinaryData;
import com.azure.identity.DefaultAzureCredentialBuilder;
import com.openai.models.responses.Response;
import com.openai.models.responses.ResponseCreateParams;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
public class FunctionCallingExample {
// Format: "https://resource_name.ai.azure.com/api/projects/project_name"
private static final String PROJECT_ENDPOINT = "your_project_endpoint";
public static void main(String[] args) {
AgentsClientBuilder builder = new AgentsClientBuilder()
.credential(new DefaultAzureCredentialBuilder().build())
.endpoint(PROJECT_ENDPOINT);
AgentsClient agentsClient = builder.buildAgentsClient();
ResponsesClient responsesClient = builder.buildResponsesClient();
// Define function parameters
Map<String, BinaryData> parameters = new HashMap<>();
parameters.put("type", BinaryData.fromString("\"object\""));
parameters.put("properties", BinaryData.fromString(
"{\"location\":{\"type\":\"string\",\"description\":\"The city and state, e.g. Seattle, WA\"},"
+ "\"unit\":{\"type\":\"string\",\"enum\":[\"celsius\",\"fahrenheit\"]}}"));
parameters.put("required", BinaryData.fromString("[\"location\"]"));
FunctionTool weatherFunction = new FunctionTool("get_weather", parameters, true);
// Create agent with function tool
PromptAgentDefinition agentDefinition = new PromptAgentDefinition("gpt-4.1-mini")
.setInstructions("You are a weather assistant. Use the get_weather function to retrieve weather information.")
.setTools(Arrays.asList(weatherFunction));
AgentVersionDetails agent = agentsClient.createAgentVersion("function-calling-agent", agentDefinition);
System.out.printf("Agent created: %s (version %s)%n", agent.getName(), agent.getVersion());
// Create a response - the agent will call the function
AgentReference agentReference = new AgentReference(agent.getName())
.setVersion(agent.getVersion());
Response response = responsesClient.createAzureResponse(
new AzureCreateResponseOptions().setAgentReference(agentReference),
ResponseCreateParams.builder()
.input("What is the weather in Seattle?"));
System.out.println("Response: " + response.output());
// Clean up
agentsClient.deleteAgentVersion(agent.getName(), agent.getVersion());
}
}
Per il ciclo completo di chiamata delle funzioni che gestisce la chiamata dello strumento e invia i risultati all'agente, vedere gli esempi del Java SDK di Azure AI Agents.
Verificare il funzionamento delle chiamate di funzione
Usare questi controlli per verificare che la chiamata di funzione funzioni:
- La prima risposta contiene un elemento di output con
typeimpostato sufunction_call. - L'app esegue la funzione richiesta usando gli argomenti restituiti.
- L'app invia una risposta di completamento che include un
function_call_outputelemento e fa riferimento alla risposta precedente e l'agente restituisce una risposta in linguaggio naturale.
Se si usa la traccia in Microsoft Foundry, verificare che sia avvenuta la chiamata allo strumento. Per indicazioni sulla convalida dell'invocazione degli strumenti e sul controllo sull'uso degli strumenti, vedere le migliori pratiche per l'uso degli strumenti in Microsoft Foundry Agent Service.
Considerazioni sulla sicurezza e i dati
- Considerare gli argomenti degli strumenti e gli output degli strumenti come input non attendibili. Convalidare e purificare i valori prima di usarli.
- Non passare segreti (chiavi API, token, stringhe di connessione) nell'output dello strumento. Restituisce solo i dati necessari per il modello.
- Applicare privilegi minimi all'identità usata da
DefaultAzureCredential. - Evitare effetti collaterali a meno che non si intenda esplicitamente. Ad esempio, limitare gli strumenti di funzione alle operazioni sicure o richiedere una conferma esplicita dell'utente per le azioni che modificano i dati.
- Per le operazioni a esecuzione prolungata, restituire immediatamente uno stato ed eseguire il polling. La scadenza di 10 minuti si applica al tempo totale trascorso, non al tempo di esecuzione delle singole funzioni.
Risoluzione dei problemi
| Problema | Probabile causa | Risoluzione |
|---|---|---|
| L'agente risponde con una chiamata di funzione ma non fornisce una risposta definitiva. | L'output dello strumento non è stato restituito al modello. | Eseguire la funzione, quindi chiamare responses.create con l'output dello strumento e l'ID conversation per continuare. |
| Non viene eseguita alcuna chiamata di funzione. | Funzione non presente nella definizione dell'agente o denominazione errata. | Verificare che lo strumento di funzione sia stato aggiunto all'agente. Usare nomi e descrizioni dei parametri chiari e descrittivi. |
| Gli argomenti non sono JSON validi. | Disallineamento dello schema o informazioni errate generate dal modello. | Verificare che lo schema JSON usi i tipi corretti e le proprietà necessarie. Gestisci gli errori di analisi in modo elegante nell'app. |
| Campi obbligatori mancanti. | Lo schema non applica le proprietà obbligatorie. | Aggiungere "required": [...] una matrice allo schema dei parametri. Impostare strict: true per la convalida più restrittiva. |
| Gli output degli strumenti falliscono a causa della scadenza. | Esecuzione scaduta (limite di 10 minuti). | Restituisce tempestivamente gli output degli strumenti. Per le operazioni lente, restituire uno stato ed eseguire il polling separatamente. |
| Funzione chiamata con parametri errati. | Descrizione della funzione ambigua. | Migliorare il campo della funzione description . Aggiungere descrizioni dettagliate dei parametri con esempi. |
| Molteplici chiamate di funzione in una singola risposta. | Il modello ha determinato più funzioni necessarie. | Gestisci ciascuna chiamata di funzione nell'array di output. Restituisce tutti i risultati in una singola responses.create chiamata. |
| Funzione non visibile nel portale Foundry. | Il portale non esegue chiamate di funzione. | Testare la chiamata di una funzione tramite SDK o API REST. Il portale mostra gli agenti, ma non richiama le funzioni. |
Pulire le risorse
Al termine del test, eliminare le risorse create per evitare costi continui.
Eliminare l'agente:
curl -X DELETE "$FOUNDRY_PROJECT_ENDPOINT/agents/<AGENT_NAME>-function-calling?api-version=v1" \
-H "Authorization: Bearer $AGENT_TOKEN"
Eliminare la conversazione:
curl -X DELETE "$FOUNDRY_PROJECT_ENDPOINT/openai/v1/conversations/<CONVERSATION_ID>" \
-H "Authorization: Bearer $AGENT_TOKEN"
Contenuto correlato
- Migliori pratiche per l'uso degli strumenti nel servizio agente Foundry di Microsoft
- Connettere gli strumenti OpenAPI agli agenti Foundry Microsoft
- guida introduttiva Microsoft Foundry