Condividi tramite


Personalizzare il comportamento dell'agente in fase di esecuzione con input strutturati

È possibile personalizzare le istruzioni dell'agente in fase di esecuzione usando input strutturati. Gli input strutturati sono segnaposto definiti nell'agente usando la sintassi del modello handlebar ({{variableName}}). In fase di esecuzione si forniscono valori effettivi per personalizzare dinamicamente le istruzioni dell'agente, le configurazioni delle risorse degli strumenti e i parametri di risposta, senza creare versioni separate dell'agente per ogni configurazione.

In questo articolo vengono illustrate le operazioni seguenti:

  • Definire input strutturati in una definizione dell'agente
  • Usare i modelli di handlebar nelle istruzioni dell'agente
  • Configurare dinamicamente le risorse degli strumenti, ad esempio Interprete codice e Ricerca file
  • Passare i valori di input strutturati durante l'esecuzione tramite la Responses API.

Prerequisiti

  • Ambiente di agenti base o standard.
  • Pacchetto SDK più recente per la lingua. Vedere la guida introduttiva per la procedura di installazione.
  • Credenziali di Azure configurate per l'autenticazione , ad esempio DefaultAzureCredential.
  • URL dell'endpoint del progetto Foundry e nome della distribuzione del modello.

Che cosa sono gli input strutturati?

Gli input strutturati usano la sintassi del modello della barra dei gestori ({{variableName}}) per creare definizioni di agenti con parametri. Gli schemi di input vengono definiti nella definizione structured_inputsdell'agente in , in cui ogni input ha un nome, una descrizione, un tipo e un valore predefinito facoltativo. In fase di esecuzione, specificare i valori effettivi che sostituiscono i segnaposto del modello prima che l'agente elabori la richiesta.

Gli input strutturati supportano due categorie di override:

  • Override delle istruzioni: parametrizzare le istruzioni dell'agente, le istruzioni a livello di risposta e i messaggi dello sviluppatore o del sistema.
  • Override delle risorse degli strumenti: configurare dinamicamente le proprietà degli strumenti in fase di esecuzione, tra cui:
    • ID store vettoriale di ricerca file
    • ID e contenitori dei file dell'interprete del codice
    • URL e intestazioni del server MCP (Model Context Protocol)

Per i campi di matrice come file_ids e vector_store_ids, il sistema rimuove automaticamente i valori di stringa vuoti in fase di esecuzione. Questa funzionalità abilita i conteggi di input flessibili: definire più slot di modello del necessario e lasciare vuoti quelli inutilizzati.

Proprietà di input strutturate supportate

Nella tabella seguente sono elencate le proprietà di definizione dell'agente che supportano i modelli di handlebar:

Categoria Proprietà Descrizione
Istruzioni Agente instructions Testo delle istruzioni a livello agente
Istruzioni Risposta instructions Istruzioni passate nella richiesta API di risposte
Istruzioni Messaggio di sistema/sviluppatore content Contenuto del messaggio nella matrice di input
Ricerca file vector_store_ids Array di ID di archiviazione vettoriali (valori vuoti rimossi)
Interprete di codice container (stringa) ID contenitore per un contenitore preconfigurato
Interprete di codice container.file_ids (matrice) ID file in un contenitore automatizzato (valori vuoti rimossi)
MCP server_label Etichetta per il server MCP
MCP server_url URL per l'endpoint del server MCP
MCP headers (valori) Valori di intestazione HTTP come coppie chiave-valore

Usare input strutturati con le istruzioni dell'agente

L'uso più semplice degli input strutturati consiste nel parametrizzare le istruzioni dell'agente. Definire i modelli di handlebar nel instructions campo e specificare i valori in fase di esecuzione. Questo approccio consente di personalizzare il comportamento dell'agente per utenti o contesti diversi senza creare più versioni dell'agente.

Gli esempi seguenti creano un agente le cui istruzioni includono dettagli specifici dell'utente e quindi forniscono tali valori durante la creazione di una risposta.

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)

Output previsto

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?

L'agente sostituisce i segnaposto {{userName}} e {{userRole}} nelle istruzioni con "Alice Smith" e "Senior Developer" prima di elaborare la richiesta.

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

Output previsto

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?

Il StructuredInputs dizionario nella definizione dell'agente mappa i nomi dei modelli ai relativi schemi. In fase di esecuzione, usare il Patch.Set metodo su CreateResponseOptions per fornire i valori effettivi tramite il $.structured_inputs percorso 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);

Output previsto

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?

La definizione dell'agente usa structured_inputs per dichiarare gli schemi del modello. In fase di esecuzione, passare i valori effettivi nel body parametro insieme a agent_reference.

Aggiungi la dipendenza a pom.xml:

<dependency>
    <groupId>com.azure</groupId>
    <artifactId>azure-ai-agents</artifactId>
    <version>2.0.0</version>
</dependency>
import com.azure.ai.agents.AgentsClient;
import com.azure.ai.agents.AgentsClientBuilder;
import com.azure.ai.agents.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());
    }
}

Output previsto

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 usa StructuredInputDefinition per lo schema dell'agente e Map<String, BinaryData> per i valori di runtime passati tramite AzureCreateResponseOptions.

Creare un agente con input strutturati

curl -X POST "$FOUNDRY_PROJECT_ENDPOINT/agents?api-version=v1" \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $AGENT_TOKEN" \
  -d '{
    "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"
        }
      }
    }
  }'

Creare una risposta con valori di input strutturati

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

L'oggetto della definizione dell'agente structured_inputs dichiara gli schemi con descrizioni e valori predefiniti. La richiesta di risposta structured_inputs fornisce i valori effettivi di runtime che sostituiscono i modelli {{userName}} e {{userRole}}.

Usare input strutturati con l'interprete del codice

Usando gli input strutturati, è possibile configurare in modo dinamico i file e i contenitori usati dallo strumento Interprete di codice in fase di esecuzione. Definire i modelli di template handlebar nelle proprietà file_ids o container dello strumento e quindi specificare gli ID effettivi durante la creazione di una risposta.

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)

Output previsto

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

Il segnaposto {{analysis_file_id}} nella matrice file_ids dello strumento viene sostituito dal file ID file effettivo in fase di esecuzione. Usando questo approccio, è possibile riutilizzare la stessa definizione dell'agente con file diversi per ogni richiesta.

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

Output previsto

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

Output previsto

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

Output previsto

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

Creare un agente con file di interprete del codice dinamico

curl -X POST "$FOUNDRY_PROJECT_ENDPOINT/agents?api-version=v1" \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $AGENT_TOKEN" \
  -d '{
    "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"}
        }
      }
    }
  }'

Creare una risposta con l'ID file

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

Il {{analysis_file_id}} template in file_ids è sostituito con l'ID effettivo del file al momento dell'esecuzione. È possibile definire più segnaposto per l'ID del file e lasciare vuoti quelli inutilizzati. I valori vuoti vengono rimossi automaticamente dalla matrice.

Usando gli input strutturati, è possibile configurare in modo dinamico il vettore in cui vengono archiviate le query dello strumento Ricerca file in fase di esecuzione. Definire i segnaposto del modello nella matrice vector_store_ids, quindi specificare gli ID store vettoriali effettivi durante la creazione di una risposta.

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)

Output previsto

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

Il segnaposto {{vector_store_id}} viene sostituito con l'ID store vettoriale effettivo in fase di esecuzione. È possibile definire più segnaposto di archiviazione vettoriale per abilitare knowledge base stratificate o specifiche al contesto.

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

Output previsto

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

Output previsto

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

Output previsto

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

Creare un agente con store vettoriali dinamici per la ricerca di file

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

Creare una risposta con l'ID dell'archivio vettoriale

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

Questo esempio combina un archivio vettoriale statico (vs_base_kb) con uno dinamico ({{tier_specific_kb}}). Il segnaposto del modello viene sostituito in fase di esecuzione e il processo rimuove automaticamente tutti i valori stringa vuoti nella matrice.

Usare input strutturati con server MCP

Usando input strutturati, è possibile configurare in modo dinamico le connessioni al server MCP in fase di esecuzione. È possibile impostare l'URL del server, le intestazioni di autenticazione e l'etichetta del server. Usando questo approccio, una singola definizione di agente può connettersi a server MCP diversi a seconda del contesto.

Il codice JSON seguente mostra il corpo della richiesta per l'operazione Create Agent Version (POST /agents?api-version=v1). La definizione dell'agente include le proprietà degli strumenti MCP con segnaposto del modello 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": {
          "Authorization": "{{auth_token}}",
          "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"}
      },
      "auth_token": {
        "description": "Authentication token",
        "required": true,
        "schema": {"type": "string"}
      },
      "project_id": {
        "description": "Project identifier",
        "required": true,
        "schema": {"type": "string"}
      }
    }
  }
}

In fase di esecuzione, specificare i valori di configurazione del server effettivi nel corpo della richiesta per l'operazione 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",
    "auth_token": "Bearer ghp_xxxxxxxxxxxx",
    "project_id": "proj_12345"
  }
}

I modelli SDK per gli input strutturati MCP seguono lo stesso approccio illustrato negli esempi precedenti. Definire i segnaposto del modello nelle proprietà dello strumento MCP, dichiarare gli schemi di input strutturati nella definizione dell'agente e specificare i valori in fase di esecuzione.

L'esempio Python seguente illustra il modello completo:

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={"Authorization": "{{auth_token}}", "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"},
            ),
            "auth_token": StructuredInputDefinition(
                description="Authentication token", 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",
            "auth_token": "Bearer ghp_xxxxxxxxxxxx",
            "project_id": "proj_12345",
        },
    },
)
print(response.output_text)

Per altre informazioni sulla connessione ai server MCP, vedere Connettere gli agenti ai server MCP.

Usare input strutturati nell'API Risposte

È possibile usare i modelli di handlebar direttamente nelle chiamate API Risposte senza definirli nella definizione dell'agente. Questo approccio funziona per le istruzioni a livello di risposta e per i messaggi di sistema o sviluppatore nella matrice di input.

Istruzioni a livello di risposta con input strutturati

Passare input strutturati insieme a instructions in una richiesta di risposta per parametrizzare il prompt del sistema.

{
  "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"
}

Messaggi di sistema e di sviluppo con input strutturati

Usare i modelli handlebar nel contenuto dei messaggi del sistema e degli sviluppatori per inserire valori di runtime nel contesto della conversazione:

{
  "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"
}

Nel codice SDK passare questi valori usando gli stessi extra_body modelli (Python), body (TypeScript) o AzureCreateResponseOptions (Java/C#) illustrati negli esempi precedenti.

L'esempio Python seguente illustra come usare istruzioni a livello di risposta con input strutturati:

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)

Sintassi avanzata dei modelli

Gli input strutturati supportano la sintassi completa dei modelli di handlebars oltre alla semplice sostituzione di variabili. È possibile usare condizionali, cicli e altri helper predefiniti per creare logica di istruzioni dinamiche all'interno di una singola definizione dell'agente.

Nell'esempio seguente viene creato un assistente meteo il cui comportamento si adatta in base agli input di runtime. Il modello di istruzioni usa {{#if}} per le sezioni condizionali e {{#each}} per scorrere un elenco di preferenze degli utenti.

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)

Con questi valori, le istruzioni risolte diventano:

Sei un assistente meteo. Fornire un riepilogo meteo utile per l'utente.

L'utente ha chiesto informazioni su: Seattle, WA

Usare le unità seguenti: Fahrenheit

Includere una breve previsione di più giorni nella risposta.

L'utente ha queste preferenze aggiuntive:

  • Evidenziare l'indice UV
  • Includere la velocità del vento

Mantenere la risposta finale chiara e facile da leggere.

La tabella seguente riepiloga gli helper di handlebar supportati:

Assistente Sintassi Descrizione
Conditional {{#if value}}...{{else}}...{{/if}} Eseguire il rendering del contenuto in base a un valore true o false
Negazione {{#unless value}}...{{/unless}} Eseguire il rendering del contenuto quando un valore non è valido
Ciclo {{#each array}}{{this}}{{/each}} Eseguire l'iterazione sugli elementi della matrice
Controllo dell'ultimo elemento {{#unless @last}}, {{/unless}} Rendere condizionalmente i separatori tra gli elementi del loop