Dostosowywanie zachowania agenta w czasie wykonywania przy użyciu ustrukturyzowanych danych wejściowych

Możesz dostosować sposób, w jaki model Foundry agenta przetwarza żądania przy użyciu ustrukturyzowanych danych wejściowych w czasie działania. Dane wejściowe ze strukturą to symbole zastępcze zdefiniowane w agencie przy użyciu składni szablonu paska obsługi ({{variableName}}). W czasie wykonywania podajesz rzeczywiste wartości umożliwiające dynamiczne dostosowywanie instrukcji agenta, konfiguracji zasobów narzędzi i parametrów odpowiedzi — bez tworzenia oddzielnych wersji agentów dla każdej konfiguracji.

Z tego artykułu dowiesz się, jak wykonywać następujące działania:

  • Definiowanie ustrukturyzowanych danych wejściowych w definicji agenta
  • Korzystanie z szablonów paska obsługi w instrukcjach agenta
  • Dynamiczne konfigurowanie zasobów narzędzi, takich jak interpreter kodu i wyszukiwanie plików
  • Przekazywanie ustrukturyzowanych wartości wejściowych podczas wykonywania za pośrednictwem API Responses

Wymagania wstępne

Ważna

Nie przekazuj tajnych danych, tokenów dostępu ani innych danych uwierzytelniających w postaci ustrukturyzowanych danych wejściowych. Dzienniki aplikacji lub trasowanie mogą rejestrować ustrukturyzowane wartości wejściowe jako część żądania. Zamiast tego przechowuj poświadczenia w połączeniach w projekcie lub w innym zarządzanym magazynie sekretów.

Co to są ustrukturyzowane dane wejściowe?

Dane wejściowe ze strukturą używają składni szablonu paska obsługi ({{variableName}}) do tworzenia sparametryzowanych definicji agentów. Należy zdefiniować schematy wejściowe w definicji agenta w obszarze structured_inputs, gdzie każde dane wejściowe ma nazwę, opis, typ i opcjonalną wartość domyślną. Podczas działania dostarcz rzeczywiste wartości w celu zastąpienia symboli zastępczych w szablonie, zanim agent przetworzy żądanie.

Strukturalne dane wejściowe obsługują dwie kategorie nadpisania.

  • Przesłonięcia instrukcji: Parametryzacja instrukcji agenta, instrukcji na poziomie odpowiedzi oraz komunikatów systemowych lub deweloperskich.
  • Nadpisywanie zasobów narzędzia: dynamiczne konfigurowanie parametrów narzędzi w czasie wykonywania, w tym:
    • Identyfikatory magazynów wektorów wyszukiwania plików
    • Identyfikatory i kontenery plików interpretera kodu
    • Adresy URL i nagłówki serwera protokołu MCP (Model Context Protocol)

W przypadku pól tablicowych, takich jak file_ids i vector_store_ids, system automatycznie usuwa puste wartości ciągów w czasie wykonywania. Ta funkcja umożliwia elastyczne liczby danych wejściowych — definiowanie większej liczby miejsc szablonu niż jest to konieczne i pozostawienie nieużywanych pustych miejsc.

Obsługiwane właściwości strukturyzowanego wejścia

W poniższej tabeli wymieniono właściwości definicji agenta, które obsługują szablony paska obsługi:

Kategoria Właściwość Opis
Instrukcje Agenta instructions Tekst instrukcji na poziomie agenta
Instrukcje Odpowiedź instructions Instrukcje przekazane w żądaniu do API odpowiedzi
Instrukcje Komunikat systemu/dewelopera content Zawartość komunikatu w tablicy wejściowej
Wyszukiwanie plików vector_store_ids Tablica identyfikatorów magazynów wektorowych (puste wartości usunięte)
Interpreter kodu container (ciąg) Identyfikator kontenera dla wstępnie skonfigurowanego kontenera
Interpreter kodu container.file_ids (tablica) Identyfikatory plików w kontenerze automatycznym (puste wartości zostały usunięte)
MCP server_label Etykieta serwera MCP
MCP server_url Adres URL punktu końcowego serwera MCP
MCP headers (wartości) Wartości nagłówka HTTP jako pary klucz-wartość
Wyszukiwanie AI platformy Azure filter Wyrażenie filtru OData zastosowane do indeksu wyszukiwania

Używanie ustrukturyzowanych danych wejściowych z instrukcjami agenta

Najprostszym zastosowaniem ustrukturyzowanych danych wejściowych jest sparametryzowanie instrukcji agenta. Zdefiniuj szablony Handlebars w polu instructions i podaj wartości w czasie wykonywania. Takie podejście umożliwia personalizowanie zachowania agenta dla różnych użytkowników lub kontekstów bez tworzenia wielu wersji agentów.

W poniższych przykładach utworzono agenta, którego instrukcje zawierają szczegóły specyficzne dla użytkownika, a następnie podaj te wartości podczas tworzenia odpowiedzi.

from azure.ai.projects import AIProjectClient
from azure.ai.projects.models import PromptAgentDefinition, StructuredInputDefinition
from azure.identity import DefaultAzureCredential

# Format: "https://resource_name.ai.azure.com/api/projects/project_name"
PROJECT_ENDPOINT = "your_project_endpoint"

# Create clients to call Foundry API
project = AIProjectClient(endpoint=PROJECT_ENDPOINT, credential=DefaultAzureCredential())
openai = project.get_openai_client()

# Create agent with handlebar templates in instructions
agent = project.agents.create_version(
    agent_name="structured-input-agent",
    definition=PromptAgentDefinition(
        model="gpt-5-mini",
        instructions=(
            "You are a helpful assistant. "
            "The user's name is {{userName}} and their role is {{userRole}}. "
            "Greet them and confirm their details."
        ),
        structured_inputs={
            "userName": StructuredInputDefinition(
                description="The user's name", required=True, schema={"type": "string"},
            ),
            "userRole": StructuredInputDefinition(
                description="The user's role", required=True, schema={"type": "string"},
            ),
        },
    ),
)
print(f"Agent created: {agent.name}, version: {agent.version}")

# Create conversation and send request with runtime values
conversation = openai.conversations.create()
response = openai.responses.create(
    conversation=conversation.id,
    input="Hello! Can you confirm my details?",
    extra_body={
        "agent_reference": {"name": agent.name, "type": "agent_reference"},
        "structured_inputs": {"userName": "Alice Smith", "userRole": "Senior Developer"},
    },
)
print(response.output_text)

Oczekiwane dane wyjściowe

Agent created: structured-input-agent, version: 1
Hello Alice Smith! I can confirm your details: your name is Alice Smith and your role is Senior Developer. How can I help you today?

Agent zastępuje symbole zastępcze {{userName}} i {{userRole}} w instrukcjach za pomocą "Alice Smith" i "Starszy deweloper" przed zrealizowaniem żądania.

using System;
using Azure.AI.Projects;
using Azure.AI.Projects.Agents;
using Azure.AI.Extensions.OpenAI;
using Azure.Identity;
using OpenAI.Responses;

// Format: "https://resource_name.ai.azure.com/api/projects/project_name"
var projectEndpoint = "your_project_endpoint";

// Create project client to call Foundry API
AIProjectClient projectClient = new(
    endpoint: new Uri(projectEndpoint),
    tokenProvider: new DefaultAzureCredential());

// Create agent with handlebar templates in instructions
DeclarativeAgentDefinition agentDefinition = new(model: "gpt-5-mini")
{
    Instructions = "You are a helpful assistant. "
        + "The user's name is {{userName}} and their role is {{userRole}}. "
        + "Greet them and confirm their details.",
    StructuredInputs =
    {
        ["userName"] = new StructuredInputDefinition
            { Description = "The user's name", IsRequired = true },
        ["userRole"] = new StructuredInputDefinition
            { Description = "The user's role", IsRequired = true }
    }
};
AgentVersion agent = projectClient.AgentAdministrationClient.CreateAgentVersion(
    agentName: "structured-input-agent", options: new(agentDefinition));

// Send response with runtime structured input values
AgentReference agentRef = new(name: agent.Name, version: agent.Version);
ProjectResponsesClient responseClient =
    projectClient.ProjectOpenAIClient.GetProjectResponsesClientForAgent(agentRef);

CreateResponseOptions responseOptions = new()
{
    Input = [ResponseItem.CreateUserMessageItem("Hello! Can you confirm my details?")]
};
responseOptions.Patch.Set(
    "$.structured_inputs[\"userName\"]"u8,
    BinaryData.FromObjectAsJson("Alice Smith"));
responseOptions.Patch.Set(
    "$.structured_inputs[\"userRole\"]"u8,
    BinaryData.FromObjectAsJson("Senior Developer"));

ResponseResult response = responseClient.CreateResponse(responseOptions);
Console.WriteLine(response.GetOutputText());

// Clean up
projectClient.AgentAdministrationClient.DeleteAgentVersion(
    agentName: agent.Name, agentVersion: agent.Version);

Oczekiwane dane wyjściowe

Hello Alice Smith! I can confirm your details: your name is Alice Smith and your role is Senior Developer. How can I help you today?

Słownik StructuredInputs definicji agenta mapuje nazwy szablonów na ich schematy. W czasie wykonywania użyj metody Patch.Set na CreateResponseOptions, aby dostarczyć rzeczywiste wartości przez ścieżkę $.structured_inputs JSON.

import { DefaultAzureCredential } from "@azure/identity";
import { AIProjectClient } from "@azure/ai-projects";

// Format: "https://resource_name.ai.azure.com/api/projects/project_name"
const PROJECT_ENDPOINT = "your_project_endpoint";

export async function main(): Promise<void> {
  // Create clients to call Foundry API
  const project = new AIProjectClient(PROJECT_ENDPOINT, new DefaultAzureCredential());
  const openai = project.getOpenAIClient();

  // Create agent with handlebar templates in instructions
  const agent = await project.agents.createVersion("structured-input-agent", {
    kind: "prompt",
    model: "gpt-5-mini",
    instructions:
      "You are a helpful assistant. " +
      "The user's name is {{userName}} and their role is {{userRole}}. " +
      "Greet them and confirm their details.",
    structured_inputs: {
      userName: { description: "The user's name", required: true },
      userRole: { description: "The user's role", required: true },
    },
  });
  console.log(`Agent created: ${agent.name}, version: ${agent.version}`);

  // Create conversation and send request with runtime values
  const conversation = await openai.conversations.create();
  const response = await openai.responses.create(
    {
      conversation: conversation.id,
      input: "Hello! Can you confirm my details?",
    },
    {
      body: {
        agent_reference: { name: agent.name, type: "agent_reference" },
        structured_inputs: { userName: "Alice Smith", userRole: "Senior Developer" },
      },
    },
  );
  console.log(response.output_text);

  // Clean up
  await project.agents.deleteVersion(agent.name, agent.version);
}

main().catch(console.error);

Oczekiwane dane wyjściowe

Agent created: structured-input-agent, version: 1
Hello Alice Smith! I can confirm your details: your name is Alice Smith and your role is Senior Developer. How can I help you today?

Definicja agenta używa structured_inputs do deklarowania schematów szablonu. W czasie wykonywania przekaż rzeczywiste wartości w parametrze body wraz z parametrem agent_reference.

Dodaj zależność do elementu pom.xml:

<dependency>
    <groupId>com.azure</groupId>
    <artifactId>azure-ai-agents</artifactId>
    <version>2.4.0</version>
</dependency>
import com.azure.ai.agents.AgentsClient;
import com.azure.ai.agents.AgentsClientBuilder;
import com.azure.ai.agents.AgentsServiceVersion;
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.PromptAgentDefinition;
import com.azure.ai.agents.models.StructuredInputDefinition;
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.LinkedHashMap;
import java.util.Map;

public class StructuredInputInstructionsExample {
    public static void main(String[] args) {
        // Format: "https://resource_name.ai.azure.com/api/projects/project_name"
        String projectEndpoint = "your_project_endpoint";

        AgentsClientBuilder builder = new AgentsClientBuilder()
            .credential(new DefaultAzureCredentialBuilder().build())
            .endpoint(projectEndpoint)
            .serviceVersion(AgentsServiceVersion.getLatest());

        AgentsClient agentsClient = builder.buildAgentsClient();
        ResponsesClient responsesClient = builder.buildResponsesClient();

        // Define structured input schemas
        Map<String, StructuredInputDefinition> inputDefs = new LinkedHashMap<>();
        inputDefs.put("userName",
            new StructuredInputDefinition().setDescription("The user's name").setRequired(true));
        inputDefs.put("userRole",
            new StructuredInputDefinition().setDescription("The user's role").setRequired(true));

        // Create agent with handlebar templates in instructions
        AgentVersionDetails agent = agentsClient.createAgentVersion(
            "structured-input-agent",
            new PromptAgentDefinition("gpt-5-mini")
                .setInstructions("You are a helpful assistant. "
                    + "The user's name is {{userName}} and their role is {{userRole}}. "
                    + "Greet them and confirm their details.")
                .setStructuredInputs(inputDefs));

        // Supply structured input values at runtime
        Map<String, BinaryData> inputValues = new LinkedHashMap<>();
        inputValues.put("userName", BinaryData.fromObject("Alice Smith"));
        inputValues.put("userRole", BinaryData.fromObject("Senior Developer"));

        Response response = responsesClient.createAzureResponse(
            new AzureCreateResponseOptions()
                .setAgentReference(
                    new AgentReference(agent.getName()).setVersion(agent.getVersion()))
                .setStructuredInputs(inputValues),
            ResponseCreateParams.builder()
                .input("Hello! Can you confirm my details?"));

        System.out.println("Response: " + response.output());

        // Clean up
        agentsClient.deleteAgentVersion(agent.getName(), agent.getVersion());
    }
}

Oczekiwane dane wyjściowe

Response: Hello Alice Smith! I can confirm your details: your name is Alice Smith and your role is Senior Developer. How can I help you today?

Java SDK używa StructuredInputDefinition dla schematu agenta i Map<String, BinaryData> dla wartości uruchomieniowych przekazywanych za pomocą AzureCreateResponseOptions.

Tworzenie agenta ze ustrukturyzowanymi danymi wejściowymi

curl -X POST "$FOUNDRY_PROJECT_ENDPOINT/agents?api-version=v1" \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $AGENT_TOKEN" \
  --data-binary @- <<EOF
{
    "name": "structured-input-agent",
    "definition": {
      "kind": "prompt",
      "model": "<MODEL_DEPLOYMENT>",
      "instructions": "You are a helpful assistant. The user's name is {{userName}} and their role is {{userRole}}. Greet them and confirm their details.",
      "structured_inputs": {
        "userName": {
          "type": "string",
          "description": "The user's name",
          "default_value": "Unknown"
        },
        "userRole": {
          "type": "string",
          "description": "The user's role",
          "default_value": "User"
        }
      }
    }
}
EOF

Tworzenie odpowiedzi z ustrukturyzowanymi wartościami wejściowymi

curl -X POST "$FOUNDRY_PROJECT_ENDPOINT/openai/v1/responses" \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $AGENT_TOKEN" \
  -d '{
    "agent_reference": {
      "type": "agent_reference",
      "name": "structured-input-agent"
    },
    "input": [
      {
        "type": "message",
        "role": "user",
        "content": "Hello! Can you confirm my details?"
      }
    ],
    "structured_inputs": {
      "userName": "Alice Smith",
      "userRole": "Senior Developer"
    }
  }'

Obiekt definicji agenta structured_inputs deklaruje schematy z opisami i wartościami domyślnymi. Żądanie odpowiedzi structured_inputs dostarcza rzeczywistych wartości środowiska uruchomieniowego, które zastępują szablony {{userName}} oraz {{userRole}}.

Używanie ustrukturyzowanych danych wejściowych z interpreterem kodu

Za pomocą danych wejściowych ze strukturą można dynamicznie konfigurować pliki i kontenery używane przez narzędzie Interpreter kodu w czasie wykonywania. Zdefiniuj szablony uchwytu we właściwościach narzędzia file_ids lub container, a następnie podaj rzeczywiste identyfikatory podczas tworzenia odpowiedzi.

from io import BytesIO
from azure.ai.projects import AIProjectClient
from azure.ai.projects.models import (
    PromptAgentDefinition,
    CodeInterpreterTool,
    AutoCodeInterpreterToolParam,
    StructuredInputDefinition,
)
from azure.identity import DefaultAzureCredential

# Format: "https://resource_name.ai.azure.com/api/projects/project_name"
PROJECT_ENDPOINT = "your_project_endpoint"

# Create clients to call Foundry API
project = AIProjectClient(endpoint=PROJECT_ENDPOINT, credential=DefaultAzureCredential())
openai = project.get_openai_client()

# Upload a CSV file for the code interpreter
csv_file = BytesIO(b"x\n1\n2\n3\n")
csv_file.name = "numbers.csv"
uploaded = openai.files.create(purpose="assistants", file=csv_file)
print(f"File uploaded (id: {uploaded.id})")

# Create agent with a template placeholder for the file ID
tool = CodeInterpreterTool(
    container=AutoCodeInterpreterToolParam(file_ids=["{{analysis_file_id}}"])
)
agent = project.agents.create_version(
    agent_name="code-interp-structured",
    definition=PromptAgentDefinition(
        model="gpt-5-mini",
        instructions="You are a helpful data analyst.",
        tools=[tool],
        structured_inputs={
            "analysis_file_id": StructuredInputDefinition(
                description="File ID for the code interpreter",
                required=True,
                schema={"type": "string"},
            ),
        },
    ),
)

# Supply the actual file ID at runtime
conversation = openai.conversations.create()
response = openai.responses.create(
    conversation=conversation.id,
    input="Read numbers.csv and return the sum of x.",
    extra_body={
        "agent_reference": {"name": agent.name, "type": "agent_reference"},
        "structured_inputs": {"analysis_file_id": uploaded.id},
    },
    tool_choice="required",
)
print(response.output_text)

Oczekiwane dane wyjściowe

File uploaded (id: <file-id>)
The sum of x in numbers.csv is 6.

Symbol {{analysis_file_id}} zastępczy w tablicy file_ids narzędzia jest zastępowany rzeczywistym identyfikatorem pliku w czasie wykonywania. Korzystając z tego podejścia, można ponownie użyć tej samej definicji agenta z różnymi plikami dla każdego żądania.

using System;
using Azure.AI.Projects;
using Azure.AI.Projects.Agents;
using Azure.AI.Extensions.OpenAI;
using Azure.Identity;
using OpenAI.Responses;

// Format: "https://resource_name.ai.azure.com/api/projects/project_name"
var projectEndpoint = "your_project_endpoint";

// Create project client to call Foundry API
AIProjectClient projectClient = new(
    endpoint: new Uri(projectEndpoint),
    tokenProvider: new DefaultAzureCredential());

// Create agent with a structured input placeholder for the file ID
DeclarativeAgentDefinition agentDefinition = new(model: "gpt-5-mini")
{
    Instructions = "You are a helpful data analyst.",
    Tools = {
        ResponseTool.CreateCodeInterpreterTool(
            new CodeInterpreterToolContainer(
                CodeInterpreterToolContainerConfiguration
                    .CreateAutomaticContainerConfiguration(
                        fileIds: ["{{analysis_file_id}}"])))
    },
    StructuredInputs =
    {
        ["analysis_file_id"] = new StructuredInputDefinition
            { Description = "File ID for the code interpreter", IsRequired = true }
    }
};
AgentVersion agent = projectClient.AgentAdministrationClient.CreateAgentVersion(
    agentName: "code-interp-structured", options: new(agentDefinition));

// Supply the actual file ID at runtime
AgentReference agentRef = new(name: agent.Name, version: agent.Version);
ProjectResponsesClient responseClient =
    projectClient.ProjectOpenAIClient.GetProjectResponsesClientForAgent(agentRef);

CreateResponseOptions responseOptions = new()
{
    Input = [ResponseItem.CreateUserMessageItem(
        "Read numbers.csv and return the sum of x.")]
};
responseOptions.Patch.Set(
    "$.structured_inputs[\"analysis_file_id\"]"u8,
    BinaryData.FromObjectAsJson("<uploaded-file-id>"));

ResponseResult response = responseClient.CreateResponse(responseOptions);
Console.WriteLine(response.GetOutputText());

// Clean up
projectClient.AgentAdministrationClient.DeleteAgentVersion(
    agentName: agent.Name, agentVersion: agent.Version);

Oczekiwane dane wyjściowe

The sum of x in numbers.csv is 6.
import { DefaultAzureCredential } from "@azure/identity";
import { AIProjectClient } from "@azure/ai-projects";

// Format: "https://resource_name.ai.azure.com/api/projects/project_name"
const PROJECT_ENDPOINT = "your_project_endpoint";

export async function main(): Promise<void> {
  const project = new AIProjectClient(PROJECT_ENDPOINT, new DefaultAzureCredential());
  const openai = project.getOpenAIClient();

  // Upload a file for code interpreter
  const file = new File(["x\n1\n2\n3\n"], "numbers.csv");
  const uploaded = await openai.files.create({ file, purpose: "assistants" });
  console.log(`File uploaded (id: ${uploaded.id})`);

  // Create agent with a template placeholder for the file ID
  const agent = await project.agents.createVersion("code-interp-structured", {
    kind: "prompt",
    model: "gpt-5-mini",
    instructions: "You are a helpful data analyst.",
    tools: [
      {
        type: "code_interpreter",
        container: { type: "auto", file_ids: ["{{analysis_file_id}}"] },
      },
    ],
    structured_inputs: {
      analysis_file_id: {
        description: "File ID for the code interpreter",
        required: true,
      },
    },
  });

  // Supply the actual file ID at runtime
  const conversation = await openai.conversations.create();
  const response = await openai.responses.create(
    {
      conversation: conversation.id,
      input: "Read numbers.csv and return the sum of x.",
      tool_choice: "required",
    },
    {
      body: {
        agent_reference: { name: agent.name, type: "agent_reference" },
        structured_inputs: { analysis_file_id: uploaded.id },
      },
    },
  );
  console.log(response.output_text);

  // Clean up
  await project.agents.deleteVersion(agent.name, agent.version);
}

main().catch(console.error);

Oczekiwane dane wyjściowe

File uploaded (id: <file-id>)
The sum of x in numbers.csv is 6.
import com.azure.ai.agents.AgentsClient;
import com.azure.ai.agents.AgentsClientBuilder;
import com.azure.ai.agents.AgentsServiceVersion;
import com.azure.ai.agents.ResponsesClient;
import com.azure.ai.agents.models.*;
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.LinkedHashMap;
import java.util.Map;

public class CodeInterpreterStructuredInputExample {
    public static void main(String[] args) {
        // Format: "https://resource_name.ai.azure.com/api/projects/project_name"
        String projectEndpoint = "your_project_endpoint";

        AgentsClientBuilder builder = new AgentsClientBuilder()
            .credential(new DefaultAzureCredentialBuilder().build())
            .endpoint(projectEndpoint)
            .serviceVersion(AgentsServiceVersion.getLatest());

        AgentsClient agentsClient = builder.buildAgentsClient();
        ResponsesClient responsesClient = builder.buildResponsesClient();

        // Create code interpreter tool with a template placeholder
        CodeInterpreterTool tool = new CodeInterpreterTool()
            .setContainer(new AutoCodeInterpreterToolParameter()
                .setFileIds(Arrays.asList("{{analysis_file_id}}")));

        Map<String, StructuredInputDefinition> inputDefs = new LinkedHashMap<>();
        inputDefs.put("analysis_file_id",
            new StructuredInputDefinition()
                .setDescription("File ID for the code interpreter")
                .setRequired(true));

        AgentVersionDetails agent = agentsClient.createAgentVersion(
            "code-interp-structured",
            new PromptAgentDefinition("gpt-5-mini")
                .setInstructions("You are a helpful data analyst.")
                .setTools(Arrays.asList(tool))
                .setStructuredInputs(inputDefs));

        // Supply the actual file ID at runtime
        Map<String, BinaryData> inputValues = new LinkedHashMap<>();
        inputValues.put("analysis_file_id",
            BinaryData.fromObject("<uploaded-file-id>"));

        Response response = responsesClient.createAzureResponse(
            new AzureCreateResponseOptions()
                .setAgentReference(
                    new AgentReference(agent.getName()).setVersion(agent.getVersion()))
                .setStructuredInputs(inputValues),
            ResponseCreateParams.builder()
                .input("Read numbers.csv and return the sum of x."));

        System.out.println("Response: " + response.output());

        // Clean up
        agentsClient.deleteAgentVersion(agent.getName(), agent.getVersion());
    }
}

Oczekiwane dane wyjściowe

Response: The sum of x in numbers.csv is 6.

Tworzenie agenta z dynamicznymi plikami interpretera kodu

curl -X POST "$FOUNDRY_PROJECT_ENDPOINT/agents?api-version=v1" \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $AGENT_TOKEN" \
  --data-binary @- <<EOF
{
    "name": "code-interp-structured",
    "definition": {
      "kind": "prompt",
      "model": "<MODEL_DEPLOYMENT>",
      "instructions": "You are a helpful data analyst.",
      "tools": [
        {
          "type": "code_interpreter",
          "container": {
            "type": "auto",
            "file_ids": ["{{analysis_file_id}}"]
          }
        }
      ],
      "structured_inputs": {
        "analysis_file_id": {
          "description": "File ID for the code interpreter",
          "required": true,
          "schema": {"type": "string"}
        }
      }
    }
}
EOF

Tworzenie odpowiedzi przy użyciu identyfikatora pliku

curl -X POST "$FOUNDRY_PROJECT_ENDPOINT/openai/v1/responses" \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $AGENT_TOKEN" \
  -d '{
    "agent_reference": {
      "type": "agent_reference",
      "name": "code-interp-structured"
    },
    "input": [
      {
        "type": "message",
        "role": "user",
        "content": "Read numbers.csv and return the sum of x."
      }
    ],
    "structured_inputs": {
      "analysis_file_id": "<FILE_ID>"
    },
    "tool_choice": "required"
  }'

Szablon {{analysis_file_id}} w pliku file_ids jest zastępowany rzeczywistym identyfikatorem pliku w czasie wykonywania. Możesz zdefiniować wiele symboli zastępczych identyfikatora pliku i pozostawić te nieużywane puste. Puste wartości są automatycznie usuwane z tablicy.

Za pomocą danych wejściowych ze strukturą można dynamicznie skonfigurować, który wektor przechowuje zapytania narzędzia wyszukiwania plików w czasie wykonywania. Określ zastępcze elementy szablonu w tablicy vector_store_ids, a następnie podaj rzeczywiste identyfikatory wektorowych magazynów danych podczas tworzenia odpowiedzi.

from azure.ai.projects import AIProjectClient
from azure.ai.projects.models import (
    PromptAgentDefinition,
    FileSearchTool,
    StructuredInputDefinition,
)
from azure.identity import DefaultAzureCredential

# Format: "https://resource_name.ai.azure.com/api/projects/project_name"
PROJECT_ENDPOINT = "your_project_endpoint"

# Create clients to call Foundry API
project = AIProjectClient(endpoint=PROJECT_ENDPOINT, credential=DefaultAzureCredential())
openai = project.get_openai_client()

# Create a vector store and upload a file
vector_store = openai.vector_stores.create(name="ProductInfoStore")
with open("product_info.md", "rb") as f:
    file = openai.vector_stores.files.upload_and_poll(
        vector_store_id=vector_store.id, file=f
    )
print(f"Vector store created (id: {vector_store.id})")

# Create agent with a template placeholder for vector store ID
tool = FileSearchTool(vector_store_ids=["{{vector_store_id}}"])
agent = project.agents.create_version(
    agent_name="file-search-structured",
    definition=PromptAgentDefinition(
        model="gpt-5-mini",
        instructions="You are a helpful assistant that searches product information.",
        tools=[tool],
        structured_inputs={
            "vector_store_id": StructuredInputDefinition(
                description="Vector store ID for file search",
                required=True,
                schema={"type": "string"},
            ),
        },
    ),
)

# Supply the actual vector store ID at runtime
conversation = openai.conversations.create()
response = openai.responses.create(
    conversation=conversation.id,
    input="Tell me about Contoso products",
    extra_body={
        "agent_reference": {"name": agent.name, "type": "agent_reference"},
        "structured_inputs": {"vector_store_id": vector_store.id},
    },
)
print(response.output_text)

Oczekiwane dane wyjściowe

Vector store created (id: <vector-store-id>)
Based on the product information, Contoso offers several product lines including...

Znacznik {{vector_store_id}} jest zastępowany rzeczywistym identyfikatorem magazynu wektorów w czasie wykonywania. Można zdefiniować wiele symboli zastępczych magazynu wektorów, aby włączyć warstwowe lub kontekstowe bazy wiedzy.

using System;
using Azure.AI.Projects;
using Azure.AI.Projects.Agents;
using Azure.AI.Extensions.OpenAI;
using Azure.Identity;
using OpenAI.Responses;

// Format: "https://resource_name.ai.azure.com/api/projects/project_name"
var projectEndpoint = "your_project_endpoint";

AIProjectClient projectClient = new(
    endpoint: new Uri(projectEndpoint),
    tokenProvider: new DefaultAzureCredential());

// Create agent with a template placeholder for vector store ID
DeclarativeAgentDefinition agentDefinition = new(model: "gpt-5-mini")
{
    Instructions = "You are a helpful assistant that searches product information.",
    Tools = {
        ResponseTool.CreateFileSearchTool(
            vectorStoreIds: ["{{vector_store_id}}"])
    },
    StructuredInputs =
    {
        ["vector_store_id"] = new StructuredInputDefinition
            { Description = "Vector store ID for file search", IsRequired = true }
    }
};
AgentVersion agent = projectClient.AgentAdministrationClient.CreateAgentVersion(
    agentName: "file-search-structured", options: new(agentDefinition));

// Supply the actual vector store ID at runtime
AgentReference agentRef = new(name: agent.Name, version: agent.Version);
ProjectResponsesClient responseClient =
    projectClient.ProjectOpenAIClient.GetProjectResponsesClientForAgent(agentRef);

CreateResponseOptions responseOptions = new()
{
    Input = [ResponseItem.CreateUserMessageItem("Tell me about Contoso products")]
};
responseOptions.Patch.Set(
    "$.structured_inputs[\"vector_store_id\"]"u8,
    BinaryData.FromObjectAsJson("<vector-store-id>"));

ResponseResult response = responseClient.CreateResponse(responseOptions);
Console.WriteLine(response.GetOutputText());

// Clean up
projectClient.AgentAdministrationClient.DeleteAgentVersion(
    agentName: agent.Name, agentVersion: agent.Version);

Oczekiwane dane wyjściowe

Based on the product information, Contoso offers several product lines including...
import { DefaultAzureCredential } from "@azure/identity";
import { AIProjectClient } from "@azure/ai-projects";

// Format: "https://resource_name.ai.azure.com/api/projects/project_name"
const PROJECT_ENDPOINT = "your_project_endpoint";

export async function main(): Promise<void> {
  const project = new AIProjectClient(PROJECT_ENDPOINT, new DefaultAzureCredential());
  const openai = project.getOpenAIClient();

  // Create a vector store (assumes file already uploaded)
  const vectorStore = await openai.vectorStores.create({ name: "ProductInfoStore" });
  console.log(`Vector store created (id: ${vectorStore.id})`);

  // Create agent with a template placeholder for vector store ID
  const agent = await project.agents.createVersion("file-search-structured", {
    kind: "prompt",
    model: "gpt-5-mini",
    instructions: "You are a helpful assistant that searches product information.",
    tools: [
      {
        type: "file_search",
        vector_store_ids: ["{{vector_store_id}}"],
      },
    ],
    structured_inputs: {
      vector_store_id: {
        description: "Vector store ID for file search",
        required: true,
      },
    },
  });

  // Supply the actual vector store ID at runtime
  const conversation = await openai.conversations.create();
  const response = await openai.responses.create(
    {
      conversation: conversation.id,
      input: "Tell me about Contoso products",
    },
    {
      body: {
        agent_reference: { name: agent.name, type: "agent_reference" },
        structured_inputs: { vector_store_id: vectorStore.id },
      },
    },
  );
  console.log(response.output_text);

  // Clean up
  await project.agents.deleteVersion(agent.name, agent.version);
}

main().catch(console.error);

Oczekiwane dane wyjściowe

Vector store created (id: <vector-store-id>)
Based on the product information, Contoso offers several product lines including...
import com.azure.ai.agents.AgentsClient;
import com.azure.ai.agents.AgentsClientBuilder;
import com.azure.ai.agents.AgentsServiceVersion;
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.FileSearchTool;
import com.azure.ai.agents.models.PromptAgentDefinition;
import com.azure.ai.agents.models.StructuredInputDefinition;
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.LinkedHashMap;
import java.util.Map;

public class FileSearchStructuredInputExample {
    public static void main(String[] args) {
        // Format: "https://resource_name.ai.azure.com/api/projects/project_name"
        String projectEndpoint = "your_project_endpoint";

        AgentsClientBuilder builder = new AgentsClientBuilder()
            .credential(new DefaultAzureCredentialBuilder().build())
            .endpoint(projectEndpoint)
            .serviceVersion(AgentsServiceVersion.getLatest());

        AgentsClient agentsClient = builder.buildAgentsClient();
        ResponsesClient responsesClient = builder.buildResponsesClient();

        // Create agent with a template placeholder for vector store ID
        FileSearchTool tool = new FileSearchTool()
            .setVectorStoreIds(Arrays.asList("{{vector_store_id}}"));

        Map<String, StructuredInputDefinition> inputDefs = new LinkedHashMap<>();
        inputDefs.put("vector_store_id",
            new StructuredInputDefinition()
                .setDescription("Vector store ID for file search")
                .setRequired(true));

        AgentVersionDetails agent = agentsClient.createAgentVersion(
            "file-search-structured",
            new PromptAgentDefinition("gpt-5-mini")
                .setInstructions(
                    "You are a helpful assistant that searches product information.")
                .setTools(Arrays.asList(tool))
                .setStructuredInputs(inputDefs));

        // Supply the actual vector store ID at runtime
        Map<String, BinaryData> inputValues = new LinkedHashMap<>();
        inputValues.put("vector_store_id",
            BinaryData.fromObject("<vector-store-id>"));

        Response response = responsesClient.createAzureResponse(
            new AzureCreateResponseOptions()
                .setAgentReference(
                    new AgentReference(agent.getName()).setVersion(agent.getVersion()))
                .setStructuredInputs(inputValues),
            ResponseCreateParams.builder()
                .input("Tell me about Contoso products"));

        System.out.println("Response: " + response.output());

        // Clean up
        agentsClient.deleteAgentVersion(agent.getName(), agent.getVersion());
    }
}

Oczekiwane dane wyjściowe

Response: Based on the product information, Contoso offers several product lines including...

Tworzenie agenta z dynamicznymi repozytoriami wektorowymi wyszukiwania plików

curl -X POST "$FOUNDRY_PROJECT_ENDPOINT/agents?api-version=v1" \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $AGENT_TOKEN" \
  -d '{
    "name": "file-search-structured",
    "definition": {
      "kind": "prompt",
      "model": "<MODEL_DEPLOYMENT>",
      "instructions": "You are a helpful assistant that searches product information.",
      "tools": [
        {
          "type": "file_search",
          "vector_store_ids": [
            "vs_base_kb",
            "{{tier_specific_kb}}"
          ]
        }
      ],
      "structured_inputs": {
        "tier_specific_kb": {
          "description": "Vector store ID for customer tier",
          "required": true,
          "schema": {"type": "string"}
        }
      }
    }
  }'

Tworzenie odpowiedzi przy użyciu identyfikatora magazynu wektorów

curl -X POST "$FOUNDRY_PROJECT_ENDPOINT/openai/v1/responses" \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $AGENT_TOKEN" \
  -d '{
    "agent_reference": {
      "type": "agent_reference",
      "name": "file-search-structured"
    },
    "input": [
      {
        "type": "message",
        "role": "user",
        "content": "Tell me about Contoso products"
      }
    ],
    "structured_inputs": {
      "tier_specific_kb": "vs_premium_kb_2024"
    }
  }'

Ten przykład łączy statyczny magazyn wektorów (vs_base_kb) z dynamicznym ({{tier_specific_kb}}). Symbol zastępczy szablonu jest zastępowany podczas działania programu, a proces automatycznie usuwa wszystkie puste ciągi znaków w tablicy.

Za pomocą strukturalnych danych wejściowych można dynamicznie skonfigurować Wyszukiwanie AI platformy Azure indeks narzędzia filter w czasie wykonywania. Zdefiniuj szablon paska obsługi w wyrażeniu filtru OData, a następnie podaj rzeczywistą wartość filtru podczas tworzenia odpowiedzi. Ten wzorzec umożliwia pojedynczej definicji agenta obsługę użytkowników, których zapytania muszą być ograniczone do różnych podzbiorów indeksu bez tworzenia oddzielnej wersji agenta na wartość filtru.

Zweryfikuj wartości przed wstawieniem ich do filtru OData. Zezwalaj tylko na oczekiwane wartości, uniknij znaków specjalnych OData i nie akceptuj pełnych wyrażeń filtru od niezaufanych użytkowników.

import os
from azure.ai.projects import AIProjectClient
from azure.ai.projects.models import (
    AISearchIndexResource,
    AzureAISearchQueryType,
    AzureAISearchTool,
    AzureAISearchToolResource,
    PromptAgentDefinition,
    StructuredInputDefinition,
)
from azure.identity import DefaultAzureCredential

# Format: "https://resource_name.ai.azure.com/api/projects/project_name"
PROJECT_ENDPOINT = "your_project_endpoint"

# Create clients to call Foundry API
project = AIProjectClient(endpoint=PROJECT_ENDPOINT, credential=DefaultAzureCredential())
openai = project.get_openai_client()

# Create the AI Search tool with a handlebar template inside the filter expression
tool = AzureAISearchTool(
    azure_ai_search=AzureAISearchToolResource(
        indexes=[
            AISearchIndexResource(
                project_connection_id=os.environ["AI_SEARCH_PROJECT_CONNECTION_ID"],
                index_name=os.environ["AI_SEARCH_INDEX_NAME"],
                query_type=AzureAISearchQueryType.SIMPLE,
                filter="search.ismatchscoring('{{userFilter}}')",
            ),
        ]
    )
)

# Create the agent with a structured input that supplies the filter value
agent = project.agents.create_version(
    agent_name="aisearch-agent-structured-input",
    definition=PromptAgentDefinition(
        model="gpt-5-mini",
        instructions=(
            "You are a helpful assistant. You must always provide citations for "
            "answers using the tool and render them as: "
            "`\u3010message_idx:search_idx\u2020source\u3011`."
        ),
        tools=[tool],
        structured_inputs={
            "userFilter": StructuredInputDefinition(
                description="The user's search filter",
                required=True,
                schema={"type": "string"},
            ),
        },
    ),
)
print(f"Agent created (id: {agent.id}, name: {agent.name}, version: {agent.version})")

# Supply the actual filter value at runtime
stream_response = openai.responses.create(
    stream=True,
    tool_choice="required",
    input="What outdoor gear do you have?",
    extra_body={
        "agent_reference": {"name": agent.name, "type": "agent_reference"},
        "structured_inputs": {"userFilter": "boots"},
    },
)

for event in stream_response:
    if event.type == "response.completed":
        print(f"Agent response: {event.response.output_text}")

Oczekiwane dane wyjściowe

Agent created (id: <agent-id>, name: aisearch-agent-structured-input, version: 1)
Agent response: Based on the index, the available outdoor boots include ...

Symbol zastępczy {{userFilter}} wewnątrz wyrażenia filter jest zastępowany wartością boots w czasie wykonywania, zanim zostanie uruchomione wyszukiwanie. Dla każdego żądania można podać różne wartości filtru, aby ograniczyć zakres wyników bez tworzenia nowej wersji agenta.

using System;
using Azure.AI.Projects;
using Azure.AI.Projects.Agents;
using Azure.AI.Extensions.OpenAI;
using Azure.Identity;
using OpenAI.Responses;

// Format: "https://resource_name.ai.azure.com/api/projects/project_name"
var projectEndpoint = "your_project_endpoint";
var searchConnectionName = "my-search-connection";
var searchIndexName = "my-search-index";

AIProjectClient projectClient = new(
    endpoint: new Uri(projectEndpoint),
    tokenProvider: new DefaultAzureCredential());

// Resolve the project connection ID from the connection name
AIProjectConnection aiSearchConnection =
    projectClient.Connections.GetConnection(connectionName: searchConnectionName);

// Define the search index with a handlebar template inside the filter expression
AzureAISearchToolIndex index = new()
{
    ProjectConnectionId = aiSearchConnection.Id,
    IndexName = searchIndexName,
    QueryType = AzureAISearchQueryType.Simple,
    Filter = "search.ismatchscoring('{{userFilter}}')"
};

// Create the agent with a structured input that supplies the filter value
DeclarativeAgentDefinition agentDefinition = new(model: "gpt-5-mini")
{
    Instructions = "You are a helpful assistant. You must always provide citations for "
        + "answers using the tool and render them as: "
        + "`\u3010message_idx:search_idx\u2020source\u3011`.",
    Tools = { new AzureAISearchTool(new AzureAISearchToolOptions(indexes: [index])) },
    StructuredInputs =
    {
        ["userFilter"] = new StructuredInputDefinition
            { Description = "The user's search filter", IsRequired = true }
    }
};
AgentVersion agent = projectClient.AgentAdministrationClient.CreateAgentVersion(
    agentName: "aisearch-agent-structured-input",
    options: new(agentDefinition));

// Supply the actual filter value at runtime
AgentReference agentRef = new(name: agent.Name, version: agent.Version);
ProjectResponsesClient responseClient =
    projectClient.ProjectOpenAIClient.GetProjectResponsesClientForAgent(agentRef);

CreateResponseOptions responseOptions = new()
{
    Input = [ResponseItem.CreateUserMessageItem("What outdoor gear do you have?")]
};
responseOptions.Patch.Set(
    "$.structured_inputs[\"userFilter\"]"u8,
    BinaryData.FromObjectAsJson("boots"));

ResponseResult response = responseClient.CreateResponse(responseOptions);
Console.WriteLine(response.GetOutputText());

// Clean up
projectClient.AgentAdministrationClient.DeleteAgentVersion(
    agentName: agent.Name, agentVersion: agent.Version);

Oczekiwane dane wyjściowe

Based on the index, the available outdoor boots include ...

Właściwość Filter w AzureAISearchToolIndex obsługuje szablony Handlebars, które są rozwiązywane w czasie wykonywania. Użyj Patch.Set w elemencie CreateResponseOptions, aby przekazać wartość filtru za pomocą ścieżki JSON $.structured_inputs.

import { DefaultAzureCredential } from "@azure/identity";
import { AIProjectClient } from "@azure/ai-projects";

// Format: "https://resource_name.ai.azure.com/api/projects/project_name"
const PROJECT_ENDPOINT = "your_project_endpoint";
const SEARCH_CONNECTION_NAME = "my-search-connection";
const SEARCH_INDEX_NAME = "my-search-index";

export async function main(): Promise<void> {
  const project = new AIProjectClient(PROJECT_ENDPOINT, new DefaultAzureCredential());
  const openai = project.getOpenAIClient();

  // Resolve the project connection ID from the connection name
  const aiSearchConnection = await project.connections.get(SEARCH_CONNECTION_NAME);

  // Create the agent with a handlebar template inside the filter expression
  const agent = await project.agents.createVersion("aisearch-agent-structured-input", {
    kind: "prompt",
    model: "gpt-5-mini",
    instructions:
      "You are a helpful assistant. You must always provide citations for " +
      "answers using the tool and render them as: `[message_idx:search_idx†source]`.",
    tools: [
      {
        type: "azure_ai_search",
        azure_ai_search: {
          indexes: [
            {
              project_connection_id: aiSearchConnection.id,
              index_name: SEARCH_INDEX_NAME,
              query_type: "simple",
              filter: "search.ismatchscoring('{{userFilter}}')",
            },
          ],
        },
      },
    ],
    structured_inputs: {
      userFilter: { description: "The user's search filter", required: true },
    },
  });
  console.log(`Agent created (id: ${agent.id}, name: ${agent.name}, version: ${agent.version})`);

  // Supply the actual filter value at runtime
  const response = await openai.responses.create(
    {
      input: "What outdoor gear do you have?",
      tool_choice: "required",
    },
    {
      body: {
        agent_reference: { name: agent.name, type: "agent_reference" },
        structured_inputs: { userFilter: "boots" },
      },
    },
  );
  console.log(response.output_text);

  // Clean up
  await project.agents.deleteVersion(agent.name, agent.version);
}

main().catch(console.error);

Oczekiwane dane wyjściowe

Agent created (id: <agent-id>, name: aisearch-agent-structured-input, version: 1)
Based on the index, the available outdoor boots include ...
import com.azure.ai.agents.AgentsClient;
import com.azure.ai.agents.AgentsClientBuilder;
import com.azure.ai.agents.AgentsServiceVersion;
import com.azure.ai.agents.ResponsesClient;
import com.azure.ai.agents.models.AISearchIndexResource;
import com.azure.ai.agents.models.AgentReference;
import com.azure.ai.agents.models.AgentVersionDetails;
import com.azure.ai.agents.models.AzureAISearchQueryType;
import com.azure.ai.agents.models.AzureAISearchTool;
import com.azure.ai.agents.models.AzureAISearchToolResource;
import com.azure.ai.agents.models.AzureCreateResponseOptions;
import com.azure.ai.agents.models.PromptAgentDefinition;
import com.azure.ai.agents.models.StructuredInputDefinition;
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.LinkedHashMap;
import java.util.Map;

public class AzureAISearchStructuredInputExample {
    public static void main(String[] args) {
        // Format: "https://resource_name.ai.azure.com/api/projects/project_name"
        String projectEndpoint = "your_project_endpoint";
        String searchConnectionId = "your-search-connection-id";
        String searchIndexName = "my-search-index";

        AgentsClientBuilder builder = new AgentsClientBuilder()
            .credential(new DefaultAzureCredentialBuilder().build())
            .endpoint(projectEndpoint)
            .serviceVersion(AgentsServiceVersion.getLatest());

        AgentsClient agentsClient = builder.buildAgentsClient();
        ResponsesClient responsesClient = builder.buildResponsesClient();

        // Create the AI Search tool with a handlebar template inside the filter expression
        AzureAISearchTool tool = new AzureAISearchTool(
            new AzureAISearchToolResource(Arrays.asList(
                new AISearchIndexResource()
                    .setProjectConnectionId(searchConnectionId)
                    .setIndexName(searchIndexName)
                    .setQueryType(AzureAISearchQueryType.SIMPLE)
                    .setFilter("search.ismatchscoring('{{userFilter}}')")
            ))
        );

        Map<String, StructuredInputDefinition> inputDefs = new LinkedHashMap<>();
        inputDefs.put("userFilter",
            new StructuredInputDefinition()
                .setDescription("The user's search filter")
                .setRequired(true));

        AgentVersionDetails agent = agentsClient.createAgentVersion(
            "aisearch-agent-structured-input",
            new PromptAgentDefinition("gpt-5-mini")
                .setInstructions("You are a helpful assistant. Always provide citations.")
                .setTools(Arrays.asList(tool))
                .setStructuredInputs(inputDefs));

        // Supply the actual filter value at runtime
        Map<String, BinaryData> inputValues = new LinkedHashMap<>();
        inputValues.put("userFilter", BinaryData.fromObject("boots"));

        Response response = responsesClient.createAzureResponse(
            new AzureCreateResponseOptions()
                .setAgentReference(
                    new AgentReference(agent.getName()).setVersion(agent.getVersion()))
                .setStructuredInputs(inputValues),
            ResponseCreateParams.builder()
                .input("What outdoor gear do you have?"));

        System.out.println("Response: " + response.output());

        // Clean up
        agentsClient.deleteAgentVersion(agent.getName(), agent.getVersion());
    }
}

Oczekiwane dane wyjściowe

Response: Based on the index, the available outdoor boots include ...

Tworzenie agenta z dynamicznym filtrem Wyszukiwanie AI platformy Azure

curl -X POST "$FOUNDRY_PROJECT_ENDPOINT/agents?api-version=v1" \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $AGENT_TOKEN" \
  --data-binary @- <<EOF
{
    "name": "aisearch-agent-structured-input",
    "definition": {
      "kind": "prompt",
      "model": "<MODEL_DEPLOYMENT>",
      "instructions": "You are a helpful assistant. Always provide citations.",
      "tools": [
        {
          "type": "azure_ai_search",
          "azure_ai_search": {
            "indexes": [
              {
                "project_connection_id": "$AZURE_AI_SEARCH_CONNECTION_ID",
                "index_name": "$AI_SEARCH_INDEX_NAME",
                "query_type": "simple",
                "filter": "search.ismatchscoring('{{userFilter}}')"
              }
            ]
          }
        }
      ],
      "structured_inputs": {
        "userFilter": {
          "description": "The user's search filter",
          "required": true,
          "schema": {"type": "string"}
        }
      }
    }
}
EOF

Utwórz odpowiedź przy użyciu wartości filtru

curl -X POST "$FOUNDRY_PROJECT_ENDPOINT/openai/v1/responses" \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $AGENT_TOKEN" \
  -d '{
    "agent_reference": {
      "type": "agent_reference",
      "name": "aisearch-agent-structured-input"
    },
    "input": [
      {
        "type": "message",
        "role": "user",
        "content": "What outdoor gear do you have?"
      }
    ],
    "structured_inputs": {
      "userFilter": "boots"
    },
    "tool_choice": "required"
  }'

W czasie wykonywania wyrażenie filter zastępuje szablon {{userFilter}} elementem boots. Niecytowany heredoc rozwija zmienne środowiskowe połączenia i indeksu, zanim curl wyśle treść JSON.

Używanie ustrukturyzowanych danych wejściowych z serwerami MCP

Za pomocą danych wejściowych ze strukturą można dynamicznie konfigurować niezabezpieczone właściwości serwera MCP, takie jak adres URL serwera, etykieta serwera i nagłówki routingu. Użyj połączenia z projektem lub innego zarządzanego mechanizmu uwierzytelniania do obsługi poświadczeń. Korzystając z tego podejścia, pojedyncza definicja agenta może łączyć się z różnymi serwerami MCP w zależności od kontekstu.

Poniższy kod JSON przedstawia treść żądania dla operacji Create Agent Version (POST /agents?api-version=v1). Definicja agenta zawiera właściwości narzędzia MCP z symbolami zastępczymi szablonu handlebar:

{
  "name": "mcp-dynamic-agent",
  "definition": {
    "kind": "prompt",
    "model": "gpt-4o",
    "instructions": "You are a development assistant for {{project_name}}.",
    "tools": [
      {
        "type": "mcp",
        "server_label": "{{server_label}}",
        "server_url": "{{server_url}}",
        "require_approval": "never",
        "headers": {"X-Project-ID": "{{project_id}}"}
      }
    ],
    "structured_inputs": {
      "project_name": {
        "description": "Project name",
        "required": true
      },
      "server_label": {
        "description": "MCP server label",
        "required": true,
        "schema": {"type": "string"}
      },
      "server_url": {
        "description": "MCP server URL",
        "required": true,
        "schema": {"type": "string"}
      },
      "project_id": {
        "description": "Project identifier",
        "required": true,
        "schema": {"type": "string"}
      }
    }
  }
}

W czasie wykonywania podaj rzeczywiste wartości konfiguracji serwera w treści żądania dla operacji Create Response (POST /openai/v1/responses):

{
  "agent_reference": {
    "type": "agent_reference",
    "name": "mcp-dynamic-agent"
  },
  "input": [{"type": "message", "role": "user", "content": "List recent commits"}],
  "structured_inputs": {
    "project_name": "CloudSync API",
    "server_label": "cloudsync-repo",
    "server_url": "https://gitmcp.io/myorg/cloudsync-api",
    "project_id": "proj_12345"
  }
}

Wzorce zestawu SDK dla danych wejściowych ze strukturą MCP są zgodne z tym samym podejściem przedstawionym w poprzednich przykładach. Zdefiniuj elementy zastępcze szablonu we właściwościach narzędzia MCP, zadeklaruj schematy wejściowe o ustrukturyzowanej strukturze w definicji agenta i podaj wartości podczas wykonywania.

Poniższy przykład Python przedstawia kompletny wzorzec:

from azure.ai.projects import AIProjectClient
from azure.ai.projects.models import (
    MCPTool,
    PromptAgentDefinition,
    StructuredInputDefinition,
)
from azure.identity import DefaultAzureCredential

# Format: "https://resource_name.ai.azure.com/api/projects/project_name"
PROJECT_ENDPOINT = "your_project_endpoint"

# Create clients to call Foundry API
project = AIProjectClient(endpoint=PROJECT_ENDPOINT, credential=DefaultAzureCredential())
openai = project.get_openai_client()

# Create MCP tool with template placeholders
tool = MCPTool(
    server_label="{{server_label}}",
    server_url="{{server_url}}",
    require_approval="never",
    headers={"X-Project-ID": "{{project_id}}"},
)

# Create agent with structured inputs for MCP configuration
agent = project.agents.create_version(
    agent_name="mcp-dynamic-agent",
    definition=PromptAgentDefinition(
        model="gpt-5-mini",
        instructions="You are a helpful development assistant for {{project_name}}.",
        tools=[tool],
        structured_inputs={
            "project_name": StructuredInputDefinition(
                description="Project name", required=True, schema={"type": "string"},
            ),
            "server_label": StructuredInputDefinition(
                description="MCP server label", required=True, schema={"type": "string"},
            ),
            "server_url": StructuredInputDefinition(
                description="MCP server URL", required=True, schema={"type": "string"},
            ),
            "project_id": StructuredInputDefinition(
                description="Project identifier", required=True, schema={"type": "string"},
            ),
        },
    ),
)

# Supply MCP server configuration at runtime
conversation = openai.conversations.create()
response = openai.responses.create(
    conversation=conversation.id,
    input="List recent commits",
    extra_body={
        "agent_reference": {"name": agent.name, "type": "agent_reference"},
        "structured_inputs": {
            "project_name": "CloudSync API",
            "server_label": "cloudsync-repo",
            "server_url": "https://gitmcp.io/myorg/cloudsync-api",
            "project_id": "proj_12345",
        },
    },
)
print(response.output_text)

Poniższy przykład języka TypeScript przedstawia ten sam wzorzec:

import { DefaultAzureCredential } from "@azure/identity";
import { AIProjectClient } from "@azure/ai-projects";

// Format: "https://resource_name.ai.azure.com/api/projects/project_name"
const PROJECT_ENDPOINT = "your_project_endpoint";

export async function main(): Promise<void> {
  // Create clients to call Foundry API
  const project = new AIProjectClient(PROJECT_ENDPOINT, new DefaultAzureCredential());
  const openai = project.getOpenAIClient();

  // Create agent with structured inputs for MCP configuration. The MCP tool
  // is defined inline so TypeScript infers the literal "mcp" type instead of
  // widening it to string.
  const agent = await project.agents.createVersion("mcp-dynamic-agent", {
    kind: "prompt",
    model: "gpt-5-mini",
    instructions: "You are a helpful development assistant for {{project_name}}.",
    tools: [
      {
        type: "mcp",
        server_label: "{{server_label}}",
        server_url: "{{server_url}}",
        require_approval: "never",
        headers: {
          Authorization: "{{auth_token}}",
          "X-Project-ID": "{{project_id}}",
        },
      },
    ],
    structured_inputs: {
      project_name: {
        description: "Project name",
        required: true,
        schema: { type: "string" },
      },
      server_label: {
        description: "MCP server label",
        required: true,
        schema: { type: "string" },
      },
      server_url: {
        description: "MCP server URL",
        required: true,
        schema: { type: "string" },
      },
      auth_token: {
        description: "Authentication token",
        required: true,
        schema: { type: "string" },
      },
      project_id: {
        description: "Project identifier",
        required: true,
        schema: { type: "string" },
      },
    },
  });

  // Supply MCP server configuration at runtime
  const conversation = await openai.conversations.create();
  const response = await openai.responses.create(
    {
      conversation: conversation.id,
      input: "List recent commits",
    },
    {
      body: {
        agent_reference: { name: agent.name, type: "agent_reference" },
        structured_inputs: {
          project_name: "CloudSync API",
          server_label: "cloudsync-repo",
          server_url: "https://gitmcp.io/myorg/cloudsync-api",
          auth_token: "******",
          project_id: "proj_12345",
        },
      },
    },
  );
  console.log(response.output_text);
}

main().catch(console.error);

Aby uzyskać więcej informacji na temat nawiązywania połączenia z serwerami MCP, zobacz Łączenie agentów z serwerami MCP.

Użyj ustrukturyzowanych danych wejściowych w interfejsie API odpowiedzi

Szablony paska obsługi można używać bezpośrednio w wywołaniach interfejsu API odpowiedzi bez definiowania ich w definicji agenta. Takie podejście działa w przypadku instrukcji dotyczących poziomu odpowiedzi oraz komunikatów systemowych lub od programistów w tablicy wejściowej.

Instrukcje na poziomie odpowiedzi ze ustrukturyzowanymi danymi wejściowymi

Przekaż ustrukturyzowane dane wejściowe wraz z instructions żądaniem odpowiedzi, aby sparametryzować monit systemowy:

{
  "instructions": "You are assisting {{customerName}} from {{companyName}} located in {{location}}.",
  "input": [
    {
      "type": "message",
      "role": "user",
      "content": "Hello, who am I?"
    }
  ],
  "structured_inputs": {
    "customerName": "Bob Johnson",
    "companyName": "Tech Corp",
    "location": "San Francisco"
  },
  "model": "gpt-4o"
}

Komunikaty systemowe i deweloperskie ze ustrukturyzowanymi danymi wejściowymi

Użyj szablonów paska obsługi w zawartości komunikatów systemowych i deweloperów, aby wstrzyknąć wartości środowiska uruchomieniowego do kontekstu konwersacji:

{
  "instructions": "You are a helpful assistant.",
  "input": [
    {
      "type": "message",
      "role": "system",
      "content": "The user's name is {{userName}} and they work in {{department}}."
    },
    {
      "type": "message",
      "role": "developer",
      "content": [
        {
          "type": "input_text",
          "text": "User role: {{userRole}}. Always be professional."
        }
      ]
    },
    {
      "type": "message",
      "role": "user",
      "content": "Hello, can you confirm my details?"
    }
  ],
  "structured_inputs": {
    "userName": "Sarah Connor",
    "department": "Engineering",
    "userRole": "Tech Lead"
  },
  "model": "gpt-4o"
}

W kodzie zestawu SDK przekaż te wartości przy użyciu tych samych wzorców extra_body (Python), body (TypeScript) lub AzureCreateResponseOptions (Java/C#) pokazanych w poprzednich przykładach.

W poniższym przykładzie Python pokazano, jak używać instrukcji na poziomie odpowiedzi ze ustrukturyzowanymi danymi wejściowymi:

from azure.ai.projects import AIProjectClient
from azure.identity import DefaultAzureCredential

# Format: "https://resource_name.ai.azure.com/api/projects/project_name"
PROJECT_ENDPOINT = "your_project_endpoint"

# Create clients to call Foundry API
project = AIProjectClient(endpoint=PROJECT_ENDPOINT, credential=DefaultAzureCredential())
openai = project.get_openai_client()

# Pass structured inputs with response-level instructions
response = openai.responses.create(
    model="gpt-5-mini",
    instructions="You are assisting {{customerName}} from {{companyName}} located in {{location}}.",
    input=[
        {
            "type": "message",
            "role": "user",
            "content": "Hello, who am I?",
        }
    ],
    extra_body={
        "structured_inputs": {
            "customerName": "Bob Johnson",
            "companyName": "Tech Corp",
            "location": "San Francisco",
        },
    },
)
print(response.output_text)

Poniższy przykład języka TypeScript przedstawia ten sam wzorzec:

import { DefaultAzureCredential } from "@azure/identity";
import { AIProjectClient } from "@azure/ai-projects";

// Format: "https://resource_name.ai.azure.com/api/projects/project_name"
const PROJECT_ENDPOINT = "your_project_endpoint";

export async function main(): Promise<void> {
  // Create clients to call Foundry API
  const project = new AIProjectClient(PROJECT_ENDPOINT, new DefaultAzureCredential());
  const openai = project.getOpenAIClient();

  // Pass structured inputs with response-level instructions
  const response = await openai.responses.create(
    {
      model: "gpt-5-mini",
      instructions:
        "You are assisting {{customerName}} from {{companyName}} located in {{location}}.",
      input: [
        {
          type: "message",
          role: "user",
          content: "Hello, who am I?",
        },
      ],
    },
    {
      body: {
        structured_inputs: {
          customerName: "Bob Johnson",
          companyName: "Tech Corp",
          location: "San Francisco",
        },
      },
    },
  );
  console.log(response.output_text);
}

main().catch(console.error);

Zaawansowana składnia szablonu

Strukturalne dane wejściowe obsługują pełną składnię szablonów Handlebars poza prostym podstawieniem zmiennych. Aby utworzyć dynamiczną logikę instrukcji w ramach jednej definicji agenta, można użyć warunkowych, pętli i innych wbudowanych pomocników.

Poniższy przykład tworzy asystenta pogody, którego zachowanie dostosowuje się na podstawie danych wejściowych środowiska uruchomieniowego. Szablon instrukcji używa {{#if}} dla sekcji warunkowych i {{#each}} do iterowania po liście preferencji użytkownika.

from azure.ai.projects import AIProjectClient
from azure.ai.projects.models import PromptAgentDefinition, StructuredInputDefinition
from azure.identity import DefaultAzureCredential

# Format: "https://resource_name.ai.azure.com/api/projects/project_name"
PROJECT_ENDPOINT = "your_project_endpoint"

# Create clients to call Foundry API
project = AIProjectClient(endpoint=PROJECT_ENDPOINT, credential=DefaultAzureCredential())
openai = project.get_openai_client()

# Define instructions with conditionals and loops
instructions = """You are a weather assistant. Provide a helpful weather summary for the user.

The user asked about: {{location}}
Use the following units: {{units}}

{{#if includeForecast}}
Include a brief multi-day forecast in your response.
{{else}}
Focus only on the current conditions.
{{/if}}

{{#if preferences}}
The user has these additional preferences:
{{#each preferences}}
- {{this}}
{{/each}}
{{/if}}

Keep the final answer clear and easy to read."""

agent = project.agents.create_version(
    agent_name="weather-assistant",
    definition=PromptAgentDefinition(
        model="gpt-5-mini",
        instructions=instructions,
        structured_inputs={
            "location": StructuredInputDefinition(
                description="City or region to check weather for",
                required=True,
                schema={"type": "string"},
            ),
            "units": StructuredInputDefinition(
                description="Temperature units (Celsius or Fahrenheit)",
                default_value="Celsius",
                schema={"type": "string"},
            ),
            "includeForecast": StructuredInputDefinition(
                description="Whether to include a multi-day forecast",
                default_value="false",
                schema={"type": "boolean"},
            ),
            "preferences": StructuredInputDefinition(
                description="Additional user preferences",
                schema={"type": "array"},
            ),
        },
    ),
)

# Supply values at runtime — conditionals and loops resolve automatically
conversation = openai.conversations.create()
response = openai.responses.create(
    conversation=conversation.id,
    input="What's the weather like?",
    extra_body={
        "agent_reference": {"name": agent.name, "type": "agent_reference"},
        "structured_inputs": {
            "location": "Seattle, WA",
            "units": "Fahrenheit",
            "includeForecast": True,
            "preferences": ["Highlight UV index", "Include wind speed"],
        },
    },
)
print(response.output_text)

Poniższy przykład języka TypeScript przedstawia ten sam wzorzec:

import { DefaultAzureCredential } from "@azure/identity";
import { AIProjectClient } from "@azure/ai-projects";

// Format: "https://resource_name.ai.azure.com/api/projects/project_name"
const PROJECT_ENDPOINT = "your_project_endpoint";

export async function main(): Promise<void> {
  // Create clients to call Foundry API
  const project = new AIProjectClient(PROJECT_ENDPOINT, new DefaultAzureCredential());
  const openai = project.getOpenAIClient();

  // Define instructions with conditionals and loops
  const instructions = `You are a weather assistant. Provide a helpful weather summary for the user.

The user asked about: {{location}}
Use the following units: {{units}}

{{#if includeForecast}}
Include a brief multi-day forecast in your response.
{{else}}
Focus only on the current conditions.
{{/if}}

{{#if preferences}}
The user has these additional preferences:
{{#each preferences}}
- {{this}}
{{/each}}
{{/if}}

Keep the final answer clear and easy to read.`;

  const agent = await project.agents.createVersion("weather-assistant", {
    kind: "prompt",
    model: "gpt-5-mini",
    instructions,
    structured_inputs: {
      location: {
        description: "City or region to check weather for",
        required: true,
        schema: { type: "string" },
      },
      units: {
        description: "Temperature units (Celsius or Fahrenheit)",
        default_value: "Celsius",
        schema: { type: "string" },
      },
      includeForecast: {
        description: "Whether to include a multi-day forecast",
        default_value: false,
        schema: { type: "boolean" },
      },
      preferences: {
        description: "Additional user preferences",
        schema: { type: "array" },
      },
    },
  });

  // Supply values at runtime — conditionals and loops resolve automatically
  const conversation = await openai.conversations.create();
  const response = await openai.responses.create(
    {
      conversation: conversation.id,
      input: "What's the weather like?",
    },
    {
      body: {
        agent_reference: { name: agent.name, type: "agent_reference" },
        structured_inputs: {
          location: "Seattle, WA",
          units: "Fahrenheit",
          includeForecast: true,
          preferences: ["Highlight UV index", "Include wind speed"],
        },
      },
    },
  );
  console.log(response.output_text);
}

main().catch(console.error);

Po tych wartościach rozwiązane instrukcje stają się następujące:

Jesteś asystentem pogody. Podaj przydatne podsumowanie pogody dla użytkownika.

Użytkownik zapytał o: Seattle, WA

Użyj następujących jednostek: Fahrenheit

Uwzględnij krótką wielodniową prognozę w odpowiedzi.

Użytkownik ma następujące dodatkowe preferencje:

  • Wyróżnianie indeksu UV
  • Uwzględnij prędkość wiatru

Zachowaj ostateczną odpowiedź jasną i łatwą do odczytania.

Poniższa tabela zawiera podsumowanie obsługiwanych pomocników pasków obsługi:

Pomocnik Składnia Opis
Warunkowe {{#if value}}...{{else}}...{{/if}} Renderowanie zawartości na podstawie wartości prawdziwej lub fałszywej
Negacja {{#unless value}}...{{/unless}} Renderuj zawartość, gdy wartość jest fałszowana
Pętla {{#each array}}{{this}}{{/each}} Iteracja po elementach tablicy
Ostatnie sprawdzenie elementu {{#unless @last}}, {{/unless}} Warunkowe renderowanie separatorów między elementami pętli