In questa guida rapida, si crea un agente di prompt nel Servizio Agente Fonderia e si ha una conversazione con esso. Un agente prompt è un agente definito in modo dichiarativo che combina un modello dal catalogo dei modelli di Foundry, con istruzioni, strumenti e prompt di linguaggio naturale per orientare il comportamento.
Suggerimento
Per un'esperienza vocale gestita in tempo reale, usare un agente di prompt basato su voce. Gli agenti basati su prompt vocali utilizzano Voice Live per conversazioni vocali e non richiedono che tu ospiti il codice di orchestrazione vocale.
Se non si ha una sottoscrizione Azure, creare un account free.
Prerequisiti
Ottenere l'endpoint del progetto
Copiare l'endpoint del progetto dalla schermata iniziale nel portale di Foundry.
Gli esempi di codice in questa guida introduttiva dichiarano i relativi valori come costanti all'inizio di ogni file. Prima di eseguire un esempio, sostituire questi segnaposto:
-
your_project_endpoint: l'endpoint del progetto, nel formato https://<resource-name>.services.ai.azure.com/api/projects/<project-name>.
-
your_agent_name: nome dell'agente, ad esempio MyAgent.
Installare pacchetti ed eseguire l'autenticazione
Assicurarsi di installare la versione corretta dei pacchetti, come illustrato di seguito.
Installare la versione corrente di azure-ai-projects. Questa versione usa l'API di Foundry projects (new). Gli esempi si autenticano utilizzando DefaultAzureCredential, che proviene da azure-identity.
pip install "azure-ai-projects>=2.3.0"
Accedi utilizzando il comando CLI az login per autenticarti prima di eseguire i tuoi script Python.
Installare i pacchetti:
Aggiungere pacchetti NuGet usando l'interfaccia della riga di comando di .NET nel terminale integrato: questi pacchetti usano l'API Foundry projects (new) API.
dotnet add package Azure.AI.Projects
dotnet add package Azure.AI.Projects.Agents
dotnet add package Azure.AI.Extensions.OpenAI
dotnet add package Azure.Identity
Accedi utilizzando il comando CLI az login per autenticarti prima di lanciare gli script C#.
Installare la versione corrente di @azure/ai-projects. Questa versione usa l'API Dei progetti Foundry (nuova).
npm install @azure/ai-projects @azure/identity
Accedere usando il comando CLI az login per eseguire l'autenticazione prima di eseguire gli script TypeScript.
<dependency>
<groupId>com.azure</groupId>
<artifactId>azure-ai-agents</artifactId>
<version>2.2.0</version>
</dependency>
<dependency>
<groupId>com.azure</groupId>
<artifactId>azure-core</artifactId>
<version>1.57.0</version>
</dependency>
<dependency>
<groupId>com.azure</groupId>
<artifactId>azure-identity</artifactId>
<version>1.18.1</version>
</dependency>
- Accedi usando il comando CLI
az login per autenticarti prima di eseguire gli script Java.
Accedi usando il comando CLI az login per autenticarti prima di eseguire il comando successivo.
Ottenere un token di accesso temporaneo. Scadrà tra 60 e 90 minuti, sarà necessario eseguire l'aggiornamento dopo.
az account get-access-token --scope https://ai.azure.com/.default
Salvare i risultati come variabile AZURE_AI_AUTH_TOKENdi ambiente .
Non è necessaria alcuna installazione per usare il portale foundry.
Creare un agente di risposta rapida
Crea un agente per i prompt utilizzando il tuo modello distribuito. L'agente usa un PromptAgentDefinition oggetto con istruzioni che definiscono il comportamento dell'agente. È possibile aggiornare o eliminare agenti in qualsiasi momento.
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"
FOUNDRY_PROJECT_ENDPOINT = "your_project_endpoint"
FOUNDRY_AGENT_NAME = "your-agent-name"
# Create project client to call Foundry API
project = AIProjectClient(
endpoint=FOUNDRY_PROJECT_ENDPOINT,
credential=DefaultAzureCredential(),
)
# Create an agent with a model and instructions
agent = project.agents.create_version(
agent_name=FOUNDRY_AGENT_NAME,
definition=PromptAgentDefinition(
model="gpt-5-mini", # supports all Foundry direct models
instructions="You are a helpful assistant that answers general questions",
),
)
print(f"Agent created (id: {agent.id}, name: {agent.name}, version: {agent.version})")
using Azure.Identity;
using Azure.AI.Projects;
using Azure.AI.Projects.Agents;
using Azure.AI.Extensions.OpenAI;
// Format: "https://resource_name.services.ai.azure.com/api/projects/project_name"
var foundryProjectEndpoint = "your_project_endpoint";
var foundryAgentName = "your-agent-name";
// Create project client to call Foundry API
AIProjectClient projectClient = new(
endpoint: new Uri(foundryProjectEndpoint),
tokenProvider: new DefaultAzureCredential());
// Create an agent with a model and instructions
ProjectsAgentDefinition agentDefinition = new DeclarativeAgentDefinition("gpt-5-mini") // supports all Foundry direct models
{
Instructions = "You are a helpful assistant that answers general questions",
};
ProjectsAgentVersion agent = projectClient.AgentAdministrationClient.CreateAgentVersion(
foundryAgentName,
options: new(agentDefinition));
Console.WriteLine($"Agent created (id: {agent.Id}, name: {agent.Name}, version: {agent.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 FOUNDRY_PROJECT_ENDPOINT = "your_project_endpoint";
const FOUNDRY_AGENT_NAME = "your-agent-name";
async function main(): Promise<void> {
const project = new AIProjectClient(FOUNDRY_PROJECT_ENDPOINT, new DefaultAzureCredential());
const agent = await project.agents.createVersion(FOUNDRY_AGENT_NAME, {
kind: "prompt",
model: "gpt-5-mini", // supports all Foundry direct models
instructions: "You are a helpful assistant that answers general questions",
});
console.log(`Agent created: ${agent.name}, version: ${agent.version}`);
}
main().catch((error) => {
console.error(error);
process.exitCode = 1;
});
package com.azure.ai.foundry.samples;
import com.azure.ai.agents.AgentsClient;
import com.azure.ai.agents.AgentsClientBuilder;
import com.azure.ai.agents.models.AgentVersionDetails;
import com.azure.ai.agents.models.PromptAgentDefinition;
import com.azure.identity.DefaultAzureCredentialBuilder;
public class CreateAgent {
public static void main(String[] args) {
// Format: "https://resource_name.services.ai.azure.com/api/projects/project_name"
String foundryProjectEndpoint = "your_project_endpoint";
String foundryAgentName = "your-agent-name";
// Create agents client to call Foundry API
AgentsClient agentsClient = new AgentsClientBuilder()
.credential(new DefaultAzureCredentialBuilder().build())
.endpoint(foundryProjectEndpoint)
.buildAgentsClient();
// Create an agent with a model and instructions
PromptAgentDefinition request = new PromptAgentDefinition("gpt-5-mini") // supports all Foundry direct models
.setInstructions("You are a helpful assistant that answers general questions");
AgentVersionDetails agent = agentsClient.createAgentVersion(foundryAgentName, request);
System.out.println("Agent ID: " + agent.getId());
System.out.println("Agent Name: " + agent.getName());
System.out.println("Agent Version: " + agent.getVersion());
}
}
Sostituire YOUR-FOUNDRY-RESOURCE-NAME con i valori:
curl -X POST https://YOUR-FOUNDRY-RESOURCE-NAME.services.ai.azure.com/api/projects/YOUR-PROJECT-NAME/agents?api-version=v1 \
-H "Content-Type: application/json" \
-H "Authorization: Bearer $AZURE_AI_AUTH_TOKEN" \
-d '{
"name": "MyAgent",
"definition": {
"kind": "prompt",
"model": "gpt-5-mini",
"instructions": "You are a helpful assistant that answers general questions"
}
}'
L'output conferma che l'agente è stato creato. Nella console viene visualizzato il nome e l'ID dell'agente.
Chat con l'agente
Usa l'agente che hai creato per interagire ponendo una domanda e un'interazione successiva correlata. La conversazione mantiene la cronologia di queste interazioni.
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"
FOUNDRY_PROJECT_ENDPOINT = "your_project_endpoint"
FOUNDRY_AGENT_NAME = "your-agent-name"
# Create project and openai clients to call Foundry API
project = AIProjectClient(
endpoint=FOUNDRY_PROJECT_ENDPOINT,
credential=DefaultAzureCredential(),
)
# Create the agent (or a new version, if it already exists)
project.agents.create_version(
agent_name=FOUNDRY_AGENT_NAME,
definition=PromptAgentDefinition(
model="gpt-5-mini",
instructions="You are a helpful assistant that answers general questions",
),
)
# Get an OpenAI client pre-bound to the specified agent
openai = project.get_openai_client(agent_name=FOUNDRY_AGENT_NAME)
# Create a conversation for multi-turn chat
conversation = openai.conversations.create()
# Chat with the agent to answer questions
response = openai.responses.create(
conversation=conversation.id,
input="What is the size of France in square miles?",
)
print(response.output_text)
# Ask a follow-up question in the same conversation
response = openai.responses.create(
conversation=conversation.id,
input="And what is the capital city?",
)
print(response.output_text)
using Azure.Identity;
using Azure.AI.Projects;
using Azure.AI.Projects.Agents;
using Azure.AI.Extensions.OpenAI;
using OpenAI.Responses;
#pragma warning disable OPENAI001
// Format: "https://resource_name.services.ai.azure.com/api/projects/project_name"
var foundryProjectEndpoint = "your_project_endpoint";
var foundryAgentName = "your-agent-name";
// Create project client to call Foundry API
AIProjectClient projectClient = new(
endpoint: new Uri(foundryProjectEndpoint),
tokenProvider: new DefaultAzureCredential());
// Create the agent (or a new version, if it already exists)
ProjectsAgentDefinition agentDefinition = new DeclarativeAgentDefinition("gpt-5-mini") // supports all Foundry direct models
{
Instructions = "You are a helpful assistant that answers general questions",
};
projectClient.AgentAdministrationClient.CreateAgentVersion(
foundryAgentName,
options: new(agentDefinition));
// Create a conversation for multi-turn chat
ProjectConversation conversation = projectClient.ProjectOpenAIClient.GetProjectConversationsClient().CreateProjectConversation();
// Chat with the agent to answer questions
ProjectResponsesClient responsesClient = projectClient.ProjectOpenAIClient.GetProjectResponsesClientForAgent(
defaultAgent: foundryAgentName,
defaultConversationId: conversation.Id);
ResponseResult response = responsesClient.CreateResponse("What is the size of France in square miles?");
Console.WriteLine(response.GetOutputText());
// Ask a follow-up question in the same conversation
response = responsesClient.CreateResponse("And what is the capital city?");
Console.WriteLine(response.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 FOUNDRY_PROJECT_ENDPOINT = "your_project_endpoint";
const FOUNDRY_AGENT_NAME = "your-agent-name";
async function main(): Promise<void> {
const credential = new DefaultAzureCredential();
const project = new AIProjectClient(FOUNDRY_PROJECT_ENDPOINT, credential);
const agent = await project.agents.createVersion(FOUNDRY_AGENT_NAME, {
kind: "prompt",
model: "gpt-5-mini", // supports all Foundry direct models
instructions: "You are a helpful assistant that answers general questions",
});
if (!agent.name || !agent.version) {
throw new Error("The created agent did not include a name and version.");
}
const agentName = agent.name;
const agentVersion = agent.version;
const openai = project.getOpenAIClient();
try {
// Create a conversation for multi-turn chat
const conversation = await openai.conversations.create();
try {
// Chat with the agent to answer questions
const response = await openai.responses.create(
{
conversation: conversation.id,
input: "What is the size of France in square miles?",
},
{
body: { agent_reference: { name: agentName, type: "agent_reference" } },
},
);
console.log(response.output_text);
// Ask a follow-up question in the same conversation
const response2 = await openai.responses.create(
{
conversation: conversation.id,
input: "And what is the capital city?",
},
{
body: { agent_reference: { name: agentName, type: "agent_reference" } },
},
);
console.log(response2.output_text);
} finally {
await openai.conversations.delete(conversation.id);
}
} finally {
await project.agents.deleteVersion(agentName, agentVersion);
}
}
main().catch((error) => {
console.error(error);
process.exitCode = 1;
});
package com.azure.ai.foundry.samples;
import com.azure.ai.agents.AgentsClient;
import com.azure.ai.agents.AgentsClientBuilder;
import com.azure.ai.agents.models.PromptAgentDefinition;
import com.azure.identity.DefaultAzureCredentialBuilder;
import com.openai.client.OpenAIClient;
import com.openai.models.conversations.Conversation;
import com.openai.models.responses.Response;
import com.openai.models.responses.ResponseCreateParams;
public class ChatWithAgent {
public static void main(String[] args) {
// Format: "https://resource_name.services.ai.azure.com/api/projects/project_name"
String foundryProjectEndpoint = "your_project_endpoint";
String foundryAgentName = "your-agent-name";
AgentsClientBuilder builder = new AgentsClientBuilder()
.credential(new DefaultAzureCredentialBuilder().build())
.endpoint(foundryProjectEndpoint);
// Create the agent (or a new version, if it already exists)
AgentsClient agentsClient = builder.buildAgentsClient();
PromptAgentDefinition agentDefinition = new PromptAgentDefinition("gpt-5-mini") // supports all Foundry direct models
.setInstructions("You are a helpful assistant that answers general questions");
agentsClient.createAgentVersion(foundryAgentName, agentDefinition);
// Create an OpenAI client bound to the agent endpoint
OpenAIClient openai = builder.buildAgentScopedOpenAIClient(foundryAgentName);
// Create a conversation for multi-turn chat
Conversation conversation = openai.conversations().create();
// Chat with the agent to answer questions
Response response = openai.responses().create(
ResponseCreateParams.builder()
.conversation(conversation.id())
.input("What is the size of France in square miles?")
.build());
printResponse(response);
// Ask a follow-up question in the same conversation
Response followUp = openai.responses().create(
ResponseCreateParams.builder()
.conversation(conversation.id())
.input("And what is the capital city?")
.build());
printResponse(followUp);
}
private static void printResponse(Response response) {
response.output().forEach(item -> item.message().ifPresent(message ->
message.content().forEach(content -> content.outputText().ifPresent(
text -> System.out.println(text.text())))));
}
}
Sostituire YOUR-FOUNDRY-RESOURCE-NAME con i valori e impostare la FOUNDRY_AGENT_NAME variabile di ambiente sul nome dell'agente usato:
# Generate a response using the agent
curl -X POST "https://YOUR-FOUNDRY-RESOURCE-NAME.services.ai.azure.com/api/projects/YOUR-PROJECT-NAME/agents/${FOUNDRY_AGENT_NAME}/endpoint/protocols/openai/responses?api-version=v1" \
-H "Content-Type: application/json" \
-H "Authorization: Bearer $AZURE_AI_AUTH_TOKEN" \
-d '{
"input": [{"role": "user", "content": "What is the size of France in square miles?"}]
}'
# Optional Step: Create a conversation to use with the agent
curl -X POST "https://YOUR-FOUNDRY-RESOURCE-NAME.services.ai.azure.com/api/projects/YOUR-PROJECT-NAME/agents/${FOUNDRY_AGENT_NAME}/endpoint/protocols/openai/conversations?api-version=v1" \
-H "Content-Type: application/json" \
-H "Authorization: Bearer $AZURE_AI_AUTH_TOKEN" \
-d '{
"items": [
{
"type": "message",
"role": "user",
"content": [
{
"type": "input_text",
"text": "What is the size of France in square miles?"
}
]
}
]
}'
# Lets say Conversation ID created is conv_123456789. Use this in the next step
#Optional Step: Ask a follow-up question in the same conversation
curl -X POST "https://YOUR-FOUNDRY-RESOURCE-NAME.services.ai.azure.com/api/projects/YOUR-PROJECT-NAME/agents/${FOUNDRY_AGENT_NAME}/endpoint/protocols/openai/responses?api-version=v1" \
-H "Content-Type: application/json" \
-H "Authorization: Bearer $AZURE_AI_AUTH_TOKEN" \
-d '{
"conversation": "<CONVERSATION_ID>",
"input": [{"role": "user", "content": "And what is the capital?"}]
}'
Vengono visualizzate le risposte dell'agente a entrambe le richieste. La risposta di follow-up dimostra che l'agente mantiene la cronologia delle conversazioni tra i turni.
Verifica quindi la trace del primo agente nel portale Foundry.
Pulire le risorse
Se non sono più necessarie risorse create, eliminare il gruppo di risorse associato al progetto.
- Nel portale Azure portale selezionare il gruppo di risorse e quindi selezionare Delete. Verificare di voler eliminare il gruppo di risorse.
Contenuto correlato