Generera strukturerade utdata

Arbeta med Llama 3

Imtihan Ahmed

Machine Learning Engineer

Strukturerade utdata i JSON

  • Exempel: Llama-svar kan matas in i en dashboard

  • Oformaterade textsvar fungerar inte ❌

  • Vi behöver strukturerade utdata ✅

Anställd på ett analystföretag för mat och dryck

Diagram över automatisering av rapporter för restauranger

Arbeta med Llama 3

JSON-svar med chattkompletering

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."} ]
Arbeta med Llama 3

JSON-svar med chattkompletering

output = llm.create_chat_completion(
         messages = message_list,

response_format = "json_object"
)
  • Svarsformat anges som JSON
  • Llama genererar ett strukturerat svar utan fri text
Arbeta med Llama 3

Extrahera JSON-svaret

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
    },... ]
}
Arbeta med Llama 3

Definiera ett schema

response_format = {
"type": "json_object",

"schema": {
"type": "object",
"properties": { "Product Name": {"type": "string"}, "Category": {"type": "string"}, "Sales Growth": {"type": "float"}}
}
}
  • Du kan ange ett schema: regler för hur data ska formateras
Arbeta med Llama 3

Definiera ett 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
}
Arbeta med Llama 3

Nu kör vi en övning!

Arbeta med Llama 3

Preparing Video For Download...