Примечание.
Для доступа к этой странице требуется авторизация. Вы можете попробовать войти или изменить каталоги.
Для доступа к этой странице требуется авторизация. Вы можете попробовать изменить каталоги.
Агенты Microsoft Foundry поддерживают вызов функций, что позволяет расширить агентов пользовательскими возможностями. Определите функцию с её именем, параметрами и описанием, и модель Foundry агента может запросить вашему приложению вызвать её. Приложение выполняет функцию и возвращает выходные данные. Затем агент использует результат для продолжения беседы с точными данными в режиме реального времени из ваших систем.
Важно
Период действия запуска истекает через 10 минут после создания. Отправьте результаты работы средства до истечения их срока действия.
Агенты можно запускать с помощью средств функций на портале Microsoft Foundry. Однако портал не поддерживает добавление, удаление или обновление определений функций в агенте. Используйте пакет SDK или REST API для настройки средств функций.
Поддержка использования
В следующей таблице показана поддержка пакета SDK и настройки.
| поддержка Microsoft Foundry | пакет SDK Python | Пакет SDK для C# | Пакет SDK для JavaScript | пакет SDK Java | REST API | Базовая настройка агента | Настройка стандартного агента |
|---|---|---|---|---|---|---|---|
| ✔️ | ✔️ | ✔️ | ✔️ | ✔️ | ✔️ | ✔️ | ✔️ |
Необходимые условия
Прежде чем начать, убедитесь, что у вас есть:
Проект Foundry и развернутая модель.
Пакет ПАКЕТА SDK для вашего языка:
- Python:
azure-ai-projects(последняя версия) - .NET:
Azure.AI.Extensions.OpenAI - TypeScript:
@azure/ai-projects(последняя версия) - Java:
azure-ai-agents
Инструкции по установке и проверке подлинности см. в кратком руководстве.
- Python:
Совет
При использовании DefaultAzureCredential войдите в систему az login перед выполнением примеров.
Создание агента с инструментами функций
Вызов функции следует этому шаблону:
- Определение средств функции — описание имени, параметров и назначения каждой функции.
- Создайте агент — зарегистрируйте агент с помощью определений функций.
- Отправка запроса — агент анализирует запрос и при необходимости запрашивает вызовы функций.
- Выполнение и возврат — приложение запускает функцию и отправляет выходные данные обратно агенту.
- Получите окончательный ответ . Агент использует выходные данные функции для завершения ответа.
Используйте следующий пример кода для создания агента, обработки вызова функции и возврата выходных данных средства обратно в агент. Выберите Prompt Agents, чтобы использовать пакет SDK Azure AI Projects для создания серверного агента для промптов, или Hosted Agents, чтобы использовать Agent Framework FoundryChatClient для создания временного внутрипроцессного агента.
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)
Ожидаемые выходные данные
В следующем примере показаны ожидаемые выходные данные:
Agent response: Your horoscope for Aquarius: Next Tuesday you will befriend a baby otter.
Пример использования агентов с функциями
В этом примере используются локальные функции с агентами. Используйте функции для предоставления определенной информации агенту в ответ на вопрос пользователя. Выберите Prompt Agents, чтобы с помощью пакета SDK Azure AI Projects создать серверный агент с подсказками, либо Hosted Agents, чтобы с помощью Microsoft Agent Framework создать эфемерный внутрипроцессный агент.
Код в этом примере синхронный. Пример асинхронного выполнения можно найти в примере кода sample в репозитории Azure SDK для .NET на 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);
}
}
Ожидаемые выходные данные
В следующем примере показаны ожидаемые выходные данные:
Calling getUserFavoriteCity...
Calling getCityNickname...
Calling getCurrentWeatherAtLocation...
Your favorite city, Seattle, WA, is also known as The Emerald City. The current weather there is 70f.
В службе агента Foundry существует два способа вызова функций.
- Создайте
response. Когда агенту снова нужно вызывать функции, создайте другойresponse. - Создайте
conversation, а затем несколько элементов беседы. Каждый элемент беседы соответствует одномуresponseэлементу.
Задайте следующие переменные среды перед выполнением примеров:
export AGENT_TOKEN=$(az account get-access-token --scope "https://ai.azure.com/.default" --query accessToken -o tsv)
Определите функцию, которую должен вызывать ваш агент
Начните с определения функции, которую ваш агент будет вызывать. При создании функции для вызова агента опишите ее структуру и все необходимые параметры в документации. Примеры функций см. на других языках SDK.
Создание агента
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"]
}
}
]
}
}'
Создание беседы
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?"
}
]
}
]
}'
Сохраните возвращенный идентификатор беседы (conv_xyz...) для следующего шага.
Создание ответа
Замените <CONVERSATION_ID> на идентификатор, полученный на предыдущем этапе.
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": [
{
"type": "function_call",
"call_id": "call_xyz789",
"name": "getCurrentWeather",
"arguments": "{\"location\": \"Dar es Salaam, Tanzania\", \"unit\": \"c\"}"
}
]
}
После обработки вызова функции и предоставления выходных данных агенту окончательный ответ включает сведения о погоде на естественном языке.
Отправка выходных данных вызова функции
После локального вызова функции отправьте результат обратно агенту:
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>call_id значением вызова функции в предыдущем ответе. Агент использует выходные данные функции для создания ответа на естественный язык.
Используйте следующий пример кода, чтобы создать агент с инструментами функции, обрабатывать вызовы функций из модели и предоставлять результаты функции для получения окончательного ответа.
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);
});
Ожидаемые выходные данные
В следующем примере показаны ожидаемые выходные данные:
Response output:
Your horoscope for Aquarius: Next Tuesday you will befriend a baby otter.
Использование вызова функции в агенте Java
Настройка
Добавьте зависимость в вашу pom.xml:
<dependency>
<groupId>com.azure</groupId>
<artifactId>azure-ai-agents</artifactId>
<version>2.0.0</version>
</dependency>
Создание агента с инструментами функций
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());
}
}
Для полного цикла вызовов функций, который обрабатывает вызов средства и отправляет результаты обратно агенту, см. в примерах Azure AI Agents Java SDK.
Проверка работы вызовов функций
Используйте эти проверки для подтверждения работы вызовов функций:
- Первый ответ содержит выходной элемент с
typeзаданным значениемfunction_call. - Приложение выполняет запрошенную функцию с помощью возвращаемых аргументов.
- Приложение отправляет следующий ответ, содержащий
function_call_outputэлемент и ссылающийся на предыдущий ответ, и агент возвращает ответ на естественный язык.
Если вы используете трассировку в Microsoft Foundry, подтвердите вызов средства. Рекомендации по проверке использования средства и управления ими см. в статье Best practices for using tools in Microsoft Foundry Agent Service.
Вопросы безопасности и данных
- Обрабатывать аргументы и выходные данные инструментов как ненадежные входные данные. Перед использованием проверяйте и очищайте значения.
- Не передавать секреты (ключи API, маркеры, строки подключения) в выходные данные средства. Возвращает только данные, необходимые модели.
- Примените наименьшие привилегии к удостоверению, используемому
DefaultAzureCredential. - Избегайте побочных эффектов, если вы явно не планируете их. Например, ограничить средства функций безопасными операциями или требовать явного подтверждения пользователей для действий, изменяющих данные.
- Для длительных операций верните статус немедленно и реализуйте опрос состояния. Срок действия 10-минутного ограничения применяется к общему прошедшему времени, а не к индивидуальному выполнению функции.
Устранение неполадок
| Проблема | Вероятно, причина | Разрешение |
|---|---|---|
| Агент возвращает вызов функции, но не возвращает окончательный ответ. | Выходные данные средства не возвращаются в модель. | Выполните функцию, а затем вызовите responses.create с выходными данными средства и идентификатором conversation, чтобы продолжить. |
| Не происходит вызов функции. | Функция либо отсутствует в определении агента, либо имеет плохое наименование. | Убедитесь, что инструмент функции добавлен к агенту. Используйте четкие, описательные имена и описания параметров. |
| Аргументы недопустимы в формате JSON. | Несоответствие схемы или модель сгенерировали неверные сведения. | Убедитесь, что схема JSON использует правильные типы и обязательные свойства. Обрабатывайте ошибки синтаксического анализа в приложении аккуратно. |
| Обязательные поля отсутствуют. | Схема не применяет обязательные свойства. | Добавьте "required": [...] массив в схему параметров. Установите strict: true для более строгой проверки. |
| Выходные данные инструмента приводят к сбоям из-за истечения срока действия. | Истек срок действия (ограничение в 10 минут). | Возвращайте результаты работы инструмента оперативно. Для медленных операций верните состояние и выполняйте опрос отдельно. |
| Функция, вызываемая с неправильными параметрами. | Неоднозначное описание функции. | Улучшение поля функции description . Добавьте подробные описания параметров с примерами. |
| Несколько вызовов функций в одном ответе. | Модель определила несколько необходимых функций. | Обработайте каждый вызов функции в выходном массиве. Возвращает все результаты в одном responses.create вызове. |
| Функция не отображается на портале Foundry. | Портал не выполняет вызовы функций. | Тестирование вызова функции с помощью пакета SDK или REST API. На портале отображаются агенты, но не вызываются функции. |
Очистка ресурсов
После завершения тестирования удалите созданные ресурсы, чтобы избежать текущих затрат.
Удалите агент:
curl -X DELETE "$FOUNDRY_PROJECT_ENDPOINT/agents/<AGENT_NAME>-function-calling?api-version=v1" \
-H "Authorization: Bearer $AGENT_TOKEN"
Удалите беседу:
curl -X DELETE "$FOUNDRY_PROJECT_ENDPOINT/openai/v1/conversations/<CONVERSATION_ID>" \
-H "Authorization: Bearer $AGENT_TOKEN"