1. 使用场景

当前,SiliconCloud 平台的大模型 API 默认生成 非结构化文本,但在一些应用场景中,您可能需要模型以结构化的形式返回结果。直接通过提示词引导大模型输出结构化内容往往难以获得预期的格式。

作为一种标准化且轻量级的数据交换格式,JSON 模式为大模型 API 提供了支持结构化输出的功能。在此模式下,模型返回的数据以 JSON 格式呈现,这不仅便于人类阅读和编写,也方便机器进行解析和处理。

目前,SiliconCloud 平台的主要语言模型已全面支持 JSON 模式,确保模型按预定结构输出数据,方便后续的逻辑解析和处理。更进一步,平台现在还支持了结构化输出(Structured Outputs)模式,为开发者提供了更强大的数据处理和集成功能。

通过 SiliconCloud API,您可以轻松实现以下应用场景的结构化输出:

  • 数据提取与分析:从公司报道中提取新闻标题、链接、发布时间等信息,构建新闻数据库。
  • 情感分析:从商品评论中提取情感极性(正面、负面、中性)、情感强度和情感关键词等情感信息。
  • 产品信息提取:从购买历史中提取产品列表、价格、促销信息等内容。
  • 自动化报告生成:生成包括多个数据点的报告,模型根据预设格式输出相关信息。

这些功能使得数据的解析与处理更加高效,便于将结果直接集成到后续工作流中。

2. 使用方式

2.1 JSON输出使用方法

在请求中添加

response_format={"type": "json_object"}

2.2 Structured Outputs使用方法

定义输出的json_schema

    class Step(BaseModel):
        explanation: str
        output: str
    class MathReasoning(BaseModel):
        steps: list[Step]
        final_answer: str
    json_schema = MathReasoning.model_json_schema()

在请求中添加json_schema

    response_format={
        "type": "json_schema",
        "json_schema": {
            "name": "math_response",
            "schema": json_schema
    }
  }

3. 支持模型列表

目前线上提供的大语言类模型都支持上述参数。

注意:支持的模型情况可能会发生变化,请查阅本文档了解最新支持的模型列表。
你的应用必须检测并处理可能导致模型输出不完整JSON对象的边缘案例。
请合理设置max_tokens,防止JSON字符串被中断。

4. 使用示例

4.1 JSON输出示例

下面是在 openai 中使用的例子:

import json  
from openai import OpenAI

client = OpenAI(
    api_key="您的 APIKEY", # 从https://cloud.siliconflow.cn/account/ak获取
    base_url="https://api.siliconflow.cn/v1"
)

response = client.chat.completions.create(
        model="deepseek-ai/DeepSeek-V2-Chat",
        messages=[
            {"role": "system", "content": "You are a helpful assistant designed to output JSON."},
            {"role": "user", "content": "? 2020 年世界奥运会乒乓球男子和女子单打冠军分别是谁? "
             "Please respond in the format {\"男子冠军\": ..., \"女子冠军\": ...}"}
        ],
        response_format={"type": "json_object"}
    )

print(response.choices[0].message.content)

模型将输出:

{"男子冠军": "马龙", "女子冠军": "陈梦"}

4.2 Structured Outputs示例

下面是在 openai 中使用的例子:

from openai import OpenAI
from pydantic import BaseModel

MODEL_NAME = "Qwen/Qwen2.5-7B-Instruct"
API_KEY = "您的 APIKEY", # 从https://cloud.siliconflow.cn/account/ak获取
client = OpenAI(api_key=API_KEY, base_url="https://api.siliconflow.cn/v1")
class Step(BaseModel):
    explanation: str
    output: str
class MathReasoning(BaseModel):
    steps: list[Step]
    final_answer: str
json_schema = MathReasoning.model_json_schema()
completion = client.chat.completions.create(
    model=MODEL_NAME,
    messages=[
        {"role": "system", "content": "You are a helpful math tutor. Guide the user through the solution step by step."},
        {"role": "user", "content": "how can I solve 8x + 7 = -23"}
    ],
    response_format={
        "type": "json_schema",
        "json_schema": {
            "name": "math_response",
            "schema": json_schema
    }
  }
)
math_reasoning = completion.choices[0].message.content
print(math_reasoning)

模型将输出:

{
    "steps": [
        {
            "explanation": "To solve the equation for x, we need to isolate x on one side of the equation.",
            "output": "8x + 7 = -23"
        },
        {
            "explanation": "First, we need to subtract 7 from both sides to cancel out the 7 on the left side.",
            "output": "8x + 7 - 7 = -23 - 7"
        },
        {
            "explanation": "Simplify the equation.",
            "output": "8x = -30"
        },
        {
            "explanation": "Next, we need to divide both sides by 8 to isolate x.",
            "output": "8x / 8 = -30 / 8"
        },
        {
            "explanation": "Simplify to find the value of x.",
            "output": "x = -30 / 8"
        },
        {
            "explanation": "We can simplify the fraction further by dividing the numerator and the denominator by their greatest common divisor, which is 2.",
            "output": "x = -15 / 4"
        }
    ],
    "final_answer": "The solution to the equation 8x + 7 = -23 is x = -15/4."
}