生成结构化输出

使用 Llama 3

Imtihan Ahmed

Machine Learning Engineer

JSON 中的结构化输出

  • 例:Llama 的回复将作为仪表板的输入

  • 纯文本无法使用 ❌

  • 需要结构化输出 ✅

食品饮料分析公司员工

餐厅报告自动化示意图

使用 Llama 3

使用聊天补全生成 JSON 响应

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 响应

output = llm.create_chat_completion(
         messages = message_list,

response_format = "json_object"
)
  • 将响应格式指定为 JSON
  • Llama 生成结构化响应,无自由文本
使用 Llama 3

提取 JSON 响应

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

Passons à la pratique !

使用 Llama 3

Preparing Video For Download...