Notitie
Voor toegang tot deze pagina is autorisatie vereist. U kunt proberen u aan te melden of de directory te wijzigen.
Voor toegang tot deze pagina is autorisatie vereist. U kunt proberen de mappen te wijzigen.
U kunt aanpassen hoe het Foundry-model van een agent aanvragen tijdens runtime verwerkt met behulp van gestructureerde invoer. Gestructureerde invoer zijn tijdelijke aanduidingen die in de agent zijn gedefinieerd met behulp van de syntaxis van de handlebarsjabloon ({{variableName}}). Tijdens runtime geeft u werkelijke waarden op om agentinstructies, hulpprogrammaresourceconfiguraties en antwoordparameters dynamisch aan te passen, zonder afzonderlijke agentversies te maken voor elke configuratie.
In dit artikel leert u het volgende:
- Gestructureerde invoer definiëren in een agentdefinitie
- Handlebarsjablonen gebruiken in agentinstructies
- Hulpprogrammabronnen zoals Code Interpreter en File Search dynamisch configureren
- Gestructureerde invoerwaarden tijdens runtime doorgeven via de Response-API
Voorwaarden
- Een basis- of standaardagentomgeving.
- Het nieuwste SDK-pakket voor uw taal. Zie de quickstart voor de installatiestappen.
- Azure inloggegevens die zijn geconfigureerd voor authenticatie (zoals
DefaultAzureCredential). - De URL van het Foundry-projecteindpunt en de naam van de modelimplementatie.
Wat zijn gestructureerde invoer?
Gestructureerde invoer maakt gebruik van de syntaxis van de handlebarsjabloon ({{variableName}}) om geparameteriseerde agentdefinities te maken. U definieert invoerschema's in de agentdefinitie onder structured_inputs, waarbij elke invoer een naam, beschrijving, type en optionele standaardwaarde heeft. Geef tijdens runtime werkelijke waarden op die de tijdelijke aanduidingen van de sjabloon vervangen voordat de agent de aanvraag verwerkt.
Gestructureerde invoer ondersteunt twee categorieën overrides:
- Instructie-overschrijvingen: Agentinstructies parameteriseren, reactieniveau instructies, en systeem- of ontwikkelaarsberichten.
-
Resource-overschrijvingen voor tools: Dynamisch configureren van tool-eigenschappen tijdens uitvoering, waaronder:
- Bestandszoek-vectoropslag-ID's
- Code interpreter bestandidentificaties en containers
- MCP-server-URL's en headers van het Model Context Protocol
Voor matrixvelden zoals file_ids en vector_store_ids, verwijdert het systeem automatisch lege tekenreekswaarden tijdens runtime. Deze functie maakt flexibele invoeraantallen mogelijk: definieer meer sjabloonsites dan nodig is en laat ongebruikte sites leeg.
Ondersteunde gestructureerde invoereigenschappen
De volgende tabel bevat de eigenschappen van agentdefinities die ondersteuning bieden voor handlebarsjablonen:
| Categorie | Eigenschap | Beschrijving |
|---|---|---|
| Instructies | Agent instructions |
Instructietekst op agentniveau |
| Instructies | Reactie instructions |
Instructies die zijn doorgegeven in de api-aanvraag voor antwoorden |
| Instructies | Systeem-/ontwikkelaarsbericht content |
Berichtinhoud in de invoermatrix |
| Zoeken naar bestanden | vector_store_ids |
Matrix van vectorarchief-id's (lege waarden verwijderd) |
| Code-interpreter |
container (tekenreeks) |
Container-id voor een vooraf geconfigureerde container |
| Code-interpreter |
container.file_ids (array) |
Bestands-id's in een automatische container waarbij lege waarden zijn verwijderd |
| MCP | server_label |
Label voor de MCP-server |
| MCP | server_url |
URL voor het MCP-servereindpunt |
| MCP |
headers (waarden) |
HTTP-headerwaarden als sleutel-waardeparen |
Gestructureerde invoer gebruiken met agentinstructies
Het eenvoudigste gebruik van gestructureerde invoer is het parameteriseren van agentinstructies. Definieer handlebarsjablonen in het instructions veld en geef waarden op tijdens runtime. Met deze benadering kunt u agentgedrag aanpassen voor verschillende gebruikers of contexten zonder meerdere agentversies te maken.
In de volgende voorbeelden wordt een agent gemaakt waarvan de instructies gebruikersspecifieke gegevens bevatten en deze waarden vervolgens opgeven bij het maken van een antwoord.
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)
Verwachte uitvoer
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?
De agent vervangt de {{userName}} en {{userRole}} tijdelijke aanduidingen in de instructies door 'Alice Smith' en 'Senior Developer' voordat de aanvraag wordt verwerkt.
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);
Verwachte uitvoer
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?
De StructuredInputs woordenlijst in de definitie van de agent wijst sjabloonnamen toe aan hun schema's. Gebruik tijdens runtime de Patch.Set methode om CreateResponseOptions de werkelijke waarden via het $.structured_inputs JSON-pad op te geven.
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);
Verwachte uitvoer
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?
De agentdefinitie gebruikt structured_inputs om de sjabloonschema's te declareren. Geef tijdens runtime de werkelijke waarden in de body parameter door naast de agent_reference.
Voeg de afhankelijkheid toe aan uw 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());
}
}
Verwachte uitvoer
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?
De Java SDK gebruikt StructuredInputDefinition voor het agentschema en Map<String, BinaryData> voor de runtime-waarden die worden doorgegeven via AzureCreateResponseOptions.
Een agent maken met gestructureerde invoer
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"
}
}
}
}'
Een antwoord maken met gestructureerde invoerwaarden
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"
}
}'
Het object van structured_inputs de agentdefinitie declareert de schema's met beschrijvingen en standaardwaarden. De antwoordaanvraag structured_inputs bevat de werkelijke runtimewaarden die de {{userName}} en {{userRole}} sjablonen vervangen.
Gestructureerde invoer gebruiken met Code Interpreter
Met behulp van gestructureerde invoer kunt u dynamisch configureren welke bestanden en containers het hulpprogramma Code Interpreter tijdens runtime gebruikt. Definieer handlebarsjablonen in de eigenschappen van de tool en geef vervolgens de feitelijke ID's op bij het maken van een reactie.
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)
Verwachte uitvoer
File uploaded (id: <file-id>)
The sum of x in numbers.csv is 6.
De {{analysis_file_id}} tijdelijke aanduiding in de matrix van het file_ids hulpprogramma wordt vervangen door de werkelijke bestands-id tijdens uitvoering. Met deze methode kunt u dezelfde agentdefinitie opnieuw gebruiken met verschillende bestanden voor elke aanvraag.
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);
Verwachte uitvoer
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);
Verwachte uitvoer
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());
}
}
Verwachte uitvoer
Response: The sum of x in numbers.csv is 6.
Een agent maken met dynamische Code Interpreter-bestanden
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"}
}
}
}
}'
Een antwoord maken met de bestands-id
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"
}'
De {{analysis_file_id}} sjabloon in file_ids wordt vervangen door de daadwerkelijke bestands-ID tijdens de uitvoeringstijd. U kunt meerdere tijdelijke aanduidingen voor bestands-id's definiëren en ongebruikte aanduidingen leeg laten. Lege waarden worden automatisch uit de matrix verwijderd.
Gestructureerde invoer gebruiken met Bestandszoekopdrachten
Met behulp van gestructureerde invoer kunt u dynamisch configureren welke vector de query's van het hulpprogramma Voor het zoeken van bestanden tijdens runtime opslaat. Definieer tijdelijke aanduidingen voor sjablonen in de vector_store_ids array en geef vervolgens werkelijke vectoropslag-ID's op bij het maken van een antwoord.
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)
Verwachte uitvoer
Vector store created (id: <vector-store-id>)
Based on the product information, Contoso offers several product lines including...
De {{vector_store_id}} placeholder wordt vervangen door de werkelijke vectoropslag-ID tijdens runtime. U kunt meerdere tijdelijke aanduidingen voor vectoropslag definiëren om gelaagde of contextspecifieke kennisbanken in te schakelen.
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);
Verwachte uitvoer
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);
Verwachte uitvoer
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());
}
}
Verwachte uitvoer
Response: Based on the product information, Contoso offers several product lines including...
Een agent maken met dynamische bestandszoekvectorarchieven
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"}
}
}
}
}'
Een antwoord maken met de vector store-id
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"
}
}'
In dit voorbeeld wordt een statisch vectorarchief (vs_base_kb) gecombineerd met een dynamische ({{tier_specific_kb}}). De plaatsaanduiding voor de sjabloon wordt tijdens uitvoeringstijd vervangen en tijdens het proces worden alle lege tekenreekswaarden in de array automatisch verwijderd.
Gestructureerde invoer gebruiken met MCP-servers
Door gestructureerde invoer te gebruiken, kunt u tijdens runtime dynamisch MCP-serververbindingen configureren. U kunt de server-URL, verificatieheaders en serverlabel instellen. Door deze methode te gebruiken, kan één agentdefinitie verbinding maken met verschillende MCP-servers, afhankelijk van de context.
In de volgende JSON ziet u de aanvraagbody voor de bewerking Agentversie maken (POST /agents?api-version=v1). De agentdefinitie bevat de eigenschappen van het MCP-hulpprogramma met tijdelijke aanduidingen voor handlebar-sjablonen:
{
"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"}
}
}
}
}
Geef tijdens runtime de werkelijke serverconfiguratiewaarden op in de aanvraagbody voor de bewerking Antwoord maken (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"
}
}
De SDK-patronen voor gestructureerde MCP-invoer volgen dezelfde benadering als in de vorige voorbeelden. Definieer de tijdelijke aanduidingen voor de sjabloon in de eigenschappen van het MCP-hulpprogramma, declareer de gestructureerde invoerschema's in de agentdefinitie en geef de waarden op tijdens runtime.
In het volgende Python voorbeeld ziet u het volledige patroon:
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)
Zie Agents verbinden met MCP-servers voor meer informatie over het maken van verbinding met MCP-servers.
Gestructureerde invoer gebruiken in de Antwoorden-API
U kunt handlebarsjablonen rechtstreeks gebruiken in antwoorden-API-aanroepen zonder deze te definiëren in de agentdefinitie. Deze aanpak werkt voor instructies op antwoordniveau en voor systeem- of ontwikkelaarsberichten in de invoermatrix.
Instructies op antwoordniveau met gestructureerde invoer
Geef gestructureerde invoer door bij een antwoordaanvraag met instructions om de systeemprompt te parameteriseren:
{
"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"
}
Systeem- en ontwikkelaarsberichten met gestructureerde invoer
Gebruik handlebarsjablonen in systeem- en berichtinhoud voor ontwikkelaars om runtime-waarden in de gesprekscontext te injecteren:
{
"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"
}
Geef in SDK-code deze waarden door met behulp van dezelfde extra_body (Python), body (TypeScript) of AzureCreateResponseOptions (Java/C#) die in de vorige voorbeelden worden weergegeven.
In het volgende Python voorbeeld ziet u hoe u instructies op antwoordniveau gebruikt met gestructureerde invoer:
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)
Geavanceerde sjabloonsyntaxis
Gestructureerde invoer biedt ondersteuning voor volledige syntaxis van handlebars-sjablonen , naast eenvoudige vervanging van variabelen. U kunt voorwaardelijke voorwaarden, lussen en andere ingebouwde helpers gebruiken om dynamische instructielogica te maken binnen één agentdefinitie.
In het volgende voorbeeld wordt een weerassistent gemaakt waarvan het gedrag wordt aangepast op basis van runtime-invoer. De instructiessjabloon gebruikt {{#if}} voor voorwaardelijke secties en {{#each}} om een lijst met gebruikersvoorkeuren te herhalen:
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)
Met deze waarden worden de opgeloste instructies:
Je bent een weerassistent. Geef een handig weeroverzicht voor de gebruiker.
De gebruiker heeft gevraagd over: Seattle, WA
Gebruik de volgende eenheden: Fahrenheit
Neem een korte prognose van meerdere dagen op in uw antwoord.
De gebruiker heeft deze aanvullende voorkeuren:
- UV-index markeren
- Inclusief windsnelheid
Houd het laatste antwoord duidelijk en gemakkelijk te lezen.
De volgende tabel bevat een overzicht van de ondersteunde helpers voor handlebars:
| Assistent | Syntaxis | Beschrijving |
|---|---|---|
| Voorwaardelijke | {{#if value}}...{{else}}...{{/if}} |
Inhoud weergeven op basis van een waarheids- of falsywaarde |
| Ontkenning | {{#unless value}}...{{/unless}} |
Inhoud weergeven wanneer een waarde falsy is |
| Lus | {{#each array}}{{this}}{{/each}} |
Herhalen over matrixitems |
| Laatste itemcontrole | {{#unless @last}}, {{/unless}} |
Voorwaardelijk scheidingstekens renderen tussen items in een lus |