การสร้าง Structured Output

การทำงานกับ Llama 3

Imtihan Ahmed

Machine Learning Engineer

Structured Output ในรูปแบบ JSON

  • ตัวอย่าง: ผลลัพธ์จาก Llama อาจถูกนำไปแสดงบน Dashboard

  • ข้อความธรรมดาใช้งานไม่ได้ ❌

  • ต้องการ Structured Output ✅

พนักงานบริษัทวิเคราะห์ข้อมูลอาหารและเครื่องดื่ม

แผนภาพการสร้างรายงานอัตโนมัติสำหรับร้านอาหาร

การทำงานกับ Llama 3

JSON Response ด้วย Chat Completion

response_format = {"type": "json_object"}


message_list = [ {"role": "system", # System role defined as market analyst "content": "You are a food industry market analyst. You analyze sales data and generate structured JSON reports of top-selling beverages."},
{"role": "user", # User role to pass the request "content": "Provide a structured report on the top-selling beverages this year."} ]
การทำงานกับ Llama 3

JSON Response ด้วย Chat Completion

output = llm.create_chat_completion(
         messages = message_list,

response_format = "json_object"
)
  • ระบุ รูปแบบ ผลลัพธ์เป็น JSON
  • Llama สร้างผลลัพธ์แบบมีโครงสร้าง ไม่ใช่ข้อความอิสระ
การทำงานกับ Llama 3

การดึง JSON Response

print(output['choices'][0]['message']['content'])
{
  "report_name": "Top-Selling Beverages 2024",
  "top_beverages": [
    {
      "rank": 1,
      "beverage_name": "Coca-Cola Classic",
      "sales_volume": 2.1,
      "growth_rate": 1.9
    },... ]
}
การทำงานกับ Llama 3

การกำหนด Schema

response_format = {
"type": "json_object",

"schema": {
"type": "object",
"properties": { "Product Name": {"type": "string"}, "Category": {"type": "string"}, "Sales Growth": {"type": "float"}}
}
}
  • ระบุ Schema ได้: กฎที่กำหนดรูปแบบของข้อมูล
การทำงานกับ Llama 3

การกำหนด Schema

output = llm.create_chat_completion(
         messages = message_list,
         response_format = response_format)  

print(output['choices'][0]['message']['content'])
{
  "Product Name": "Coca-Cola",
  "Category": "Soft Drink",
  "Sales Growth": 12.5
}
การทำงานกับ Llama 3

มาฝึกกันเถอะ!

การทำงานกับ Llama 3

Preparing Video For Download...