Penggunaan pemanggilan fungsi dengan agen Microsoft Foundry

Microsoft Foundry mendukung panggilan fungsi, yang memungkinkan Anda memperluas agen dengan kemampuan yang dikustomisasi. Tentukan fungsi dengan nama, parameter, dan deskripsinya, dan agen model Foundry dapat meminta aplikasi Anda untuk memanggil fungsi tersebut. Aplikasi Anda menjalankan fungsi dan mengembalikan output. Agen kemudian menggunakan hasilnya untuk melanjutkan percakapan dengan data real-time yang akurat dari sistem Anda.

Penting

Pengoperasian berakhir 10 menit setelah pembuatan. Kirim output alat Anda sebelum kedaluwarsa.

Anda dapat menjalankan agen dengan alat fungsi di portal Microsoft Foundry. Namun, portal tidak mendukung penambahan, penghapusan, atau pembaruan definisi fungsi pada agen. Gunakan SDK atau REST API untuk mengonfigurasi alat fungsi.

Dukungan penggunaan

Tabel berikut ini memperlihatkan SDK dan dukungan penyiapan.

dukungan Microsoft Foundry Python SDK C# SDK JavaScript SDK Java SDK REST API Penyiapan agen dasar Penyiapan agen standar
✔️ ✔️ ✔️ ✔️ ✔️ ✔️ ✔️ ✔️

Prasyarat

Sebelum memulai, pastikan Anda memiliki:

  • Lingkungan agen dasar atau standar.

  • Proyek Foundry dan model yang disebarkan.

  • Paket SDK untuk bahasa Anda:

    • Python: azure-ai-projects (terbaru)
    • .NET: Azure.AI.Extensions.OpenAI
    • TypeScript: @azure/ai-projects (terbaru)
    • Java: azure-ai-agents

    Untuk langkah-langkah penginstalan dan autentikasi, lihat mulai cepat.

Tips

Jika Anda menggunakan DefaultAzureCredential, masuk dengan menggunakan az login sebelum menjalankan sampel.

Membuat agen dengan alat fungsi

Pemanggilan fungsi mengikuti pola ini:

  1. Tentukan alat fungsi — Menjelaskan nama, parameter, dan tujuan setiap fungsi.
  2. Buat agen — Daftarkan agen dengan definisi fungsi Anda.
  3. Kirim permintaan — Agen menganalisis perintah dan meminta panggilan fungsi jika diperlukan.
  4. Jalankan dan kembalikan — Aplikasi Anda menjalankan fungsi dan mengirimkan output kembali ke agen.
  5. Dapatkan respons akhir — Agen menggunakan output fungsi Anda untuk menyelesaikan responsnya.

Gunakan sampel kode berikut untuk membuat agen, menangani panggilan fungsi, dan mengembalikan output alat kembali ke agen.

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 yang diharapkan

Contoh berikut menunjukkan output yang diharapkan:

Agent response: Your horoscope for Aquarius: Next Tuesday you will befriend a baby otter.

Menggunakan agen dengan contoh fungsi

Dalam contoh ini, Anda menggunakan fungsi lokal beserta agen. Gunakan fungsi untuk memberikan informasi spesifik Agen sebagai respons atas pertanyaan pengguna. Kode dalam contoh ini sinkron. Untuk contoh asinkron, lihat contoh kode sample di Azure SDK untuk repositori .NET di 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 yang diharapkan

Contoh berikut menunjukkan output yang diharapkan:

Calling getUserFavoriteCity...
Calling getCityNickname...
Calling getCurrentWeatherAtLocation...
Your favorite city, Seattle, WA, is also known as The Emerald City. The current weather there is 70f.

Ada dua cara untuk menggunakan panggilan fungsi di Foundry Agent Service.

  1. Buat response. Ketika Anda memerlukan agen untuk memanggil fungsi lagi, buat agen lain response.
  2. Buat conversation, lalu buat beberapa item percakapan. Setiap item percakapan sesuai dengan satu response.

Atur variabel lingkungan berikut sebelum menjalankan contoh:

export AGENT_TOKEN=$(az account get-access-token --scope "https://ai.azure.com/.default" --query accessToken -o tsv)

Definisikan fungsi untuk dipanggil agen Anda

Mulailah dengan menentukan fungsi untuk dipanggil agen Anda. Saat Anda membuat fungsi untuk dipanggil agen, jelaskan strukturnya dan parameter yang diperlukan dalam docstring. Misalnya fungsi, lihat bahasa SDK lainnya.

Membuat agen

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"]
          }
        }
      ]
    }
  }'

Membuat percakapan

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?"
          }
        ]
      }
    ]
  }'

Simpan ID percakapan yang dikembalikan (conv_xyz...) untuk langkah berikutnya.

Membuat respons

Ganti <CONVERSATION_ID> dengan ID dari langkah sebelumnya.

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 yang diharapkan

Respons berisi item panggilan fungsi yang perlu Anda proses:

{
  "output": [
    {
      "type": "function_call",
      "call_id": "call_xyz789",
      "name": "getCurrentWeather",
      "arguments": "{\"location\": \"Dar es Salaam, Tanzania\", \"unit\": \"c\"}"
    }
  ]
}

Setelah Anda memproses panggilan fungsi dan memberikan output kembali ke agen, respons akhir mencakup informasi cuaca dalam bahasa alami.

Kirim output panggilan fungsi

Setelah memproses panggilan fungsi secara lokal, kirimkan hasilnya kembali ke agen:

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\"}"
      }
    ]
  }'

Ganti <CALL_ID> dengan call_id nilai dari panggilan fungsi di respons sebelumnya. Agen menggunakan output fungsi untuk menghasilkan jawaban bahasa alami.

Gunakan sampel kode berikut untuk membuat agen dengan alat fungsi, menangani panggilan fungsi dari model, dan memberikan hasil fungsi untuk mendapatkan respons akhir.

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 yang diharapkan

Contoh berikut menunjukkan output yang diharapkan:

Response output: 
Your horoscope for Aquarius: Next Tuesday you will befriend a baby otter.

Penggunaan pemanggilan fungsi dalam agen Java

Konfigurasi

Tambahkan dependensi ke pom.xml:

<dependency>
    <groupId>com.azure</groupId>
    <artifactId>azure-ai-agents</artifactId>
    <version>2.0.0</version>
</dependency>

Membuat agen dengan alat fungsi

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());
    }
}

Untuk perulangan pemanggilan fungsi lengkap untuk menangani pemanggilan alat dan mengembalikan hasil kepada agen, lihat sampel SDK Java Azure AI Agents.

Memverifikasi apakah panggilan fungsi berfungsi

Gunakan pemeriksaan ini untuk memverifikasi bahwa panggilan fungsi beroperasi dengan baik.

  1. Respons pertama Anda berisi item output dengan type diatur ke function_call.
  2. Aplikasi Anda menjalankan fungsi yang diminta dengan menggunakan argumen yang dikembalikan.
  3. Aplikasi Anda mengirimkan respons tindak lanjut yang menyertakan function_call_output item dan mereferensikan respons sebelumnya, dan agen mengembalikan jawaban bahasa alami.

Jika Anda menggunakan pelacakan di Microsoft Foundry, konfirmasikan bahwa pemanggilan alat telah dilakukan. Untuk panduan tentang memvalidasi pemanggilan alat dan pengendalian penggunaan alat, lihat praktik terbaik untuk menggunakan alat di Microsoft Foundry Agent Service.

Pertimbangan keamanan dan data

  • Perlakukan argumen alat dan output alat sebagai input yang tidak tepercaya. Validasi dan sanitasi nilai sebelum menggunakannya.
  • Jangan meneruskan rahasia (kunci API, token, string koneksi) dalam output alat. Mengembalikan hanya data yang dibutuhkan model.
  • Terapkan hak istimewa paling sedikit ke identitas yang digunakan oleh DefaultAzureCredential.
  • Hindari efek samping kecuali Anda secara eksplisit menginginkannya. Misalnya, batasi alat fungsi untuk operasi yang aman, atau memerlukan konfirmasi pengguna eksplisit untuk tindakan yang mengubah data.
  • Untuk operasi yang berlangsung lama, segera kembalikan status dan terapkan mekanisme polling untuk memantau perkembangannya. Kedaluwarsa batas waktu 10 menit berlaku untuk total waktu yang berlalu, bukan eksekusi fungsi individual.

Pemecahan masalah

Masalah Kemungkinan penyebabnya Resolusi
Agen mengembalikan panggilan fungsi tetapi tidak memberikan jawaban definitif. Output alat tidak dikembalikan ke model. Jalankan fungsi, lalu panggil responses.create dengan output alat dan conversation ID untuk melanjutkan.
Tidak ada panggilan fungsi yang terjadi. Fungsi tidak termasuk dalam definisi agen atau penamaan yang kurang tepat. Konfirmasikan bahwa alat fungsi ditambahkan ke agent. Gunakan nama dan deskripsi parameter yang jelas dan deskriptif.
Argumen bukan JSON yang valid. Ketidakcocokan skema atau model menghasilkan informasi yang salah. Verifikasi skema JSON menggunakan jenis yang benar dan properti yang diperlukan. Tangani kesalahan penguraian dengan efisien di aplikasi Anda.
Kolom yang diperlukan tidak ada. Skema tidak mengharuskan properti wajib. Tambahkan "required": [...] array ke skema parameter Anda. Atur strict: true untuk validasi yang lebih ketat.
Keluaran alat gagal karena kedaluwarsa. Jalur telah kedaluwarsa (batas waktu 10 menit). Kembalikan keluaran perangkat segera. Untuk operasi yang lambat, kembalikan status dan lakukan pemeriksaan secara terpisah.
Fungsi yang dipanggil dengan parameter yang salah. Deskripsi fungsi ambigu. Tingkatkan bidang fungsi description . Tambahkan deskripsi parameter terperinci dengan contoh.
Beberapa panggilan fungsi dalam satu respons. Model menentukan beberapa fungsi yang diperlukan. Tangani setiap panggilan fungsi dalam array output. Mengembalikan semua hasil dalam satu responses.create panggilan.
Fungsi tidak terlihat di portal Foundry. Portal tidak menjalankan panggilan fungsi. Menguji panggilan fungsi melalui SDK atau REST API. Portal menunjukkan agen tetapi tidak memanggil fungsi.

Membersihkan sumber daya

Setelah selesai menguji, hapus sumber daya yang Anda buat untuk menghindari biaya yang sedang berlangsung.

Hapus agen:

curl -X DELETE "$FOUNDRY_PROJECT_ENDPOINT/agents/<AGENT_NAME>-function-calling?api-version=v1" \
  -H "Authorization: Bearer $AGENT_TOKEN"

Hapus percakapan:

curl -X DELETE "$FOUNDRY_PROJECT_ENDPOINT/openai/v1/conversations/<CONVERSATION_ID>" \
  -H "Authorization: Bearer $AGENT_TOKEN"