Перейти к основному содержанию

Сценарии использования

Функция Structured Outputs позволяет модели генерировать ответы, соответствующие предоставленной вами JSON Schema, благодаря чему результаты генерации становятся более контролируемыми и простыми для разбора. Эта функция упрощает последующий анализ и обработку логики, а также помогает интегрировать результаты в бизнес-системы. Она подходит для различных сценариев автоматизации и обработки данных.

Поддерживаемые модели

Следующие модели поддерживают структурированный вывод:

Как использовать

Добавьте в запрос следующую информацию:
  • Настройка параметра: укажите определенную вами JSON Schema с помощью параметра response_format.
  • Инструкции в промпте: направьте модель в промпте на генерацию структурированного вывода.

Пример использования

Ниже приведен полный пример кода на Python, демонстрирующий, как использовать функцию Structured Outputs для генерации JSON-ответа, соответствующего предоставленной вами JSON Schema.

1. Инициализация клиента

Вам нужно инициализировать клиент с помощью вашего API-ключа JieKou AI.
from openai import OpenAI

client = OpenAI(
    base_url="https://api.highwayapi.ai/openai",
    api_key="<Your API Key>",
)

model = "qwen/qwen-2.5-72b-instruct"

2. Определение JSON Schema

Вам нужно определить JSON Schema. В следующем примере создается JSON Schema для извлечения информации о расходах из пользовательского ввода.
# Определите системный промпт для отслеживания расходов.
system_prompt = """You are an expense tracking assistant. 
Extract expense information from the user's input and format it according to the provided schema."""

# Определите JSON Schema для структурированного ответа.
response_format = {
    "type": "json_schema",
    "json_schema": {
        "name": "expense_tracking_schema",
        "schema": {
            "type": "object",
            "properties": {
                "expenses": {
                    "type": "array",
                    "items": {
                        "type": "object",
                        "properties": {
                            "description": {
                                "type": "string",
                                "description": "Description of the expense"
                            },
                            "amount": {
                                "type": "number",
                                "description": "Amount spent in dollars"
                            },
                            "date": {
                                "type": "string",
                                "description": "When the expense occurred"
                            },
                            "category": {
                                "type": "string",
                                "description": "Category of expense (e.g., food, office, travel)"
                            }
                        },
                        "required": [
                            "description",
                            "amount"
                        ]
                    }
                },
                "total": {
                    "type": "number",
                    "description": "Total amount of all expenses"
                }
            },
            "required": [
                "expenses",
                "total"
            ],
        },
    },
}

3. Отправка API-запроса

Создайте API-запрос. Этот запрос включает параметр response_format, который указывает JSON schema, определенную на предыдущем шаге.
chat_completion = client.chat.completions.create(
    model=model,
    messages=[
        {
            "role": "system",
            "content": system_prompt,
        },
        {
            "role": "user",
            "content": """I spent $120 on dinner at an Italian restaurant last Friday with my colleagues.
Also bought office supplies for $45 on Monday.""",
        },
    ],
    max_tokens=1024,
    temperature=0.8,
    stream=False,
    response_format=response_format,
)

response_content = chat_completion.choices[0].message.content

# Разбор и форматирование JSON
try:
    json_response = json.loads(response_content)
    prettified_json = json.dumps(json_response, indent=2)
    print(prettified_json)
except json.JSONDecodeError:
    print("Could not parse response as JSON. Raw response:")
    print(response_content)
Вывод:
{
  "expenses": [
    {
      "date": "2023-03-17",
      "description": "Dinner at Italian restaurant",
      "amount": 120,
      "category": "Food & Dining"
    },
    {
      "date": "2023-03-13",
      "description": "Office supplies",
      "amount": 45,
      "category": "Office Supplies"
    }
  ],
  "total": 165
}

Полный код

from openai import OpenAI
import json

client = OpenAI(
    base_url="https://api.highwayapi.ai/openai",
    api_key="<Your API Key>",
)

model = "qwen/qwen-2.5-72b-instruct"

# Пример структурированного вывода с использованием JSON Schema
# В этом примере создается schema для извлечения информации о расходах

# Определите системный промпт для отслеживания расходов
system_prompt = """You are an expense tracking assistant. 
Extract expense information from the user's input and format it according to the provided schema."""

# Определите JSON schema для структурированного ответа
response_format = {
    "type": "json_schema",
    "json_schema": {
        "name": "expense_tracking_schema",
        "schema": {
            "type": "object",
            "properties": {
                "expenses": {
                    "type": "array",
                    "items": {
                        "type": "object",
                        "properties": {
                            "description": {
                                "type": "string",
                                "description": "Description of the expense"
                            },
                            "amount": {
                                "type": "number",
                                "description": "Amount spent in dollars"
                            },
                            "date": {
                                "type": "string",
                                "description": "When the expense occurred"
                            },
                            "category": {
                                "type": "string",
                                "description": "Category of expense (e.g., food, office, travel)"
                            }
                        },
                        "required": [
                            "description",
                            "amount"
                        ]
                    }
                },
                "total": {
                    "type": "number",
                    "description": "Total amount of all expenses"
                }
            },
            "required": [
                "expenses",
                "total"
            ],
        },
    },
}

chat_completion = client.chat.completions.create(
    model=model,
    messages=[
        {
            "role": "system",
            "content": system_prompt,
        },
        {
            "role": "user",
            "content": """I spent $120 on dinner at an Italian restaurant last Friday with my colleagues.
Also bought office supplies for $45 on Monday.""",
        },
    ],
    max_tokens=1024,
    temperature=0.8,
    stream=False,
    response_format=response_format,
)

response_content = chat_completion.choices[0].message.content

# Разбор и форматирование JSON
try:
    json_response = json.loads(response_content)
    prettified_json = json.dumps(json_response, indent=2)
    print(prettified_json)
except json.JSONDecodeError:
    print("Could not parse response as JSON. Raw response:")
    print(response_content)