Il servizio Microsoft Foundry Agent usa tre componenti di runtime di base, ovvero agenti, conversazioni e risposte, per attivare le interazioni con stato e a più turni. Un agente definisce il modello, le istruzioni e gli strumenti da usare. Una conversazione mantiene la cronologia tra turni. Una risposta è l'output generato dall'agente quando elabora l'input.
Questo articolo illustra in dettaglio ogni componente e illustra come usarli insieme nel codice. Si apprenderà come creare un agente, avviare una conversazione, generare risposte (con o senza un agente), aggiungere messaggi di completamento e trasmettere i risultati, con esempi in Python, C#, JavaScript, JavaScript e API REST.
Come interagiscono i componenti di runtime
Quando si lavora con un agente, si segue un modello coerente:
-
Creare un agente: definire un agente per iniziare a inviare messaggi e ricevere risposte.
-
Creare una conversazione (facoltativa): usare una conversazione per mantenere la cronologia tra turni. Se non si usa una conversazione, portare avanti il contesto usando l'output di una risposta precedente.
-
Generare una risposta: l'agente elabora gli elementi di input nella conversazione ed eventuali istruzioni fornite nella richiesta. L'agente potrebbe aggiungere elementi alla conversazione.
-
Controllare lo stato della risposta: monitorare la risposta fino al termine(in particolare in modalità streaming o in background).
-
Recuperare la risposta: visualizzare la risposta generata all'utente.
Il diagramma seguente illustra come questi componenti interagiscono in un tipico agente loop.
Si specifica l'input dell'utente (e facoltativamente la cronologia delle conversazioni), il servizio genera una risposta (incluse le chiamate degli strumenti quando configurate) e gli elementi risultanti possono essere riutilizzati come contesto per il turno successivo.
Prerequisiti
Per eseguire gli esempi in questo articolo, è necessario:
pip install "azure-ai-projects>=2.0.0"
pip install azure-identity
dotnet add package Azure.AI.Projects --prerelease
dotnet add package Azure.AI.Projects.OpenAI --prerelease
dotnet add package Azure.Identity
npm install @azure/ai-projects@2.0.0
npm install @azure/identity
<dependency>
<groupId>com.azure</groupId>
<artifactId>azure-ai-agents</artifactId>
<version>2.0.0-beta.2</version>
</dependency>
<dependency>
<groupId>com.azure</groupId>
<artifactId>azure-identity</artifactId>
<version>1.15.4</version>
</dependency>
Creare un agente
Un agente è una definizione di orchestrazione persistente che combina modelli di intelligenza artificiale, istruzioni, codice, strumenti, parametri e controlli facoltativi di sicurezza o governance.
Archiviare gli agenti come asset nominati e con versione in Microsoft Foundry. Durante la generazione della risposta, la definizione dell'agente funziona con la cronologia di interazione (conversazione o risposta precedente) per elaborare e rispondere all'input dell'utente.
Nell'esempio seguente viene creato un agente prompt con un nome, un modello e istruzioni. Usare il client di progetto per la creazione e il controllo delle versioni dell'agente.
from azure.identity import DefaultAzureCredential
from azure.ai.projects import AIProjectClient
from azure.ai.projects.models import PromptAgentDefinition
# Format: "https://resource_name.services.ai.azure.com/api/projects/project_name"
PROJECT_ENDPOINT = "your_project_endpoint"
# Create project client to call Foundry API
project = AIProjectClient(
endpoint=PROJECT_ENDPOINT,
credential=DefaultAzureCredential(),
)
# Create a prompt agent
agent = project.agents.create_version(
agent_name="my-agent",
definition=PromptAgentDefinition(
model="gpt-5-mini",
instructions="You are a helpful assistant.",
),
)
print(f"Agent: {agent.name}, Version: {agent.version}")
using Azure.Identity;
using Azure.AI.Projects;
// Format: "https://resource_name.services.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 a prompt agent
var agent = await projectClient.Agents
.CreateAgentVersionAsync(
agentName: "my-agent",
options: new(
new PromptAgentDefinition("gpt-5-mini")
{
Instructions = "You are a helpful assistant.",
}));
Console.WriteLine($"Agent: {agent.Value.Name}, Version: {agent.Value.Version}");
import { DefaultAzureCredential } from "@azure/identity";
import { AIProjectClient } from "@azure/ai-projects";
// Format: "https://resource_name.services.ai.azure.com/api/projects/project_name"
const PROJECT_ENDPOINT = "your_project_endpoint";
// Create project client to call Foundry API
const project = new AIProjectClient(PROJECT_ENDPOINT, new DefaultAzureCredential());
// Create a prompt agent
const agent = await project.agents.createVersion(
"my-agent",
{
kind: "prompt",
model: "gpt-5-mini",
instructions: "You are a helpful assistant.",
},
);
console.log(`Agent: ${agent.name}, Version: ${agent.version}`);
import com.azure.ai.agents.AgentsClientBuilder;
import com.azure.ai.agents.AgentsClient;
import com.azure.ai.agents.models.PromptAgentDefinition;
import com.azure.identity.DefaultAzureCredentialBuilder;
// Format: "https://resource_name.services.ai.azure.com/api/projects/project_name"
String projectEndpoint = "your_project_endpoint";
// Create agents client to call Foundry API
AgentsClient agentsClient = new AgentsClientBuilder()
.credential(new DefaultAzureCredentialBuilder().build())
.endpoint(projectEndpoint)
.buildAgentsClient();
// Create a prompt agent
PromptAgentDefinition definition = new PromptAgentDefinition("gpt-5-mini");
definition.setInstructions("You are a helpful assistant.");
var agent = agentsClient.createAgentVersion("my-agent", definition);
System.out.println("Agent: " + agent.getName() + ", Version: " + agent.getVersion());
# Configuration
ENDPOINT="https://{resource_name}.services.ai.azure.com/api/projects/{project_name}"
ACCESS_TOKEN="$(az account get-access-token --resource https://ai.azure.com/ --query accessToken -o tsv)"
# Create a prompt agent
curl -X POST "${ENDPOINT}/agents?api-version=v1" \
-H "Authorization: Bearer ${ACCESS_TOKEN}" \
-H "Content-Type: application/json" \
-d '{
"name": "my-agent",
"definition": {
"kind": "prompt",
"model": "gpt-5-mini",
"instructions": "You are a helpful assistant."
}
}'
Annotazioni
Gli agenti vengono ora identificati usando il nome dell'agente e la versione dell'agente. Non hanno più un GUID chiamato AgentID .
Per altri tipi di agente (flusso di lavoro, ospitato), vedere Ciclo di vita di sviluppo dell'agente.
Gli strumenti estendono le operazioni che un agente può eseguire oltre la generazione di testo. Quando si collegano strumenti a un agente, l'agente può chiamare servizi esterni, eseguire codice, cercare file e accedere alle origini dati durante la generazione della risposta, usando strumenti come la ricerca Web o la chiamata di funzioni.
È possibile collegare uno o più strumenti quando si crea un agente. Durante la generazione della risposta, l'agente decide se chiamare uno strumento in base all'input dell'utente e alle relative istruzioni. Nell'esempio seguente viene creato un agente con uno strumento di ricerca Web collegato.
from azure.identity import DefaultAzureCredential
from azure.ai.projects import AIProjectClient
from azure.ai.projects.models import PromptAgentDefinition, WebSearchTool
PROJECT_ENDPOINT = "your_project_endpoint"
project = AIProjectClient(
endpoint=PROJECT_ENDPOINT,
credential=DefaultAzureCredential(),
)
# Create an agent with a web search tool
agent = project.agents.create_version(
agent_name="my-tool-agent",
definition=PromptAgentDefinition(
model="gpt-5-mini",
instructions="You are a helpful assistant that can search the web.",
tools=[WebSearchTool()],
),
)
print(f"Agent: {agent.name}, Version: {agent.version}")
using Azure.Identity;
using Azure.AI.Projects;
var projectEndpoint = "your_project_endpoint";
AIProjectClient projectClient = new(
endpoint: new Uri(projectEndpoint),
tokenProvider: new DefaultAzureCredential());
// Create an agent with a web search tool
var agent = await projectClient.Agents
.CreateAgentVersionAsync(
agentName: "my-tool-agent",
options: new(
new PromptAgentDefinition("gpt-5-mini")
{
Instructions = "You are a helpful assistant that can search the web.",
Tools = { ResponseTool.CreateWebSearchTool() },
}));
Console.WriteLine($"Agent: {agent.Value.Name}, Version: {agent.Value.Version}");
import { DefaultAzureCredential } from "@azure/identity";
import { AIProjectClient } from "@azure/ai-projects";
const PROJECT_ENDPOINT = "your_project_endpoint";
const project = new AIProjectClient(PROJECT_ENDPOINT, new DefaultAzureCredential());
// Create an agent with a web search tool
const agent = await project.agents.createVersion(
"my-tool-agent",
{
kind: "prompt",
model: "gpt-5-mini",
instructions: "You are a helpful assistant that can search the web.",
tools: [{ type: "web_search_preview" }],
},
);
console.log(`Agent: ${agent.name}, Version: ${agent.version}`);
import com.azure.ai.agents.AgentsClientBuilder;
import com.azure.ai.agents.AgentsClient;
import com.azure.ai.agents.models.PromptAgentDefinition;
import com.azure.ai.agents.models.WebSearchPreviewTool;
import com.azure.identity.DefaultAzureCredentialBuilder;
import java.util.Collections;
String projectEndpoint = "your_project_endpoint";
AgentsClient agentsClient = new AgentsClientBuilder()
.credential(new DefaultAzureCredentialBuilder().build())
.endpoint(projectEndpoint)
.buildAgentsClient();
// Create an agent with a web search tool
WebSearchPreviewTool webSearchTool = new WebSearchPreviewTool();
PromptAgentDefinition definition = new PromptAgentDefinition("gpt-5-mini");
definition.setInstructions("You are a helpful assistant that can search the web.");
definition.setTools(Collections.singletonList(webSearchTool));
var agent = agentsClient.createAgentVersion("my-tool-agent", definition);
System.out.println("Agent: " + agent.getName() + ", Version: " + agent.getVersion());
ENDPOINT="https://{resource_name}.services.ai.azure.com/api/projects/{project_name}"
ACCESS_TOKEN="$(az account get-access-token --resource https://ai.azure.com/ --query accessToken -o tsv)"
# Create an agent with a web search tool
curl -X POST "${ENDPOINT}/agents?api-version=v1" \
-H "Authorization: Bearer ${ACCESS_TOKEN}" \
-H "Content-Type: application/json" \
-d '{
"name": "my-tool-agent",
"definition": {
"kind": "prompt",
"model": "gpt-5-mini",
"instructions": "You are a helpful assistant that can search the web.",
"tools": [{ "type": "web_search_preview" }]
}
}'
Per l'elenco completo degli strumenti disponibili, vedere la panoramica degli strumenti. Per le procedure consigliate, vedere Procedure consigliate per l'uso degli strumenti.
Generare risposte
La generazione della risposta richiama l'agente. L'agente usa la configurazione e la cronologia fornita (conversazione o risposta precedente) per eseguire attività chiamando modelli e strumenti. Nell'ambito della generazione della risposta, l'agente aggiunge elementi alla conversazione.
È anche possibile generare una risposta senza definire un agente. In questo caso, è possibile specificare tutte le configurazioni direttamente nella richiesta e usarle solo per tale risposta. Questo approccio è utile per scenari semplici con strumenti minimi.
Inoltre, è possibile fare il fork della conversazione al primo ID risposta o al secondo ID risposta.
Generare una risposta con un agente
L'esempio seguente genera una risposta usando un riferimento all'agente, quindi invia una domanda di completamento usando la risposta precedente come contesto.
from azure.identity import DefaultAzureCredential
from azure.ai.projects import AIProjectClient
# Format: "https://resource_name.services.ai.azure.com/api/projects/project_name"
PROJECT_ENDPOINT = "your_project_endpoint"
AGENT_NAME = "your_agent_name"
# Create clients to call Foundry API
project = AIProjectClient(
endpoint=PROJECT_ENDPOINT,
credential=DefaultAzureCredential(),
)
openai = project.get_openai_client()
# Generate a response using the agent
response = openai.responses.create(
extra_body={
"agent_reference": {
"name": AGENT_NAME,
"type": "agent_reference",
}
},
input="What is the largest city in France?",
)
print(response.output_text)
# Ask a follow-up question using the previous response
follow_up = openai.responses.create(
extra_body={
"agent_reference": {
"name": AGENT_NAME,
"type": "agent_reference",
}
},
previous_response_id=response.id,
input="What is the population of that city?",
)
print(follow_up.output_text)
using Azure.Identity;
using Azure.AI.Projects;
using Azure.AI.Projects.OpenAI;
// Format: "https://resource_name.services.ai.azure.com/api/projects/project_name"
var projectEndpoint = "your_project_endpoint";
var agentName = "your_agent_name";
// Create project client to call Foundry API
AIProjectClient projectClient = new(
endpoint: new Uri(projectEndpoint),
tokenProvider: new DefaultAzureCredential());
// Generate a response using the agent
ResponsesClient responsesClient
= projectClient.OpenAI.GetProjectResponsesClientForAgent(
new AgentReference { Name = agentName });
ResponseResult response = await responsesClient.CreateResponseAsync(
"What is the largest city in France?");
Console.WriteLine(response.GetOutputText());
// Ask a follow-up question using the previous response
ResponseResult followUp = await responsesClient.CreateResponseAsync(
"What is the population of that city?",
previousResponseId: response.Id);
Console.WriteLine(followUp.GetOutputText());
import { DefaultAzureCredential } from "@azure/identity";
import { AIProjectClient } from "@azure/ai-projects";
// Format: "https://resource_name.services.ai.azure.com/api/projects/project_name"
const PROJECT_ENDPOINT = "your_project_endpoint";
const AGENT_NAME = "your_agent_name";
// Create clients to call Foundry API
const project = new AIProjectClient(PROJECT_ENDPOINT, new DefaultAzureCredential());
const openai = await project.getOpenAIClient();
// Generate a response using the agent
const response = await openai.responses.create({
input: "What is the largest city in France?",
agent_reference: {
name: AGENT_NAME,
type: "agent_reference",
},
});
console.log(response.output_text);
// Ask a follow-up question using the previous response
const followUp = await openai.responses.create({
input: "What is the population of that city?",
previous_response_id: response.id,
agent_reference: {
name: AGENT_NAME,
type: "agent_reference",
},
});
console.log(followUp.output_text);
import com.azure.ai.agents.*;
import com.azure.ai.agents.models.AgentReference;
import com.azure.identity.DefaultAzureCredentialBuilder;
// Format: "https://resource_name.services.ai.azure.com/api/projects/project_name"
String projectEndpoint = "your_project_endpoint";
String agentName = "your_agent_name";
// Create clients to call Foundry API
AgentsClientBuilder builder = new AgentsClientBuilder()
.credential(new DefaultAzureCredentialBuilder().build())
.endpoint(projectEndpoint);
ResponsesClient responsesClient = builder.buildResponsesClient();
// Generate a response using the agent
AgentReference agentRef = new AgentReference(agentName);
Response response = responsesClient.createWithAgent(
agentRef,
ResponseCreateParams.builder()
.input("What is the largest city in France?"));
System.out.println(response.output());
// Ask a follow-up question using the previous response
Response followUp = responsesClient.createWithAgent(
agentRef,
ResponseCreateParams.builder()
.input("What is the population of that city?")
.previousResponseId(response.id()));
System.out.println(followUp.output());
# Configuration
ENDPOINT="https://{resource_name}.services.ai.azure.com/api/projects/{project_name}"
ACCESS_TOKEN="$(az account get-access-token --resource https://ai.azure.com/ --query accessToken -o tsv)"
AGENT_NAME="your_agent_name"
# Generate a response using an agent
RESPONSE=$(curl -s -X POST "${ENDPOINT}/openai/v1/responses" \
-H "Authorization: Bearer ${ACCESS_TOKEN}" \
-H "Content-Type: application/json" \
-d '{
"input": "What is the largest city in France?",
"agent_reference": {
"name": "'"${AGENT_NAME}"'",
"type": "agent_reference"
}
}')
RESPONSE_ID=$(echo "$RESPONSE" | jq -r '.id')
# Ask a follow-up question using the previous response
curl -X POST "${ENDPOINT}/openai/v1/responses" \
-H "Authorization: Bearer ${ACCESS_TOKEN}" \
-H "Content-Type: application/json" \
-d '{
"input": "What is the population of that city?",
"previous_response_id": "'"${RESPONSE_ID}"'",
"agent_reference": {
"name": "'"${AGENT_NAME}"'",
"type": "agent_reference"
}
}'
Quando un agente usa strumenti durante la generazione della risposta, l'output della risposta contiene elementi di chiamata dello strumento insieme al messaggio finale. È possibile eseguire l'iterazione response.output per esaminare ogni elemento e visualizzare chiamate di strumenti, ad esempio ricerche Web, chiamate di funzione o ricerche di file, prima di stampare la risposta di testo.
from azure.identity import DefaultAzureCredential
from azure.ai.projects import AIProjectClient
PROJECT_ENDPOINT = "your_project_endpoint"
AGENT_NAME = "your_agent_name"
project = AIProjectClient(
endpoint=PROJECT_ENDPOINT,
credential=DefaultAzureCredential(),
)
openai = project.get_openai_client()
response = openai.responses.create(
extra_body={
"agent_reference": {
"name": AGENT_NAME,
"type": "agent_reference",
}
},
input="What happened in the news today?",
)
# Print each output item, including tool calls
for item in response.output:
if item.type == "web_search_call":
print(f"[Tool] Web search: status={item.status}")
elif item.type == "function_call":
print(f"[Tool] Function call: {item.name}({item.arguments})")
elif item.type == "file_search_call":
print(f"[Tool] File search: status={item.status}")
elif item.type == "message":
print(f"[Assistant] {item.content[0].text}")
using Azure.Identity;
using Azure.AI.Projects;
using Azure.AI.Projects.OpenAI;
var projectEndpoint = "your_project_endpoint";
var agentName = "your_agent_name";
AIProjectClient projectClient = new(
endpoint: new Uri(projectEndpoint),
tokenProvider: new DefaultAzureCredential());
ResponsesClient responsesClient
= projectClient.OpenAI.GetProjectResponsesClientForAgent(
new AgentReference { Name = agentName });
ResponseResult response = await responsesClient.CreateResponseAsync(
"What happened in the news today?");
// Print each output item, including tool calls
foreach (var item in response.OutputItems)
{
switch (item)
{
case ResponseWebSearchCallItem webSearch:
Console.WriteLine($"[Tool] Web search: status={webSearch.Status}");
break;
case ResponseFunctionCallItem functionCall:
Console.WriteLine($"[Tool] Function call: {functionCall.Name}({functionCall.Arguments})");
break;
case ResponseFileSearchCallItem fileSearch:
Console.WriteLine($"[Tool] File search: status={fileSearch.Status}");
break;
case ResponseOutputMessage message:
Console.WriteLine($"[Assistant] {message.Content[0].Text}");
break;
}
}
import { DefaultAzureCredential } from "@azure/identity";
import { AIProjectClient } from "@azure/ai-projects";
const PROJECT_ENDPOINT = "your_project_endpoint";
const AGENT_NAME = "your_agent_name";
const project = new AIProjectClient(PROJECT_ENDPOINT, new DefaultAzureCredential());
const openai = await project.getOpenAIClient();
const response = await openai.responses.create({
input: "What happened in the news today?",
agent_reference: {
name: AGENT_NAME,
type: "agent_reference",
},
});
// Print each output item, including tool calls
for (const item of response.output) {
switch (item.type) {
case "web_search_call":
console.log(`[Tool] Web search: status=${item.status}`);
break;
case "function_call":
console.log(`[Tool] Function call: ${item.name}(${item.arguments})`);
break;
case "file_search_call":
console.log(`[Tool] File search: status=${item.status}`);
break;
case "message":
console.log(`[Assistant] ${item.content[0].text}`);
break;
}
}
import com.azure.ai.agents.*;
import com.azure.ai.agents.models.*;
import com.azure.identity.DefaultAzureCredentialBuilder;
String projectEndpoint = "your_project_endpoint";
String agentName = "your_agent_name";
AgentsClientBuilder builder = new AgentsClientBuilder()
.credential(new DefaultAzureCredentialBuilder().build())
.endpoint(projectEndpoint);
ResponsesClient responsesClient = builder.buildResponsesClient();
AgentReference agentRef = new AgentReference(agentName);
Response response = responsesClient.createWithAgent(
agentRef,
ResponseCreateParams.builder()
.input("What happened in the news today?"));
// Print each output item, including tool calls
for (ResponseOutputItem item : response.getOutput()) {
String type = item.getType();
if ("web_search_call".equals(type)) {
System.out.println("[Tool] Web search: status=" + item.getStatus());
} else if ("function_call".equals(type)) {
System.out.println("[Tool] Function call: " + item.getName()
+ "(" + item.getArguments() + ")");
} else if ("file_search_call".equals(type)) {
System.out.println("[Tool] File search: status=" + item.getStatus());
} else if ("message".equals(type)) {
System.out.println("[Assistant] " + item.getContent().get(0).getText());
}
}
ENDPOINT="https://{resource_name}.services.ai.azure.com/api/projects/{project_name}"
ACCESS_TOKEN="$(az account get-access-token --resource https://ai.azure.com/ --query accessToken -o tsv)"
AGENT_NAME="your_agent_name"
RESPONSE=$(curl -s -X POST "${ENDPOINT}/openai/v1/responses" \
-H "Authorization: Bearer ${ACCESS_TOKEN}" \
-H "Content-Type: application/json" \
-d '{
"input": "What happened in the news today?",
"agent_reference": {
"name": "'"${AGENT_NAME}"'",
"type": "agent_reference"
}
}')
# Print each output item, including tool calls
echo "$RESPONSE" | jq -r '.output[] |
if .type == "web_search_call" then "[Tool] Web search: status=\(.status)"
elif .type == "function_call" then "[Tool] Function call: \(.name)(\(.arguments))"
elif .type == "file_search_call" then "[Tool] File search: status=\(.status)"
elif .type == "message" then "[Assistant] \(.content[0].text)"
else "[Unknown] \(.type)"
end'
Generare una risposta senza archiviare
Per impostazione predefinita, il servizio archivia la cronologia delle risposte sul lato server, in modo da poter fare riferimento previous_response_id al contesto a più turni. Se imposti store su false, il servizio non persiste la risposta. È necessario inoltrare manualmente il contesto della conversazione passando gli elementi di output precedenti come input alla richiesta successiva.
Questo approccio è utile quando è necessario il controllo completo sullo stato della conversazione, si vogliono ridurre al minimo i dati archiviati o lavorare in un ambiente di conservazione dei dati zero.
from azure.identity import DefaultAzureCredential
from azure.ai.projects import AIProjectClient
PROJECT_ENDPOINT = "your_project_endpoint"
AGENT_NAME = "your_agent_name"
project = AIProjectClient(
endpoint=PROJECT_ENDPOINT,
credential=DefaultAzureCredential(),
)
openai = project.get_openai_client()
# Generate a response without storing
response = openai.responses.create(
extra_body={
"agent_reference": {
"name": AGENT_NAME,
"type": "agent_reference",
}
},
input="What is the largest city in France?",
store=False,
)
print(response.output_text)
# Carry forward context client-side by passing previous output as input
follow_up = openai.responses.create(
extra_body={
"agent_reference": {
"name": AGENT_NAME,
"type": "agent_reference",
}
},
input=[
{"role": "user", "content": "What is the largest city in France?"},
{"role": "assistant", "content": response.output_text},
{"role": "user", "content": "What is the population of that city?"},
],
store=False,
)
print(follow_up.output_text)
using Azure.Identity;
using Azure.AI.Projects;
using Azure.AI.Projects.OpenAI;
var projectEndpoint = "your_project_endpoint";
var agentName = "your_agent_name";
AIProjectClient projectClient = new(
endpoint: new Uri(projectEndpoint),
tokenProvider: new DefaultAzureCredential());
// Generate a response without storing
ResponsesClient responsesClient
= projectClient.OpenAI.GetProjectResponsesClientForAgent(
new AgentReference { Name = agentName });
ResponseResult response = await responsesClient.CreateResponseAsync(
"What is the largest city in France?",
store: false);
Console.WriteLine(response.GetOutputText());
// Carry forward context client-side by passing previous output as input
ResponseResult followUp = await responsesClient.CreateResponseAsync(
new ResponseCreationOptions
{
Instructions = null,
Input = ResponseInput.FromItems(
new ResponseInputItem.Message
{
Role = "user",
Content = "What is the largest city in France?"
},
new ResponseInputItem.Message
{
Role = "assistant",
Content = response.GetOutputText()
},
new ResponseInputItem.Message
{
Role = "user",
Content = "What is the population of that city?"
}
),
Store = false
});
Console.WriteLine(followUp.GetOutputText());
import { DefaultAzureCredential } from "@azure/identity";
import { AIProjectClient } from "@azure/ai-projects";
const PROJECT_ENDPOINT = "your_project_endpoint";
const AGENT_NAME = "your_agent_name";
const project = new AIProjectClient(PROJECT_ENDPOINT, new DefaultAzureCredential());
const openai = await project.getOpenAIClient();
// Generate a response without storing
const response = await openai.responses.create({
input: "What is the largest city in France?",
store: false,
agent_reference: {
name: AGENT_NAME,
type: "agent_reference",
},
});
console.log(response.output_text);
// Carry forward context client-side by passing previous output as input
const followUp = await openai.responses.create({
input: [
{ role: "user", content: "What is the largest city in France?" },
{ role: "assistant", content: response.output_text },
{ role: "user", content: "What is the population of that city?" },
],
store: false,
agent_reference: {
name: AGENT_NAME,
type: "agent_reference",
},
});
console.log(followUp.output_text);
import com.azure.ai.agents.*;
import com.azure.ai.agents.models.AgentReference;
import com.azure.identity.DefaultAzureCredentialBuilder;
String projectEndpoint = "your_project_endpoint";
String agentName = "your_agent_name";
AgentsClientBuilder builder = new AgentsClientBuilder()
.credential(new DefaultAzureCredentialBuilder().build())
.endpoint(projectEndpoint);
ResponsesClient responsesClient = builder.buildResponsesClient();
// Generate a response without storing
AgentReference agentRef = new AgentReference(agentName);
Response response = responsesClient.createWithAgent(
agentRef,
ResponseCreateParams.builder()
.input("What is the largest city in France?")
.store(false));
System.out.println(response.output());
// Carry forward context client-side by passing previous output as input
Response followUp = responsesClient.createWithAgent(
agentRef,
ResponseCreateParams.builder()
.input(List.of(
new InputMessage("user", "What is the largest city in France?"),
new InputMessage("assistant", response.output()),
new InputMessage("user", "What is the population of that city?")))
.store(false));
System.out.println(followUp.output());
ENDPOINT="https://{resource_name}.services.ai.azure.com/api/projects/{project_name}"
ACCESS_TOKEN="$(az account get-access-token --resource https://ai.azure.com/ --query accessToken -o tsv)"
AGENT_NAME="your_agent_name"
# Generate a response without storing
RESPONSE=$(curl -s -X POST "${ENDPOINT}/openai/v1/responses" \
-H "Authorization: Bearer ${ACCESS_TOKEN}" \
-H "Content-Type: application/json" \
-d '{
"input": "What is the largest city in France?",
"store": false,
"agent_reference": {
"name": "'"${AGENT_NAME}"'",
"type": "agent_reference"
}
}')
OUTPUT_TEXT=$(echo "$RESPONSE" | jq -r '.output[] | select(.type=="message") | .content[0].text')
# Carry forward context client-side by passing previous output as input
curl -X POST "${ENDPOINT}/openai/v1/responses" \
-H "Authorization: Bearer ${ACCESS_TOKEN}" \
-H "Content-Type: application/json" \
-d '{
"input": [
{"role": "user", "content": "What is the largest city in France?"},
{"role": "assistant", "content": "'"${OUTPUT_TEXT}"'"},
{"role": "user", "content": "What is the population of that city?"}
],
"store": false,
"agent_reference": {
"name": "'"${AGENT_NAME}"'",
"type": "agent_reference"
}
}'
Conversazioni ed elementi di conversazione
Le conversazioni sono oggetti durevoli con identificatori univoci. Dopo la creazione, è possibile riutilizzarli tra le sessioni.
Gli elementi delle conversazioni archiviate possono includere messaggi, chiamate agli strumenti, output degli strumenti e altri dati.
Creare una conversazione
Nell'esempio seguente viene creata una conversazione con un messaggio utente iniziale. Usare il client OpenAI (ottenuto dal client del progetto) per conversazioni e risposte.
from azure.identity import DefaultAzureCredential
from azure.ai.projects import AIProjectClient
# Format: "https://resource_name.services.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 conversation with an initial user message
conversation = openai.conversations.create(
items=[
{
"type": "message",
"role": "user",
"content": "What is the largest city in France?",
}
],
)
print(f"Conversation ID: {conversation.id}")
using Azure.Identity;
using Azure.AI.Projects;
using Azure.AI.Projects.OpenAI;
// Format: "https://resource_name.services.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 a conversation
ProjectConversation conversation
= await projectClient.OpenAI.Conversations.CreateProjectConversationAsync();
Console.WriteLine($"Conversation ID: {conversation.Id}");
import { DefaultAzureCredential } from "@azure/identity";
import { AIProjectClient } from "@azure/ai-projects";
// Format: "https://resource_name.services.ai.azure.com/api/projects/project_name"
const PROJECT_ENDPOINT = "your_project_endpoint";
// Create clients to call Foundry API
const project = new AIProjectClient(PROJECT_ENDPOINT, new DefaultAzureCredential());
const openai = await project.getOpenAIClient();
// Create a conversation with an initial user message
const conversation = await openai.conversations.create({
items: [
{
type: "message",
role: "user",
content: "What is the largest city in France?",
},
],
});
console.log(`Conversation ID: ${conversation.id}`);
import com.azure.ai.agents.AgentsClientBuilder;
import com.azure.ai.agents.ConversationsClient;
import com.azure.identity.DefaultAzureCredentialBuilder;
// Format: "https://resource_name.services.ai.azure.com/api/projects/project_name"
String projectEndpoint = "your_project_endpoint";
// Create conversations client to call Foundry API
ConversationsClient conversationsClient = new AgentsClientBuilder()
.credential(new DefaultAzureCredentialBuilder().build())
.endpoint(projectEndpoint)
.buildConversationsClient();
// Create a conversation
var conversation = conversationsClient.getConversationService().create();
System.out.println("Conversation ID: " + conversation.id());
# Configuration
ENDPOINT="https://{resource_name}.services.ai.azure.com/api/projects/{project_name}"
ACCESS_TOKEN="$(az account get-access-token --resource https://ai.azure.com/ --query accessToken -o tsv)"
# Create a conversation with an initial user message
curl -X POST "${ENDPOINT}/openai/v1/conversations" \
-H "Authorization: Bearer ${ACCESS_TOKEN}" \
-H "Content-Type: application/json" \
-d '{
"items": [
{
"type": "message",
"role": "user",
"content": "What is the largest city in France?"
}
]
}'
Quando usare una conversazione
Utilizza una conversazione quando vuoi:
-
Continuità a più turni: mantenere una cronologia stabile tra turni senza ricompilare manualmente il contesto.
-
Continuità tra sessioni: riutilizzare la stessa conversazione per un utente che torna in un secondo momento.
-
Debug più semplice: controllare cosa è successo nel tempo (ad esempio, chiamate e output degli strumenti).
Quando una conversazione viene usata per generare una risposta (con o senza un agente), la conversazione completa viene fornita come input per il modello. La risposta generata viene quindi aggiunta alla stessa conversazione.
Annotazioni
Se la conversazione supera le dimensioni del contesto supportate dal modello, il modello tronca automaticamente il contesto di input. La conversazione stessa non viene troncata, ma viene usato solo un subset di esso per generare la risposta.
Se non si crea una conversazione, è comunque possibile creare flussi a più turni usando l'output di una risposta precedente come punto di partenza per la richiesta successiva. Questo approccio offre maggiore flessibilità rispetto al modello basato su thread precedente, in cui lo stato è strettamente associato agli oggetti thread. Per indicazioni sulla migrazione, vedere Eseguire la migrazione ad Agents SDK.
Tipi di elementi di conversazione
Conversazioni archivia elementi anziché solo messaggi di chat. Gli elementi acquisiscono ciò che è successo durante la generazione della risposta, in modo che il turno successivo possa riutilizzare tale contesto.
I tipi di elementi comuni includono:
-
Elementi del messaggio: messaggi utente o assistente.
-
Elementi di chiamata dello strumento: record di chiamate dello strumento tentate dall'agente.
-
Elementi di output dello strumento: output restituiti dagli strumenti (ad esempio, risultati di recupero).
-
Elementi di output: il contenuto della risposta visualizzato all'utente.
Aggiungere elementi a una conversazione
Dopo aver creato una conversazione, usare conversations.items.create() per aggiungere messaggi utente successivi o altri elementi.
# Add a follow-up message to an existing conversation
openai.conversations.items.create(
conversation_id=conversation.id,
items=[
{
"type": "message",
"role": "user",
"content": "What about Germany?",
}
],
)
// In C#, send follow-up input directly
// through the responses client
var followUp = await responsesClient.CreateResponseAsync(
"What about Germany?");
Console.WriteLine(followUp.GetOutputText());
// Add a follow-up message to an existing conversation
await openai.conversations.items.create(
conversation.id,
{
items: [
{
type: "message",
role: "user",
content: "What about Germany?",
},
],
},
);
// In Java, send follow-up input directly
// through the responses client
AgentReference agentRef = new AgentReference("my-agent");
Response followUp = responsesClient.createWithAgent(
agentRef,
ResponseCreateParams.builder()
.input("What about Germany?"));
System.out.println(followUp.output());
# Add items to an existing conversation
CONVERSATION_ID="conv_abc123"
curl -X POST "${ENDPOINT}/openai/v1/conversations/${CONVERSATION_ID}/items" \
-H "Authorization: Bearer ${ACCESS_TOKEN}" \
-H "Content-Type: application/json" \
-d '{
"items": [
{
"type": "message",
"role": "user",
"content": "What about Germany?"
}
]
}'
Usare una conversazione con un agente
Combinare una conversazione con un riferimento all'agente per mantenere la cronologia tra più turni. L'agente elabora tutti gli elementi della conversazione e ne aggiunge automaticamente l'output.
from azure.identity import DefaultAzureCredential
from azure.ai.projects import AIProjectClient
PROJECT_ENDPOINT = "your_project_endpoint"
AGENT_NAME = "your_agent_name"
# Create clients to call Foundry API
project = AIProjectClient(
endpoint=PROJECT_ENDPOINT,
credential=DefaultAzureCredential(),
)
openai = project.get_openai_client()
# Create a conversation for multi-turn chat
conversation = openai.conversations.create()
# First turn
response = openai.responses.create(
conversation=conversation.id,
extra_body={
"agent_reference": {
"name": AGENT_NAME,
"type": "agent_reference",
}
},
input="What is the largest city in France?",
)
print(response.output_text)
# Follow-up turn in the same conversation
follow_up = openai.responses.create(
conversation=conversation.id,
extra_body={
"agent_reference": {
"name": AGENT_NAME,
"type": "agent_reference",
}
},
input="What is the population of that city?",
)
print(follow_up.output_text)
using Azure.Identity;
using Azure.AI.Projects;
using Azure.AI.Projects.OpenAI;
var projectEndpoint = "your_project_endpoint";
var agentName = "your_agent_name";
AIProjectClient projectClient = new(
endpoint: new Uri(projectEndpoint),
tokenProvider: new DefaultAzureCredential());
// Create a conversation for multi-turn chat
ProjectConversation conversation
= await projectClient.OpenAI.Conversations.CreateProjectConversationAsync();
// First turn
ResponsesClient responsesClient
= projectClient.OpenAI.GetProjectResponsesClientForAgent(
new AgentReference { Name = agentName },
conversation.Id);
ResponseResult response = await responsesClient.CreateResponseAsync(
"What is the largest city in France?");
Console.WriteLine(response.GetOutputText());
// Follow-up turn in the same conversation
ResponseResult followUp = await responsesClient.CreateResponseAsync(
"What is the population of that city?");
Console.WriteLine(followUp.GetOutputText());
import { DefaultAzureCredential } from "@azure/identity";
import { AIProjectClient } from "@azure/ai-projects";
const PROJECT_ENDPOINT = "your_project_endpoint";
const AGENT_NAME = "your_agent_name";
const project = new AIProjectClient(PROJECT_ENDPOINT, new DefaultAzureCredential());
const openai = await project.getOpenAIClient();
// Create a conversation for multi-turn chat
const conversation = await openai.conversations.create();
// First turn
const response = await openai.responses.create({
conversation: conversation.id,
input: "What is the largest city in France?",
agent_reference: {
name: AGENT_NAME,
type: "agent_reference",
},
});
console.log(response.output_text);
// Follow-up turn in the same conversation
const followUp = await openai.responses.create({
conversation: conversation.id,
input: "What is the population of that city?",
agent_reference: {
name: AGENT_NAME,
type: "agent_reference",
},
});
console.log(followUp.output_text);
import com.azure.ai.agents.*;
import com.azure.ai.agents.models.AgentReference;
import com.azure.identity.DefaultAzureCredentialBuilder;
String projectEndpoint = "your_project_endpoint";
String agentName = "your_agent_name";
AgentsClientBuilder builder = new AgentsClientBuilder()
.credential(new DefaultAzureCredentialBuilder().build())
.endpoint(projectEndpoint);
ResponsesClient responsesClient = builder.buildResponsesClient();
ConversationsClient conversationsClient = builder.buildConversationsClient();
// Create a conversation for multi-turn chat
var conversation = conversationsClient.getConversationService().create();
// First turn
AgentReference agentRef = new AgentReference(agentName);
Response response = responsesClient.createWithAgentConversation(
agentRef, conversation.id(),
ResponseCreateParams.builder()
.input("What is the largest city in France?"));
System.out.println(response.output());
// Follow-up turn in the same conversation
Response followUp = responsesClient.createWithAgentConversation(
agentRef, conversation.id(),
ResponseCreateParams.builder()
.input("What is the population of that city?"));
System.out.println(followUp.output());
ENDPOINT="https://{resource_name}.services.ai.azure.com/api/projects/{project_name}"
ACCESS_TOKEN="$(az account get-access-token --resource https://ai.azure.com/ --query accessToken -o tsv)"
AGENT_NAME="your_agent_name"
# Create a conversation
CONVERSATION=$(curl -s -X POST "${ENDPOINT}/openai/v1/conversations" \
-H "Authorization: Bearer ${ACCESS_TOKEN}" \
-H "Content-Type: application/json" \
-d '{}')
CONVERSATION_ID=$(echo "$CONVERSATION" | jq -r '.id')
# First turn
curl -s -X POST "${ENDPOINT}/openai/v1/responses" \
-H "Authorization: Bearer ${ACCESS_TOKEN}" \
-H "Content-Type: application/json" \
-d '{
"input": "What is the largest city in France?",
"conversation": "'"${CONVERSATION_ID}"'",
"agent_reference": {
"name": "'"${AGENT_NAME}"'",
"type": "agent_reference"
}
}'
# Follow-up turn in the same conversation
curl -X POST "${ENDPOINT}/openai/v1/responses" \
-H "Authorization: Bearer ${ACCESS_TOKEN}" \
-H "Content-Type: application/json" \
-d '{
"input": "What is the population of that city?",
"conversation": "'"${CONVERSATION_ID}"'",
"agent_reference": {
"name": "'"${AGENT_NAME}"'",
"type": "agent_reference"
}
}'
Per esempi che illustrano il funzionamento delle conversazioni e delle risposte nel codice, vedere Creare e usare la memoria nel servizio foundry Agent.
Streaming e risposte in background
Per le operazioni a esecuzione prolungata, è possibile restituire i risultati in modo incrementale usando streaming o eseguire completamente in modo asincrono tramite background la modalità . In questi casi, in genere si monitora la risposta fino al termine e quindi si utilizzano gli elementi di output finali.
Trasmettere una risposta
Lo streaming restituisce risultati parziali man mano che vengono generati. Questo approccio è utile per mostrare l'output agli utenti in tempo reale.
from azure.identity import DefaultAzureCredential
from azure.ai.projects import AIProjectClient
# Format: "https://resource_name.services.ai.azure.com/api/projects/project_name"
PROJECT_ENDPOINT = "your_project_endpoint"
AGENT_NAME = "your_agent_name"
# Create clients to call Foundry API
project = AIProjectClient(
endpoint=PROJECT_ENDPOINT,
credential=DefaultAzureCredential(),
)
openai = project.get_openai_client()
# Stream a response using the agent
stream = openai.responses.create(
extra_body={
"agent_reference": {
"name": AGENT_NAME,
"type": "agent_reference",
}
},
input="Explain how agents work in one paragraph.",
stream=True,
)
for event in stream:
if hasattr(event, "delta") and event.delta:
print(event.delta, end="", flush=True)
using Azure.Identity;
using Azure.AI.Projects;
using Azure.AI.Projects.OpenAI;
// Format: "https://resource_name.services.ai.azure.com/api/projects/project_name"
var projectEndpoint = "your_project_endpoint";
var agentName = "your_agent_name";
// Create project client to call Foundry API
AIProjectClient projectClient = new(
endpoint: new Uri(projectEndpoint),
tokenProvider: new DefaultAzureCredential());
// Stream a response using the agent
ResponsesClient responsesClient
= projectClient.OpenAI.GetProjectResponsesClientForAgent(
new AgentReference { Name = agentName });
await foreach (var update in responsesClient.CreateResponseStreamingAsync(
"Explain how agents work in one paragraph."))
{
Console.Write(update.Text);
}
import { DefaultAzureCredential } from "@azure/identity";
import { AIProjectClient } from "@azure/ai-projects";
// Format: "https://resource_name.services.ai.azure.com/api/projects/project_name"
const PROJECT_ENDPOINT = "your_project_endpoint";
const AGENT_NAME = "your_agent_name";
// Create clients to call Foundry API
const project = new AIProjectClient(PROJECT_ENDPOINT, new DefaultAzureCredential());
const openai = await project.getOpenAIClient();
// Stream a response using the agent
const stream = await openai.responses.create({
input: "Explain how agents work in one paragraph.",
stream: true,
agent_reference: {
name: AGENT_NAME,
type: "agent_reference",
},
});
for await (const event of stream) {
if (event.type === "response.output_text.delta") {
process.stdout.write(event.delta);
}
}
// Streaming is not yet supported in the Java SDK.
// Use a synchronous response call instead.
import com.azure.ai.agents.*;
import com.azure.ai.agents.models.AgentReference;
import com.azure.identity.DefaultAzureCredentialBuilder;
String projectEndpoint = "your_project_endpoint";
String agentName = "your_agent_name";
ResponsesClient responsesClient = new AgentsClientBuilder()
.credential(new DefaultAzureCredentialBuilder().build())
.endpoint(projectEndpoint)
.buildResponsesClient();
AgentReference agentRef = new AgentReference(agentName);
Response response = responsesClient.createWithAgent(
agentRef,
ResponseCreateParams.builder()
.input("Explain how agents work in one paragraph."));
System.out.println(response.output());
# Configuration
ENDPOINT="https://{resource_name}.services.ai.azure.com/api/projects/{project_name}"
ACCESS_TOKEN="$(az account get-access-token --resource https://ai.azure.com/ --query accessToken -o tsv)"
AGENT_NAME="your_agent_name"
# Stream a response using an agent (returns server-sent events)
curl -N -X POST "${ENDPOINT}/openai/v1/responses" \
-H "Authorization: Bearer ${ACCESS_TOKEN}" \
-H "Content-Type: application/json" \
-d '{
"input": "Explain how agents work in one paragraph.",
"stream": true,
"agent_reference": {
"name": "'"${AGENT_NAME}"'",
"type": "agent_reference"
}
}'
Per informazioni dettagliate sulle modalità di risposta e su come usare gli output, vedere API delle risposte.
Eseguire un agente in modalità background
La modalità in background esegue l'agente in modo asincrono, utile per attività a esecuzione prolungata, ad esempio motivi complessi o generazione di immagini. Imposta background su true e quindi controlla lo stato della risposta fino a quando non viene completato.
from time import sleep
from azure.identity import DefaultAzureCredential
from azure.ai.projects import AIProjectClient
PROJECT_ENDPOINT = "your_project_endpoint"
AGENT_NAME = "your_agent_name"
# Create clients to call Foundry API
project = AIProjectClient(
endpoint=PROJECT_ENDPOINT,
credential=DefaultAzureCredential(),
)
openai = project.get_openai_client()
# Start a background response using the agent
response = openai.responses.create(
extra_body={
"agent_reference": {
"name": AGENT_NAME,
"type": "agent_reference",
}
},
input="Write a detailed analysis of renewable energy trends.",
background=True,
)
# Poll until the response completes
while response.status in ("queued", "in_progress"):
sleep(2)
response = openai.responses.retrieve(response.id)
print(response.output_text)
using Azure.Identity;
using Azure.AI.Projects;
using Azure.AI.Projects.OpenAI;
var projectEndpoint = "your_project_endpoint";
var agentName = "your_agent_name";
AIProjectClient projectClient = new(
endpoint: new Uri(projectEndpoint),
tokenProvider: new DefaultAzureCredential());
// Start a background response using the agent
ResponsesClient responsesClient
= projectClient.OpenAI.GetProjectResponsesClientForAgent(
new AgentReference { Name = agentName });
ResponseResult response = await responsesClient.CreateResponseAsync(
"Write a detailed analysis of renewable energy trends.",
background: true);
// Poll until the response completes
while (response.Status is "queued" or "in_progress")
{
await Task.Delay(2000);
response = await responsesClient.RetrieveResponseAsync(response.Id);
}
Console.WriteLine(response.GetOutputText());
import { DefaultAzureCredential } from "@azure/identity";
import { AIProjectClient } from "@azure/ai-projects";
const PROJECT_ENDPOINT = "your_project_endpoint";
const AGENT_NAME = "your_agent_name";
const project = new AIProjectClient(PROJECT_ENDPOINT, new DefaultAzureCredential());
const openai = await project.getOpenAIClient();
// Start a background response using the agent
let response = await openai.responses.create({
input: "Write a detailed analysis of renewable energy trends.",
background: true,
agent_reference: {
name: AGENT_NAME,
type: "agent_reference",
},
});
// Poll until the response completes
while (response.status === "queued" || response.status === "in_progress") {
await new Promise((r) => setTimeout(r, 2000));
response = await openai.responses.retrieve(response.id);
}
console.log(response.output_text);
Annotazioni
La modalità in background con il polling non è ancora completamente supportata in Java SDK. Controllare le note di rilascio di azure-ai-agents per gli aggiornamenti.
ENDPOINT="https://{resource_name}.services.ai.azure.com/api/projects/{project_name}"
ACCESS_TOKEN="$(az account get-access-token --resource https://ai.azure.com/ --query accessToken -o tsv)"
AGENT_NAME="your_agent_name"
# Start a background response using an agent
RESPONSE=$(curl -s -X POST "${ENDPOINT}/openai/v1/responses" \
-H "Authorization: Bearer ${ACCESS_TOKEN}" \
-H "Content-Type: application/json" \
-d '{
"input": "Write a detailed analysis of renewable energy trends.",
"background": true,
"agent_reference": {
"name": "'"${AGENT_NAME}"'",
"type": "agent_reference"
}
}')
RESPONSE_ID=$(echo "$RESPONSE" | jq -r '.id')
# Poll until the response completes
STATUS=$(echo "$RESPONSE" | jq -r '.status')
while [ "$STATUS" = "queued" ] || [ "$STATUS" = "in_progress" ]; do
sleep 2
RESPONSE=$(curl -s -X GET "${ENDPOINT}/openai/v1/responses/${RESPONSE_ID}" \
-H "Authorization: Bearer ${ACCESS_TOKEN}")
STATUS=$(echo "$RESPONSE" | jq -r '.status')
done
echo "$RESPONSE" | jq -r '.output[0].content[0].text'
Associare la memoria a un agente (anteprima)
La memoria offre agli agenti la possibilità di conservare le informazioni tra le sessioni, in modo da poter personalizzare le risposte e richiamare le preferenze utente nel tempo. Senza memoria, ogni conversazione inizia da zero.
Il servizio agente Foundry offre una soluzione di memoria gestita (anteprima) configurata tramite archivi di memoria. Un archivio di memoria definisce i tipi di informazioni che l'agente deve conservare. Collegare un archivio di memoria all'agente e l'agente usa memorie archiviate come contesto aggiuntivo durante la generazione della risposta.
L'esempio seguente crea un archivio di memoria e lo collega a un agente.
from azure.identity import DefaultAzureCredential
from azure.ai.projects import AIProjectClient
from azure.ai.projects.models import (
MemoryStoreDefaultDefinition,
MemoryStoreDefaultOptions,
)
PROJECT_ENDPOINT = "your_project_endpoint"
project = AIProjectClient(
endpoint=PROJECT_ENDPOINT,
credential=DefaultAzureCredential(),
)
# Create a memory store
options = MemoryStoreDefaultOptions(
chat_summary_enabled=True,
user_profile_enabled=True,
)
definition = MemoryStoreDefaultDefinition(
chat_model="gpt-5.2",
embedding_model="text-embedding-3-small",
options=options,
)
memory_store = project.beta.memory_stores.create(
name="my_memory_store",
definition=definition,
description="Memory store for my agent",
)
print(f"Memory store: {memory_store.name}")
using Azure.Identity;
using Azure.AI.Projects;
#pragma warning disable AAIP001
var projectEndpoint = "your_project_endpoint";
AIProjectClient projectClient = new(
new Uri(projectEndpoint),
new DefaultAzureCredential());
// Create a memory store
MemoryStoreDefaultDefinition memoryStoreDefinition = new(
chatModel: "gpt-5.2",
embeddingModel: "text-embedding-3-small");
memoryStoreDefinition.Options = new(
userProfileEnabled: true,
chatSummaryEnabled: true);
MemoryStore memoryStore = await projectClient.MemoryStores
.CreateMemoryStoreAsync(
name: "my_memory_store",
definition: memoryStoreDefinition,
description: "Memory store for my agent");
Console.WriteLine($"Memory store: {memoryStore.Name}");
import { DefaultAzureCredential } from "@azure/identity";
import { AIProjectClient } from "@azure/ai-projects";
const PROJECT_ENDPOINT = "your_project_endpoint";
const project = new AIProjectClient(PROJECT_ENDPOINT, new DefaultAzureCredential());
// Create a memory store
const memoryStore = await project.beta.memoryStores.create(
"my_memory_store",
{
kind: "default",
chat_model: "gpt-5.2",
embedding_model: "text-embedding-3-small",
options: {
user_profile_enabled: true,
chat_summary_enabled: true,
},
},
{ description: "Memory store for my agent" },
);
console.log(`Memory store: ${memoryStore.name}`);
import com.azure.ai.agents.AgentsClientBuilder;
import com.azure.ai.agents.MemoryStoresClient;
import com.azure.ai.agents.models.MemoryStoreDefaultDefinition;
import com.azure.ai.agents.models.MemoryStoreDetails;
import com.azure.identity.DefaultAzureCredentialBuilder;
String projectEndpoint = "your_project_endpoint";
// Create memory stores client
MemoryStoresClient memoryStoresClient = new AgentsClientBuilder()
.credential(new DefaultAzureCredentialBuilder().build())
.endpoint(projectEndpoint)
.buildMemoryStoresClient();
// Create a memory store
MemoryStoreDefaultDefinition definition =
new MemoryStoreDefaultDefinition("gpt-5.2", "text-embedding-3-small");
MemoryStoreDetails memoryStore = memoryStoresClient
.createMemoryStore("my_memory_store", definition,
"Memory store for my agent", null);
System.out.println("Memory store: " + memoryStore.getName());
ENDPOINT="https://{resource_name}.services.ai.azure.com/api/projects/{project_name}"
API_VERSION="2025-11-15-preview"
ACCESS_TOKEN="$(az account get-access-token --resource https://ai.azure.com/ --query accessToken -o tsv)"
# Create a memory store
curl -X POST "${ENDPOINT}/memory_stores?api-version=${API_VERSION}" \
-H "Authorization: Bearer ${ACCESS_TOKEN}" \
-H "Content-Type: application/json" \
-d '{
"name": "my_memory_store",
"description": "Memory store for my agent",
"definition": {
"kind": "default",
"chat_model": "gpt-5.2",
"embedding_model": "text-embedding-3-small",
"options": {
"chat_summary_enabled": true,
"user_profile_enabled": true
}
}
}'
Per i dettagli concettuali, consultare Memoria nel servizio Foundry Agent. Per indicazioni complete sull'implementazione, vedere Creare e usare la memoria.
Sicurezza e gestione dei dati
Poiché le conversazioni e le risposte possono rendere persistenti i contenuti e gli output degli strumenti forniti dall'utente, trattare i dati di runtime come i dati dell'applicazione:
-
Evitare di archiviare i segreti nelle richieste o nella cronologia delle conversazioni. Usare invece connessioni e archivi segreti gestiti, ad esempio Impostare una connessione Key Vault).
-
Usare i minimi privilegi per l'accesso agli strumenti. Quando uno strumento accede a sistemi esterni, l'agente può potenzialmente leggere o inviare dati tramite tale strumento.
-
Prestare attenzione ai servizi non Microsoft. Se l'agente chiama strumenti supportati da servizi non Microsoft, alcuni dati potrebbero essere trasmessi a tali servizi. Per considerazioni correlate, vedere Scoprire gli strumenti nei Foundry Tools.
Limiti e vincoli
I limiti possono dipendere dal modello, dall'area geografica e dagli strumenti collegati( ad esempio, la disponibilità di streaming e il supporto degli strumenti). Per la disponibilità e i vincoli correnti per le risposte, vedere API Risposte.
Contenuti correlati