Leum gun t-susbaint
Toraidhean structarail

Toraidhean structarail

Iarr am freagairt mar JSON: nì JSON sam bith, no JSON a leanas sgeama a chuireas tu. Cleachd e nuair a leughas prògram, chan e neach, am freagairt.

POST https://api.shannon-ai.com/v1/chat/completions

import json
from openai import OpenAI

client = OpenAI(api_key="YOUR_API_KEY", base_url="https://api.shannon-ai.com/v1")

response = client.chat.completions.create(
    model="Kimi-K3-3BIT-REAP",
    messages=[
        {"role": "user", "content": "Extract the person: John Doe, 30 years old, engineer."}
    ],
    response_format={
        "type": "json_schema",
        "json_schema": {
            "name": "person",
            "strict": True,
            "schema": {
                "type": "object",
                "properties": {
                    "name": {"type": "string"},
                    "age": {"type": "integer"},
                    "occupation": {"type": "string"},
                },
                "required": ["name", "age", "occupation"],
            },
        },
    },
)

# The JSON arrives as text in message.content: parse it, then check it.
try:
    person = json.loads(response.choices[0].message.content)
except json.JSONDecodeError:
    person = None  # ask again, or report the failure

print(person)

Is e an JSON teacsa an fhreagairt, ann an choices[0].message.content:

200 JSON
{
  "id": "chatcmpl-0c4e7a1b9d2f4e6a8b3c5d7e9f1a2b3c",
  "object": "chat.completion",
  "created": 1791590400,
  "model": "Kimi-K3-3BIT-REAP",
  "choices": [
    {
      "index": 0,
      "message": {
        "role": "assistant",
        "content": "{\"name\":\"John Doe\",\"age\":30,\"occupation\":\"engineer\"}",
        "reasoning_content": null
      },
      "finish_reason": "stop"
    }
  ],
  "usage": {
    "prompt_tokens": 96,
    "completion_tokens": 19,
    "total_tokens": 115,
    "prompt_tokens_details": {"cached_tokens": 0},
    "completion_tokens_details": {"reasoning_tokens": 0}
  }
}

Modhan response_format

Is e raon de /v1/chat/completions a th’ ann an response_format. Às aonais tha am freagairt na theacsa àbhaisteach.

Modh Luach Na gheibh thu
Nì JSON {"type": "json_object"} Tha am freagairt na JSON gun chumadh òrdaichte. Abair sa phrompt dè na h-iuchraichean a tha thu ag iarraidh.
JSON schema {"type": "json_schema", "json_schema": {"name": "…", "schema": {…}}} Leanaidh am freagairt an sgeama a chuireas tu: na h-iuchraichean, na seòrsaichean agus na raointean riatanach aige.
Strict "strict": true Raon de json_schema, chan e treas modh. Tha e true mura cuir thu false.
Raon Seòrsa Bun-roghainn Tuairisgeul Air a chur an sàs le
type string json_object no json_schema. Riatanach am broinn response_format. Thèid text a ghabhail agus bheir e freagairt teacsa àbhaisteach. A h-uile modail a ghabhas am modh
json_schema.schema object An JSON Schema a leanas am freagairt. Cuir e a h-uile uair a tha type json_schema. A h-uile modail a ghabhas am modh
json_schema.name string Leubail airson an sgeama, mar ann an cruth OpenAI. Modailean open-weight hosted
json_schema.strict boolean true Co-dhiù a dh’fheumas am freagairt an sgeama a leantainn dìreach. Cuiridh na modailean Shannon gach sgeama an gnìomh mar strict. Modailean open-weight hosted

Chan eil feum air sgeama sa mhodh nì JSON. Ainmich na h-iuchraichean sa phrompt:

Bodhaig an iarrtais
{
  "model": "shannon-3",
  "messages": [
    {
      "role": "user",
      "content": "Name the capital of France. Answer as JSON with the keys city and country."
    }
  ],
  "response_format": {"type": "json_object"}
}

Taic gach modail

Modail json_object json_schema
A h-uile modail Shannon (shannon-*) Tha Tha
Modailean open-weight hosted, ach a-mhàin an fheadhainn a tha ainmichte gu h-ìosal Tha Tha
Laguna-S-2.1-W4A16-AUTOROUND-REAP — —
inkling-W4A16-AUTOROUND-REAP Tha —

Tha GET /v1/models ag aithris an aon rud gach id: capabilities.json_schema air gach modail, agus capabilities.response_format air na modailean open-weight hosted. Modailean & prìsean

Faclan-iuchrach sgeama a thathar a’ toirt taic dhaibh

Tha na gheibh modail dhen sgeama agad an urra ris a’ mhodail agus ris an endpoint:

Modailean /v1/chat/completions /v1/responses
Modailean Shannon Fo-sheata nam facal-iuchrach gu h-ìosal, air a chur an gnìomh mar strict. An sgeama mar a chuireas tu e, air a chur an gnìomh mar strict.
Modailean open-weight hosted An sgeama mar a chuireas tu e. Tha strict true mura cuir thu e. An sgeama mar a chuireas tu e. Tha strict true mura cuir thu e.

Fo-sheata nam facal-iuchrach aig na modailean Shannon air /v1/chat/completions:

Facal-iuchrach Mar a thèid a leughadh
Faclan-iuchrach air an leughadh type, format, title, description, nullable, enum, items, properties, required, minItems, maxItems, minimum, maximum, minLength, maxLength, pattern, anyOf, default
$ref Air fuasgladh o $defs no definitions aig mullach an sgeama. Thèid faclan-iuchrach a sgrìobhar ri taobh $ref, leithid description, a chumail. Thèid iomradh gun mhìneachadh a fhreagras ris a leughadh mar {"type": "object"}.
allOf Thèid na buill a cho-aonadh gu aon sgeama. Far a bheil dà bhall a’ suidheachadh an aon fhacail-iuchrach, bidh am fear nas anmoiche a’ cunntadh.
oneOf Air a leughadh mar anyOf.
Sgeamaichean a tha a’ toirt iomradh orra fhèin Air am meudachadh gu 24 ìre. Thèid ìre nas doimhne a leughadh mar {"type": "object"}.
Taobh a-muigh an fho-sheata A h-uile facal-iuchrach eile, mar eisimpleir additionalProperties, const, multipleOf, uniqueItems, exclusiveMinimum, exclusiveMaximum, patternProperties, prefixItems, minProperties, maxProperties, not agus if / then / else. Chan eil iad sin nam pàirt dhen sgeama a gheibh am modail.

Air /v1/responses: text.format

Tha /v1/responses a’ sgrìobhadh an aon iarrtais mar text.format. Tha an sgeama dìreach ann an format, ri taobh name agus strict, chan ann fo iuchair json_schema. Airson modh nì JSON cuir {"format": {"type": "json_object"}}.

Bodhaig an iarrtais
{
  "model": "Kimi-K3-3BIT-REAP",
  "input": "Extract the person: John Doe, 30 years old, engineer.",
  "text": {
    "format": {
      "type": "json_schema",
      "name": "person",
      "strict": true,
      "schema": {
        "type": "object",
        "properties": {
          "name": {"type": "string"},
          "age": {"type": "integer"},
          "occupation": {"type": "string"}
        },
        "required": ["name", "age", "occupation"]
      }
    }
  }
}

Is e an JSON an text aig a’ phàirt output_text dhen nì message:

200 JSON
{
  "output": [
    {
      "id": "msg_7e1d3c5b9a2f4d6e8c0b1a3f5e7d9c2b",
      "type": "message",
      "role": "assistant",
      "status": "completed",
      "content": [
        {
          "type": "output_text",
          "text": "{\"name\":\"John Doe\",\"age\":30,\"occupation\":\"engineer\"}",
          "annotations": []
        }
      ]
    }
  ]
}

Tha taic gach modail agus na mearachdan mar a tha iad air /v1/chat/completions. Responses API

Air /v1/messages: inneal mar an sgeama

Chan eil raon toraidh structaraichte aig cruth Messages. Airson JSON o na h-aon mhodailean, gairm /v1/chat/completions no /v1/responses leis an aon iuchair.

Gus fuireach air /v1/messages, mìnich an nì mar inneal: cuir an sgeama agad ann an input_schema agus ainmich an t-inneal ann an tool_choice. Is e input a’ bhloc tool_use an uair sin an nì agad, parsaichte mu thràth. Cuiridh na modailean open-weight hosted tool_choice air ainm an gnìomh.

Bodhaig an iarrtais
{
  "model": "Kimi-K3-3BIT-REAP",
  "max_tokens": 1024,
  "messages": [
    {
      "role": "user",
      "content": "Extract the person: John Doe, 30 years old, engineer."
    }
  ],
  "tools": [
    {
      "name": "record_person",
      "description": "Record the extracted person.",
      "input_schema": {
        "type": "object",
        "properties": {
          "name": {"type": "string"},
          "age": {"type": "integer"},
          "occupation": {"type": "string"}
        },
        "required": ["name", "age", "occupation"]
      }
    }
  ],
  "tool_choice": {"type": "tool", "name": "record_person"}
}
200 JSON
{
  "stop_reason": "tool_use",
  "content": [
    {
      "type": "tool_use",
      "id": "toolu_4b8d2f6a1c3e4a5b9d7f0e2c4a6b8d1f",
      "name": "record_person",
      "input": {"name": "John Doe", "age": 30, "occupation": "engineer"}
    }
  ]
}

Dèan cinnteach gu bheil stop_reason tool_use mus leugh thu am bloc. Call gnìomh

Mar a thig an JSON

  • Is e sreang an JSON. Chan eil nì parsaichte ri thaobh san fhreagairt: ruith do pharser JSON air message.content.
  • Le stream: true thig an JSON ann am pìosan delta.content. Cuir còmhla iad agus parsaich aon turas às dèidh crìoch an stream; chan eil pios leis fhèin na JSON dligheach.
  • Freagraidh modail open-weight hosted air iarrtas response_format gun teacsa reasoning: tha reasoning_content null.

Sgrùd na gheibh thu

Stiùiridh an sgeama mar a sgrìobhas am modail. Chan eil an API a’ dèanamh coimeas eadar am freagairt crìochnaichte agus an sgeama agad, agus mar sin nì do chòd an sgrùdadh mu dheireadh:

  • Parsaich am broinn làimhsiche mearachd, mar a nì an sampall aig a’ mhullach.
  • Dearbh an nì parsaichte leis an aon sgeama nad chòd fhèin, mar eisimpleir le leabharlann JSON Schema, Pydantic no Zod.
  • Faodaidh freagairt fhada crìochnachadh mus bi an JSON coileanta. Chan eil freagairt gun streaming ag aithris finish_reason ach mar stop no tool_calls, agus mar sin is e mearachd parsaidh an comharra. Iarr a-rithist, no iarr nì nas lugha.

Mearachdan

Staid Seòrsa Teachdaireachd Cuin
400 invalid_request_error <id> does not accept response_format Chan eil am modail a’ gabhail an dà mhodh.
400 invalid_request_error <id> does not accept response_format json_schema; use json_object Tha am modail a’ gabhail json_object agus chuir thu json_schema.
422 invalid_request_error Failed to deserialize the JSON body into the target type: … Chan eil type aig response_format, no chan e nì JSON a th’ ann.

Thèid an dà fhreagairt 400 a chur mus tèid dad a thoirt bho do balance. Làimhseachadh mearachd