Step 4 of 16
Create typed function tools, write useful descriptions, validate inputs, and return structured data.
ต่อ agent เข้ากับ application code ผ่าน contract ขนาดเล็ก พร้อม validation และ typed output ครับ
Level: Intermediate
Agent ตอบจาก model ได้ แต่ยังอ่านข้อมูลของระบบเราไม่ได้ครับ Function tool คือ contract ที่เปิด application capability ให้ model เลือกเรียก โดย Description มีผลต่อการเลือก tool และการสร้าง arguments
เพิ่ม read-only tool หนึ่งตัวที่เรียก application service ผ่าน typed input/output และมี contract tests ครับ
using System.ComponentModel;
using Microsoft.Extensions.AI;
[Description("Find one handbook section by its stable section ID.")]
static HandbookSection? FindSection(
[Description("Stable ID such as deploy-health-checks")] string sectionId)
{
var sections = new Dictionary<string, HandbookSection>
{
["deploy-health-checks"] = new(
"deploy-health-checks",
"Expose readiness and liveness endpoints.")
};
return sections.GetValueOrDefault(sectionId);
}
record HandbookSection(string Id, string Text);
ลงทะเบียน tool ตอนสร้าง agent:
AIAgent agent = projectClient.AsAIAgent(
model: model,
instructions: "Use handbook tools when a section ID is available.",
tools: [AIFunctionFactory.Create(FindSection)]);
เริ่มจาก read-only tool ที่ deterministic ก่อนครับ Tool ควร validate input, รองรับ cancellation สำหรับ I/O, คืนข้อมูลขนาดเล็ก และโยน typed exception ที่ middleware แปลงเป็น safe error ได้ อย่าส่ง database entity ทั้งก้อนกลับไปหา model
ถ้าคำตอบต้องถูกใช้ต่อใน code ให้กำหนด record แทนการ parse prose:
record DeploymentAdvice(
string Summary,
IReadOnlyList<string> Checks,
string RiskLevel);
Structured output ช่วยลด parsing error แต่ยังต้อง validate ค่าทาง business เช่น RiskLevel และจำนวนรายการครับ Schema validation ไม่ได้แทน authorization หรือ domain rule
Tool handler ต้องรับ identity จาก trusted runtime context ไม่ใช่ parameter ที่ model สร้างครับ เช่น tenantId ควรมาจาก authenticated request และถูกส่งผ่าน AgentRunOptions.AdditionalProperties หรือ middleware
สร้าง contract tests สำหรับ valid input, unknown ID, forbidden tenant, timeout และ cancellation จากนั้น run prompt matrix ที่ควรเรียก tool, ไม่ควรเรียก tool และส่ง arguments ผิดรูปแบบครับ บันทึก tool name กับ sanitized outcome โดยไม่เก็บ sensitive payload
ส่ง tool contract, handler, registration, automated tests และ metric สำหรับ call count, latency กับ failures
บทถัดไปจะวาง approval gate หน้า tool ที่สร้าง side effect ครับ