Step 2 of 16
Create an AIAgent, run a response, add streaming, cancellation, and a failure checklist.
ทำ request แรกให้ผ่านก่อน แล้วเก็บ latency เป็น baseline สำหรับเทียบหลังเพิ่ม capability ครับ
Level: Intermediate
เป้าหมายบทนี้คือให้ request แรกผ่านครบเส้นทาง: application สร้าง client, client สร้าง AIAgent, agent เรียก model และ application แสดงผลครับ ยังไม่ต้องใส่ database หรือ tools เพราะเราต้องการ baseline ที่ debug ง่าย
สร้าง agent ผ่าน dependency injection แล้วเปิด endpoint แบบ non-streaming ก่อน จากนั้นเพิ่ม streaming endpoint ที่รองรับ cancellation ครับ
using Azure.AI.Projects;
using Azure.Identity;
using Microsoft.Agents.AI;
var endpoint = Environment.GetEnvironmentVariable("FOUNDRY_PROJECT_ENDPOINT")
?? throw new InvalidOperationException("FOUNDRY_PROJECT_ENDPOINT is missing.");
var model = Environment.GetEnvironmentVariable("FOUNDRY_MODEL")
?? throw new InvalidOperationException("FOUNDRY_MODEL is missing.");
var projectClient = new AIProjectClient(
new Uri(endpoint),
new DefaultAzureCredential());
AIAgent agent = projectClient.AsAIAgent(
model: model,
name: "TPCoderSupport",
instructions: "Help developers understand the internal engineering handbook. " +
"Say when the supplied context is not enough.");
var response = await agent.RunAsync(
"Give me a three-item checklist before deploying an API.");
Console.WriteLine(response);
ลองรันด้วย dotnet run แล้วบันทึก prompt, latency และ response ไว้เป็น baseline ครับ ถ้า authentication ล้มเหลว ให้ตรวจ az account show, endpoint และ role ที่ Foundry project ก่อนแก้ agent code
เก็บ agent creation ใน Infrastructure และ expose interface จาก Application อย่าสร้าง AIProjectClient ใหม่ในทุก request ครับ Client และ agent configuration ควรถูก reuse ผ่าน dependency injection
Streaming ช่วยให้ UI แสดงข้อมูลระหว่างรอ model สร้างคำตอบ:
await foreach (var update in agent.RunStreamingAsync(
"Explain readiness and liveness checks with one example each."))
{
Console.Write(update);
}
อย่ารวม update แต่ละชิ้นเป็น business event เพราะ streaming chunk อาจแบ่งคำในตำแหน่งที่เปลี่ยนไปได้ หากระบบต้อง parse output ให้ใช้ non-streaming response หรือ structured output แล้ว validate schema
คุณควรตอบคำถามเหล่านี้ได้ก่อนเดินต่อครับ:
CancellationToken อย่างไรเพิ่ม smoke test ที่เรียก prompt เดิมและตรวจว่า response ไม่ว่าง จากนั้นเพิ่ม integration test ที่ cancel request แล้วพิสูจน์ว่า CancellationToken ไปถึง agent call ครับ เก็บ live-provider test แยกจาก unit tests และเปิดด้วย environment flag ใน CI
ส่ง agent registration, one non-streaming endpoint, one streaming endpoint, cancellation test และ baseline latency note
บทถัดไปจะเพิ่ม AgentSession เพื่อรักษา context หลาย turn ครับ