Poznámka:
Přístup k této stránce vyžaduje autorizaci. Můžete se zkusit přihlásit nebo změnit adresáře.
Přístup k této stránce vyžaduje autorizaci. Můžete zkusit změnit adresáře.
Microsoft agenti Foundry podporují volání funkcí, což umožňuje rozšířit agenty o vlastní možnosti. Definujte funkci s jejím názvem, parametry a popisem, a model Foundry agenta může vaši aplikaci požádat, aby ji zavolala. Aplikace spustí funkci a vrátí výstup. Agent pak pomocí výsledku pokračuje v konverzaci s přesnými daty v reálném čase z vašich systémů.
Důležité
Běhy vyprší 10 minut po vytvoření. Odešlete výstupy nástroje před vypršením jejich platnosti.
Agenty můžete spouštět pomocí nástrojů funkcí na portálu Microsoft Foundry. Portál ale nepodporuje přidávání, odebírání nebo aktualizaci definic funkcí v agentovi. Ke konfiguraci nástrojů funkcí použijte sadu SDK nebo rozhraní REST API.
Podpora využití
Následující tabulka ukazuje podporu sady SDK a nastavení.
| podpora Microsoft Foundry | Python SDK | C# SDK | JavaScript SDK | Java SDK | REST API | Základní nastavení agenta | Nastavení standardního agenta |
|---|---|---|---|---|---|---|---|
| ✔️ | ✔️ | ✔️ | ✔️ | ✔️ | ✔️ | ✔️ | ✔️ |
Požadavky
Než začnete, ujistěte se, že máte:
Projekt Foundry a nasazený model
Balíček SDK pro váš jazyk:
- Python:
azure-ai-projects(nejnovější) - .NET:
Azure.AI.Extensions.OpenAI - TypeScript:
@azure/ai-projects(nejnovější) - Java:
azure-ai-agents
Postup instalace a ověřování najdete v rychlém startu.
- Python:
Tip
Pokud používáte DefaultAzureCredential, přihlaste se pomocí az login před spuštěním ukázek.
Vytvoření agenta pomocí nástrojů funkcí
Volání funkce se řídí tímto vzorem:
- Definovat nástroje funkcí – Popište název, parametry a účel jednotlivých funkcí.
- Vytvořte agenta – zaregistrujte agenta s definicemi funkce.
- Odeslat výzvu – Agent analyzuje výzvu a v případě potřeby požaduje volání funkcí.
- Spusťte a vraťte – Aplikace spustí funkci a odešle výstup zpět do agenta.
- Získejte konečnou odpověď – Agent k dokončení odpovědi použije výstup funkce.
Pomocí následující ukázky kódu můžete vytvořit agenta, zpracovat volání funkce a vrátit výstup nástroje zpět do agenta. Vyberte Prompt Agents, chcete-li použít SDK Azure AI Projects k vytvoření serverového agenta promptů, nebo Hosted Agents, chcete-li použít Agent Framework FoundryChatClient k vytvoření dočasného agenta v rámci procesu.
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)
Očekávaný výstup
Následující příklad ukazuje očekávaný výstup:
Agent response: Your horoscope for Aquarius: Next Tuesday you will befriend a baby otter.
Použití agentů s příkladem funkcí
V tomto příkladu použijete místní funkce s agenty. Pomocí funkcí dejte agentovi konkrétní informace v reakci na otázku uživatele. Vyberte Prompt Agents, chcete-li pomocí sady Azure AI Projects SDK vytvořit serverového agenta pro prompty, nebo Hosted Agents, chcete-li pomocí Microsoft Agent Framework vytvořit dočasného agenta v procesu.
Kód v tomto příkladu je synchronní. Asynchronní příklad najdete v ukázkovém kódu sample v úložišti Azure SDK pro .NET na GitHubu.
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);
}
}
Očekávaný výstup
Následující příklad ukazuje očekávaný výstup:
Calling getUserFavoriteCity...
Calling getCityNickname...
Calling getCurrentWeatherAtLocation...
Your favorite city, Seattle, WA, is also known as The Emerald City. The current weather there is 70f.
Existují dva způsoby, jak použít volání funkcí ve službě agenta Foundry.
- Vytvoření souboru
response. Pokud potřebujete, aby agent znovu vykonával funkce, vytvořte dalšíresponse. - Vytvořte
conversation, poté vytvořte více konverzačních položek. Každá položka konverzace odpovídá jedné položceresponse.
Před spuštěním příkladů nastavte následující proměnné prostředí:
export AGENT_TOKEN=$(az account get-access-token --scope "https://ai.azure.com/.default" --query accessToken -o tsv)
Definujte funkci, kterou může váš agent volat
Začněte definováním funkce, kterou má agent volat. Když vytvoříte funkci pro volání agenta, popište její strukturu a všechny požadované parametry v docstringu. Například funkce najdete v dalších jazycích sady SDK.
Vytvoření agenta
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"]
}
}
]
}
}'
Vytvoření konverzace
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?"
}
]
}
]
}'
Uložte vrácené ID konverzace (conv_xyz...) pro další krok.
Vytvoření odpovědi
Nahraďte <CONVERSATION_ID> IDčkem z předchozího kroku.
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": []
}'
Očekávaný výstup
Odpověď obsahuje položku volání funkce, kterou potřebujete zpracovat:
{
"output": [
{
"type": "function_call",
"call_id": "call_xyz789",
"name": "getCurrentWeather",
"arguments": "{\"location\": \"Dar es Salaam, Tanzania\", \"unit\": \"c\"}"
}
]
}
Po zpracování volání funkce a předání výstupu zpět agentovi obsahuje konečná odpověď informace o počasí v přirozeném jazyce.
Odeslání výstupu volání funkce
Po místním zpracování volání funkce odešlete výsledek zpět do agenta:
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\"}"
}
]
}'
<CALL_ID> Nahraďte call_id hodnotou z volání funkce v předchozí odpovědi. Agent používá výstup funkce k vygenerování odpovědi v přirozeném jazyce.
Následující ukázka kódu slouží k vytvoření agenta s nástroji funkcí, zpracování volání funkcí z modelu a poskytnutí výsledků funkce pro získání konečné odpovědi.
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);
});
Očekávaný výstup
Následující příklad ukazuje očekávaný výstup:
Response output:
Your horoscope for Aquarius: Next Tuesday you will befriend a baby otter.
Použití volání funkce v agentu Java
Nastavit
Přidejte závislost do svého pom.xml:
<dependency>
<groupId>com.azure</groupId>
<artifactId>azure-ai-agents</artifactId>
<version>2.2.0</version>
</dependency>
Vytvoření agenta pomocí nástrojů funkcí
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());
}
}
Kompletní smyčku volání funkce, která zajišťuje volání nástroje a odeslání výsledků zpět agentovi, najdete v ukázkách Azure AI Agents Java SDK.
Ověřit, že volání funkcí funguje
Pomocí těchto kontrol ověřte, že volání funkce funguje:
- První odpověď obsahuje výstupní položku s položkou
typenastavenou na hodnotufunction_call. - Aplikace spustí požadovanou funkci pomocí vrácených argumentů.
- Aplikace odešle následnou odpověď, která obsahuje
function_call_outputpoložku a odkazuje na předchozí odpověď, a agent vrátí odpověď v přirozeném jazyce.
Pokud používáte trasování v Microsoft Foundry, potvrďte, že došlo k vyvolání nástroje. Pokyny k ověřování vyvolání nástrojů a řízení využití nástrojů najdete v tématu Nejlepší postupy pro používání nástrojů ve službě Microsoft Foundry Agent Service.
Aspekty zabezpečení a dat
- Považovat argumenty nástroje a výstupy nástroje za nedůvěryhodný vstup Před použitím hodnot ověřte a sanitujte je.
- Ve výstupu nástroje nepředávejte tajné kódy (klíče rozhraní API, tokeny, připojovací řetězce). Vrátí jenom data, která model potřebuje.
- Použití nejnižších oprávnění na identitu používanou uživatelem
DefaultAzureCredential. - Vyhněte se vedlejším účinkům, pokud je explicitně nechystáte. Omezte například nástroje funkcí na bezpečné operace nebo u akcí, které mění data, vyžadují explicitní potvrzení uživatele.
- V případě dlouhotrvajících operací okamžitě vraťte stav a implementujte dotazování. Platnost 10minutového spuštění se vztahuje na celkový uplynulý čas, ne na provádění jednotlivých funkcí.
Řešení potíží
| Problém | Pravděpodobná příčina | Rozlišení |
|---|---|---|
| Agent provádí volání funkce, ale nedává žádnou konečnou odpověď. | Výstup z nástroje nebyl vrácen do modelu. | Spusťte funkci, poté zavolejte responses.create s výstupem nástroje a ID conversation pro pokračování. |
| K volání funkce nedojde. | Funkce není v definici agenta nebo je špatně pojmenována. | Ověřte, že je funkční nástroj přidán k agentovi. Používejte jasné, popisné názvy a popisy parametrů. |
| Argumenty nejsou platným JSON. | Neshoda schématu nebo model generovaly nesprávné informace. | Ověřte, že schéma JSON používá správné typy a požadované vlastnosti. Zpracujte chyby při parsování elegantně ve své aplikaci. |
| Chybí požadovaná pole. | Schéma nevynucuje požadované vlastnosti. | Přidejte "required": [...] pole do schématu parametrů. Nastavte strict: true pro přísnější ověřování. |
| Výstupy nástrojů selžou kvůli vypršení platnosti. | Časový limit vypršel (limit 10 minut). | Okamžitě vrátí výstupy nástroje. V případě pomalých operací vraťte stav a dotazování zvlášť. |
| Funkce byla volána s nesprávnými parametry. | Popis nejednoznačné funkce | Vylepšete pole funkce description . Přidejte podrobné popisy parametrů s příklady. |
| Více volání funkcí v jedné odpovědi. | Model určil více potřebných funkcí. | Zpracujte každé volání funkce ve výstupním poli. Vraťte všechny výsledky v jednom responses.create volání. |
| Funkce není viditelná na portálu Foundry. | Portál neprovádí volání funkcí. | Testování volání funkcí prostřednictvím sady SDK nebo rozhraní REST API Portál zobrazuje agenty, ale nevyvolává funkce. |
Vyčištění prostředků
Po dokončení testování odstraňte vytvořené prostředky, abyste se vyhnuli průběžným nákladům.
Odstraňte agenta:
curl -X DELETE "$FOUNDRY_PROJECT_ENDPOINT/agents/<AGENT_NAME>-function-calling?api-version=v1" \
-H "Authorization: Bearer $AGENT_TOKEN"
Odstraňte konverzaci:
curl -X DELETE "$FOUNDRY_PROJECT_ENDPOINT/openai/v1/conversations/<CONVERSATION_ID>" \
-H "Authorization: Bearer $AGENT_TOKEN"
Související obsah
- Nejlepší postupy pro používání nástrojů ve službě Microsoft Foundry Agent
- Připojení nástrojů OpenAPI k Microsoft agentům Foundry
- Microsoft Foundry – rychlý start