تستخدم خدمة وكلاء الصاهر Microsoft ثلاثة مكونات أساسية في وقت التشغيل—agents، conversations، و responses—لتمكين التفاعلات الحالة متعددة الأدوار. يستخدم الوكيل نموذجا من كتالوج نماذج Foundry، مع تعليمات وأدوات. تستمر المحادثة في التاريخ عبر المنعطفات. الاستجابة هي الناتج الذي ينتجه الوكيل عند معالجة الإدخالات.
اختر المكونات استنادا إلى السلوك وحالة احتياجات التطبيق الخاص بك:
| المكون |
العلاقه |
استخدمه عندما |
|
العامل |
يوفر نموذجا وتعليمات وأدوات قابلة لإعادة الاستخدام للاستجابة. |
تحتاج الطلبات المتعددة إلى نفس السلوك أو تكوين الأداة. |
|
حوار |
استمرت الإمدادات في عناصر الإدخال والإخراج للاستجابات. |
تحتاج المنعطفات اللاحقة إلى محفوظات من جانب الخادم. |
|
استجابه |
تشغيل نموذج أو عامل مقابل الإدخال وإنتاج عناصر الإخراج. |
يحتاج كل تفاعل إلى وحدة تنفيذ واحدة، مع أو بدون وكيل أو محادثة. |
ابدأ باستجابة لتفاعل واحد. إضافة عامل لسلوك قابل لإعادة الاستخدام أو محادثة للمحفوظات المستمرة أو كليهما. للحصول على تفاصيل التنفيذ، انتقل مباشرة إلى إنشاء عامل أو إنشاء استجابات أو العمل مع المحادثات وعناصر المحادثة.
تعمل المكونات معا في دورة حياة يمكن التنبؤ بها. على سبيل المثال، ضع في اعتبارك مساعد دعم يجيب عن سؤال متابعة:
- يحدد التطبيق وكيلا يحدد إرشادات وأدوات الدعم.
- يقوم بإنشاء محادثة وإضافة السؤال الأول للعميل كعنصر إدخال.
- تقوم الاستجابة بتشغيل العامل مقابل المحادثة وإلحاق عناصر الإخراج.
- تستخدم الاستجابة التالية نفس المحادثة، بحيث يمكن للعامل الإجابة عن سؤال متابعة في السياق.
بدون محادثة، يمكن للتطبيق بدلا من ذلك نقل السياق إلى الأمام عن طريق الرجوع إلى استجابة مخزنة سابقة أو عن طريق إعادة إرسال العناصر السابقة. يغير وضع الدفق والخلفية كيفية تلقي التطبيق استجابة، وليس العلاقة بين الوكلاء والمحادثات والاستجابات.
يوضح الرسم البياني التالي كيف تتفاعل هذه المكونات في حلقة وكيل نموذجية.
توفر مدخلات المستخدم (وأحيانا تاريخ المحادثة)، وتقوم الخدمة بتوليد استجابة (بما في ذلك استدعاءات الأدوات عند التكوين)، ويمكن إعادة استخدام العناصر الناتجة كسياق للدور التالي.
المتطلبات الأساسية
لتشغيل العينات في هذا المقال، تحتاج:
pip install "azure-ai-projects>=2.0.0"
pip install azure-identity
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
npm install @azure/ai-projects
npm install @azure/identity
استخدم Node.js 22 أو أحدث مع @azure/ai-projects 2.4.0.
<dependency>
<groupId>com.azure</groupId>
<artifactId>azure-ai-agents</artifactId>
<version>2.2.0</version>
</dependency>
<dependency>
<groupId>com.azure</groupId>
<artifactId>azure-identity</artifactId>
<version>1.18.4</version>
</dependency>
لا حاجة لتثبيت SDK. استخدم Azure CLI للحصول على رمز الوصول:
az login
إنشاء وكيل
الوكيل هو تعريف تنسيق مستمر يجمع بين نماذج الذكاء الاصطناعي، والتعليمات، والشيفرة، والأدوات، والمعلمات، وضوابط السلامة أو الحوكمة الاختيارية.
وكلاء التخزين كما هو مسمى، والأصول المعدلة في Microsoft Foundry. خلال توليد الردود، يعمل تعريف الوكيل مع تاريخ التفاعل (المحادثة أو الاستجابة السابقة) لمعالجة والاستجابة لمدخلات المستخدم.
المثال التالي ينشئ وكيل المطالبات مع اسم ونموذج وتعليمات. استخدم عميل المشروع لإنشاء وكيل وإصدار الإصدارات.
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
ProjectsAgentVersion agent = await projectClient.AgentAdministrationClient
.CreateAgentVersionAsync(
agentName: "my-agent",
options: new(
new DeclarativeAgentDefinition("gpt-5-mini")
{
Instructions = "You are a helpful assistant.",
}));
Console.WriteLine($"Agent: {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 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."
}
}'
ملاحظة
يتم الآن تحديد الوكلاء باستخدام اسم الوكيل ونسخة الوكيل. لم يعد لديهم رمز GUID بعد AgentID الآن.
لأنواع الوكلاء الإضافية (المستضيفة)، انظر دورة حياة تطوير الوكيل.
الأدوات تمتد إلى ما يمكن للوكيل فعله إلى ما هو أبعد من توليد النص. عند ربط أدوات بوكيل، يمكن للوكيل استدعاء خدمات خارجية، وتشغيل الكود، والبحث عن الملفات، والوصول إلى مصادر البيانات أثناء توليد الرد — باستخدام أدوات مثل البحث على الويب أو استدعاء الدوال.
يمكنك إرفاق أداة أو أكثر عند إنشاء وكيل. خلال توليد الاستجابة، يقرر الوكيل ما إذا كان سيطلب أداة بناء على مدخلات المستخدم وتعليماتها. المثال التالي ينشئ وكيلا مع أداة بحث ويب مرفقة.
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
ProjectsAgentVersion agent = await projectClient.AgentAdministrationClient
.CreateAgentVersionAsync(
agentName: "my-tool-agent",
options: new(
new DeclarativeAgentDefinition("gpt-5-mini")
{
Instructions = "You are a helpful assistant that can search the web.",
Tools = { ResponseTool.CreateWebSearchTool() },
}));
Console.WriteLine($"Agent: {agent.Name}, Version: {agent.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" }]
}
}'
للاطلاع على القائمة الكاملة للأدوات المتاحة، راجع نظرة عامة على الأدوات. للحصول على أفضل الممارسات، راجع أفضل الممارسات لاستخدام الأدوات.
توليد الردود
توليد الاستجابة يستدعي الوكيل. يستخدم الوكيل تكوينه وأي سجل موفر (محادثة أو استجابة سابقة) لأداء المهام عن طريق استدعاء النماذج والأدوات. كجزء من توليد الردود، يضيف الوكيل عناصر إلى المحادثة.
يمكنك أيضا توليد استجابة دون تعريف وكيل. في هذه الحالة، تقدم جميع الإعدادات مباشرة في الطلب وتستخدمها فقط لهذا الرد. هذا النهج مفيد للسيناريوهات البسيطة التي تحتوي على أدوات قليلة.
بالإضافة إلى ذلك، يمكنك تقسيم المحادثة إلى معرف الاستجابة الأولى أو معرف الاستجابة الثانية
توليد استجابة باستخدام وكيل
المثال التالي يولد إجابة باستخدام مرجع وكيل، ثم يرسل سؤالا متابعة باستخدام الإجابة السابقة كسياق.
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.Extensions.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
ProjectResponsesClient responsesClient
= projectClient.ProjectOpenAIClient.GetProjectResponsesClientForAgent(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(
new CreateResponseOptions
{
PreviousResponseId = response.Id,
InputItems = { ResponseItem.CreateUserMessageItem(
"What is the population of that city?") },
});
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 = project.getOpenAIClient();
// Generate a response using the agent
const response = await openai.responses.create(
{ input: "What is the largest city in France?" },
{ body: { 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,
},
{ body: { 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.ai.agents.models.AzureCreateResponseOptions;
import com.azure.identity.DefaultAzureCredentialBuilder;
import com.openai.models.responses.Response;
import com.openai.models.responses.ResponseCreateParams;
// 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.createAzureResponse(
new AzureCreateResponseOptions().setAgentReference(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.createAzureResponse(
new AzureCreateResponseOptions().setAgentReference(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"
}
}'
عندما يستخدم وكيل أدوات أثناء توليد الاستجابة، يحتوي مخرجات الاستجابة على عناصر استدعاء الأدوات إلى جانب الرسالة النهائية. يمكنك التكرار response.output لفحص كل عنصر وعرض استدعاءات الأدوات—مثل عمليات البحث على الإنترنت، استدعاءات الوظائف، أو البحث في الملفات—قبل طباعة الاستجابة النصية.
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.Extensions.OpenAI;
var projectEndpoint = "your_project_endpoint";
var agentName = "your_agent_name";
AIProjectClient projectClient = new(
endpoint: new Uri(projectEndpoint),
tokenProvider: new DefaultAzureCredential());
ProjectResponsesClient responsesClient
= projectClient.ProjectOpenAIClient.GetProjectResponsesClientForAgent(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 = project.getOpenAIClient();
const response = await openai.responses.create(
{ input: "What happened in the news today?" },
{ body: { 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.AgentReference;
import com.azure.ai.agents.models.AzureCreateResponseOptions;
import com.azure.identity.DefaultAzureCredentialBuilder;
import com.openai.models.responses.Response;
import com.openai.models.responses.ResponseCreateParams;
import com.openai.models.responses.ResponseOutputItem;
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.createAzureResponse(
new AzureCreateResponseOptions().setAgentReference(agentRef),
ResponseCreateParams.builder()
.input("What happened in the news today?"));
// Print each output item, including tool calls
for (ResponseOutputItem item : response.output()) {
item.webSearchCall().ifPresent(ws ->
System.out.println("[Tool] Web search: status=" + ws.status()));
item.functionCall().ifPresent(fc ->
System.out.println("[Tool] Function call: " + fc.name()
+ "(" + fc.arguments() + ")"));
item.fileSearchCall().ifPresent(fs ->
System.out.println("[Tool] File search: status=" + fs.status()));
item.message().ifPresent(msg ->
System.out.println("[Assistant] "
+ msg.content().get(0).asOutputText().text()));
}
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'
توليد استجابة دون تخزين
افتراضيا، تخزن الخدمة سجل الاستجابة على جانب الخادم، لذا يمكنك الرجوع previous_response_id إلى سياق متعدد الأدوار. إذا ضبطت store على ، falseفإن الخدمة لا تستمر في الاستجابة باستمرار. يجب أن تنقل سياق المحادثة بنفسك عن طريق تمرير عناصر المخرج السابقة كمدخلات للطلب التالي.
هذا النهج مفيد عندما تحتاج إلى تحكم كامل في حالة المحادثة، أو ترغب في تقليل البيانات المخزنة، أو العمل في بيئة لا تحتفظ بها بيانات.
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.Extensions.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
ProjectResponsesClient responsesClient
= projectClient.ProjectOpenAIClient.GetProjectResponsesClientForAgent(agentName);
ResponseResult response = await responsesClient.CreateResponseAsync(
new CreateResponseOptions
{
InputItems = { ResponseItem.CreateUserMessageItem(
"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 CreateResponseOptions
{
InputItems =
{
ResponseItem.CreateUserMessageItem(
"What is the largest city in France?"),
ResponseItem.CreateAssistantMessageItem(
response.GetOutputText()),
ResponseItem.CreateUserMessageItem(
"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 = project.getOpenAIClient();
// Generate a response without storing
const response = await openai.responses.create(
{ input: "What is the largest city in France?", store: false },
{ body: { 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,
},
{ body: { 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.ai.agents.models.AzureCreateResponseOptions;
import com.azure.identity.DefaultAzureCredentialBuilder;
import com.openai.models.responses.Response;
import com.openai.models.responses.ResponseCreateParams;
import com.openai.models.responses.EasyInputMessage;
import java.util.List;
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.createAzureResponse(
new AzureCreateResponseOptions().setAgentReference(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.createAzureResponse(
new AzureCreateResponseOptions().setAgentReference(agentRef),
ResponseCreateParams.builder()
.inputOfResponse(List.of(
EasyInputMessage.builder()
.role(EasyInputMessage.Role.USER)
.content("What is the largest city in France?").build(),
EasyInputMessage.builder()
.role(EasyInputMessage.Role.ASSISTANT)
.content(response.outputText()).build(),
EasyInputMessage.builder()
.role(EasyInputMessage.Role.USER)
.content("What is the population of that city?").build()))
.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"
}
}'
المحادثات وعناصر المحادثة
المحادثات أشياء متينة لها معرفات فريدة. بعد الإنشاء، يمكنك إعادة استخدامها عبر الجلسات.
تخزن المحادثات عناصر، والتي قد تشمل الرسائل، واستدعاءات الأدوات، ومخرجات الأدوات، وبيانات أخرى.
أنشئ محادثة
المثال التالي ينشئ محادثة مع رسالة مستخدم أولية. استخدم عميل OpenAI (المستخرج من عميل المشروع) للمحادثات والاستجابات.
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.Extensions.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.ProjectOpenAIClient.GetProjectConversationsClient().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 = 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.identity.DefaultAzureCredentialBuilder;
import com.openai.models.conversations.Conversation;
import com.openai.services.blocking.ConversationService;
// Format: "https://resource_name.services.ai.azure.com/api/projects/project_name"
String projectEndpoint = "your_project_endpoint";
// Create conversations client to call Foundry API
ConversationService conversationService = new AgentsClientBuilder()
.credential(new DefaultAzureCredentialBuilder().build())
.endpoint(projectEndpoint)
.buildOpenAIClient()
.conversations();
// Create a conversation
Conversation conversation = conversationService.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?"
}
]
}'
متى تستخدم المحادثة
استخدم محادثة عندما تريد:
-
استمرارية الأدوار المتعددة: حافظ على تاريخ مستقر عبر الأدوار دون إعادة بناء السياق بنفسك.
-
الاستمرارية عبر الجلسات: أعد استخدام نفس المحادثة لمستخدم يعود لاحقا.
-
تصحيح الأخطاء: فحص ما حدث مع مرور الوقت (مثل استدعاءات الأدوات والمخرجات).
عندما تستخدم المحادثة لتوليد استجابة (مع وكيل أو بدونه)، يتم توفير المحادثة الكاملة كمدخل للنموذج. ثم يتم إلحاق الرد المولد بنفس المحادثة.
ملاحظة
إذا تجاوزت المحادثة حجم السياق المدعوم للنموذج، سيقوم النموذج تلقائيا باختصار سياق الإدخال. المحادثة نفسها ليست مختصرة، بل تستخدم فقط جزءا منها لتوليد الرد.
إذا لم تنشئ محادثة، يمكنك بناء تدفقات متعددة الأدوار باستخدام مخرجات الاستجابة السابقة كنقطة انطلاق للطلب التالي. هذا النهج يمنحك مرونة أكبر من النمط القديم المعتمد على الخيوط، حيث كانت الحالة مرتبطة بإحكام مع كائنات الخيط. للحصول على إرشادات الترحيل، راجع Migration إلى Agents SDK.
أنواع عناصر المحادثة
المحادثات تخزن العناصر بدلا من الرسائل المحادثة فقط. العناصر تلتقط ما حدث أثناء توليد الاستجابة حتى يتمكن الدور التالي من إعادة استخدام هذا السياق.
تشمل أنواع العناصر الشائعة:
-
عناصر الرسالة: رسائل المستخدم أو المساعد.
-
عناصر استدعاء الأداة: سجلات استدعاءات الأدوات التي حاول الوكيل استخدامها.
-
عناصر مخرجات الأداة: المخرجات التي تعيدها الأدوات (على سبيل المثال، نتائج الاسترجاع).
-
العناصر المخرجة: محتوى الاستجابة الذي تعرضه للمستخدم.
إضافة عناصر إلى المحادثة
بعد إنشاء محادثة، استخدم conversations.items.create() ذلك لإضافة رسائل مستخدم لاحقة أو عناصر أخرى.
# 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.createAzureResponse(
new AzureCreateResponseOptions().setAgentReference(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?"
}
]
}'
استخدم محادثة مع وكيل
اجمع بين المحادثة ومرجع الوكيل للحفاظ على التاريخ عبر عدة أدوار. يقوم الوكيل بمعالجة جميع العناصر في المحادثة ويضيف مخرجاته تلقائيا.
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.Extensions.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.ProjectOpenAIClient.GetProjectConversationsClient().CreateProjectConversationAsync();
// First turn
ProjectResponsesClient responsesClient
= projectClient.ProjectOpenAIClient.GetProjectResponsesClientForAgent(
agentName, conversation);
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 = 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?" },
{ body: { 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?" },
{ body: { 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.ai.agents.models.AzureCreateResponseOptions;
import com.azure.identity.DefaultAzureCredentialBuilder;
import com.openai.models.conversations.Conversation;
import com.openai.models.responses.Response;
import com.openai.models.responses.ResponseCreateParams;
import com.openai.services.blocking.ConversationService;
String projectEndpoint = "your_project_endpoint";
String agentName = "your_agent_name";
AgentsClientBuilder builder = new AgentsClientBuilder()
.credential(new DefaultAzureCredentialBuilder().build())
.endpoint(projectEndpoint);
ResponsesClient responsesClient = builder.buildResponsesClient();
ConversationService conversationService
= builder.buildOpenAIClient().conversations();
// Create a conversation for multi-turn chat
Conversation conversation = conversationService.create();
// First turn
AgentReference agentRef = new AgentReference(agentName);
Response response = responsesClient.createAzureResponse(
new AzureCreateResponseOptions().setAgentReference(agentRef),
ResponseCreateParams.builder()
.conversation(conversation.id())
.input("What is the largest city in France?"));
System.out.println(response.output());
// Follow-up turn in the same conversation
Response followUp = responsesClient.createAzureResponse(
new AzureCreateResponseOptions().setAgentReference(agentRef),
ResponseCreateParams.builder()
.conversation(conversation.id())
.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"
}
}'
للحصول على أمثلة تظهر كيف تعمل المحادثات والردود معا في الكود، انظر إنشاء واستخدام الذاكرة في خدمة وكلاء المسبح.
البث والردود الخلفية
للعمليات طويلة الأمد، يمكنك إرجاع النتائج تدريجيا باستخدام streaming الوضع أو تشغيله بشكل غير متزامن تماما باستخدام background الوضع. في هذه الحالات، عادة ما تراقب الاستجابة حتى تنتهي ثم تستهلك العناصر النهائية المخرجة.
استمر ردا
البث يعيد نتائج جزئية فور توليدها. هذا النهج مفيد لعرض النتائج للمستخدمين في الوقت الحقيقي.
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.Extensions.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
ProjectResponsesClient responsesClient
= projectClient.ProjectOpenAIClient.GetProjectResponsesClientForAgent(agentName);
await foreach (StreamingResponseUpdate update
in responsesClient.CreateResponseStreamingAsync(
"Explain how agents work in one paragraph."))
{
if (update is StreamingResponseOutputTextDeltaUpdate textDelta)
{
Console.Write(textDelta.Delta);
}
}
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 = project.getOpenAIClient();
// Stream a response using the agent
const stream = await openai.responses.create(
{ input: "Explain how agents work in one paragraph.", stream: true },
{ body: { 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);
}
}
import com.azure.ai.agents.*;
import com.azure.ai.agents.models.AgentReference;
import com.azure.ai.agents.models.AzureCreateResponseOptions;
import com.azure.core.util.IterableStream;
import com.azure.identity.DefaultAzureCredentialBuilder;
import com.openai.models.responses.ResponseCreateParams;
import com.openai.models.responses.ResponseStreamEvent;
// Format: "https://resource_name.services.ai.azure.com/api/projects/project_name"
String projectEndpoint = "your_project_endpoint";
String agentName = "your_agent_name";
AgentsClientBuilder builder = new AgentsClientBuilder()
.credential(new DefaultAzureCredentialBuilder().build())
.endpoint(projectEndpoint);
ResponsesClient responsesClient = builder.buildResponsesClient();
// Stream a response using the agent
AgentReference agentRef = new AgentReference(agentName);
IterableStream<ResponseStreamEvent> events =
responsesClient.createStreamingAzureResponse(
new AzureCreateResponseOptions()
.setAgentReference(agentRef),
ResponseCreateParams.builder()
.input("Explain how agents work in one paragraph."));
for (ResponseStreamEvent event : events) {
event.outputTextDelta()
.ifPresent(textEvent ->
System.out.print(textEvent.delta()));
}
# 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"
}
}'
للحصول على تفاصيل حول أوضاع الاستجابة وكيفية استهلاك المخرجات، راجع واجهة برمجة التطبيقات (Responses API).
تشغيل وكيل في وضع الخلفية
وضع الخلفية يشغل الوكيل بشكل غير متزامن، وهو أمر مفيد للمهام طويلة الأمد مثل التفكير المعقد أو توليد الصور. قم بتعيين background إلى true ثم قم باستطلاع حالة الرد حتى يكملها.
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.Extensions.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
ProjectResponsesClient responsesClient
= projectClient.ProjectOpenAIClient.GetProjectResponsesClientForAgent(agentName);
ResponseResult response = await responsesClient.CreateResponseAsync(
new CreateResponseOptions
{
InputItems = { ResponseItem.CreateUserMessageItem(
"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 = 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,
},
{ body: { 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);
import com.azure.ai.agents.*;
import com.azure.ai.agents.models.AgentReference;
import com.azure.ai.agents.models.AzureCreateResponseOptions;
import com.azure.identity.DefaultAzureCredentialBuilder;
import com.openai.models.responses.Response;
import com.openai.models.responses.ResponseCreateParams;
import com.openai.models.responses.ResponseStatus;
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();
// Start a background response using the agent
AgentReference agentRef = new AgentReference(agentName);
Response response = responsesClient.createAzureResponse(
new AzureCreateResponseOptions().setAgentReference(agentRef),
ResponseCreateParams.builder()
.input("Write a detailed analysis of renewable energy trends.")
.background(true));
while (response.status().orElse(null) == ResponseStatus.QUEUED
|| response.status().orElse(null) == ResponseStatus.IN_PROGRESS) {
Thread.sleep(1000);
response = responsesClient.getResponseService().retrieve(response.id());
}
System.out.println("Response status: " + response.status().orElse(null));
System.out.println(response.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"
# 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'
ربط الذاكرة بوكيل (معاينة)
تمنح الذاكرة الوكلاء القدرة على الاحتفاظ بالمعلومات عبر الجلسات، بحيث يمكنهم تخصيص الردود واستدعاء تفضيلات المستخدم مع مرور الوقت. بدون ذاكرة، تبدأ كل محادثة من الصفر.
توفر خدمة Foundry Agent حل ذاكرة مدارة (معاينة) تقوم بتكوينه من خلال مخازن الذاكرة. يحدد مخزن الذاكرة أنواع المعلومات التي يجب أن يحتفظ بها الوكيل. قم بإرفاق مخزن ذاكرة بوكيلك، وسيستخدم الوكيل الذكريات المخزنة كسياق إضافي أثناء توليد الردود.
المثال التالي ينشئ مخزن ذاكرة ويربطه بوكيل.
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.BetaMemoryStoresClient;
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
BetaMemoryStoresClient memoryStoresClient = new AgentsClientBuilder()
.credential(new DefaultAzureCredentialBuilder().build())
.endpoint(projectEndpoint)
.beta()
.buildBetaMemoryStoresClient();
// 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
}
}
}'
للتفاصيل المفاهيمية، انظر الذاكرة في خدمة وكيل المسبك. للحصول على إرشادات كاملة للتنفيذ، راجع إنشاء واستخدام الذاكرة.
الأمن والتعامل مع البيانات
نظرا لأن المحادثات والردود يمكن أن تستمر في المحتوى والمخرجات التي يوفرها المستخدمون، تعامل بيانات وقت التشغيل كبيانات تطبيق:
-
تجنب تخزين الأسرار في المحفزات أو سجل المحادثات. استخدم الاتصالات والمخازن السرية المدارة بدلا من ذلك (على سبيل المثال، قم بإعداد اتصال Key Vault).
-
استخدم أقل امتياز للوصول إلى الأداة. عندما تصل الأداة إلى أنظمة خارجية، يمكن للوكيل قراءة أو إرسال البيانات من خلال تلك الأداة.
-
كن حذرا مع غير خدمات Microsoft. إذا استدعى وكيلك أدوات مدعومة بخدمات غير خدمات Microsoft، فقد تتدفق بعض البيانات إلى تلك الخدمات. للاعتبارات ذات الصلة، راجع اكتشف الأدوات في أدوات المسبك.
الحدود والقيود
يمكن أن تعتمد الحدود على النموذج، والمنطقة، والأدوات التي توصلها (على سبيل المثال، توفر البث ودعم الأدوات). للاطلاع على التوفر الحالي والقيود على الردود، راجع واجهة برمجة التطبيقات للاستجابات.
محتوى ذو صلة