Tlola ho ea ho litaba
Diphoso

Diphoso

Kopo e hlolehang e khutlisa khoutu ea boemo ba HTTP le body ea JSON e nang le mofuta oa phoso le molaetsa. Leqephe lena le thathamisa boemo bo bong le bo bong, le bontša body ea phoso ea sebopeho se seng le se seng sa API mme le re ke liphoso life tseo ho leng molemo ho li romela hape.

Li-SDK li hlahisa ntho ea phoso e nang le khoutu ea boemo le li-field tsa body. Kopo ena e reha model e sa tsoeng teng:

import openai
from openai import OpenAI

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

try:
    client.chat.completions.create(
        model="no-such-model",
        messages=[{"role": "user", "content": "Hello"}],
    )
except openai.APIStatusError as error:
    print(error.status_code)                           # 400
    print(error.type)                                  # invalid_request_error
    print(error.body["message"])                       # unknown model: no-such-model
    print(error.response.headers.get("x-request-id"))  # the id of this request

E khutlisa boemo ba 400 le body ena:

400 JSON
{
  "error": {
    "type": "invalid_request_error",
    "message": "unknown model: no-such-model"
  }
}

Body ea phoso

Ho na le li-body tse peli. /v1/messages e araba ka sebopeho sa Anthropic; endpoint e 'ngoe le e 'ngoe e araba ka sebopeho sa OpenAI. Ka bobeli, lintlha li ho error.type le error.message, kahoo moreki a le mong o sebeletsa li-endpoint tsohle.

401 Sebopeho sa OpenAI
{
  "error": {
    "type": "authentication_error",
    "message": "Invalid API key",
    "code": "invalid_api_key",
    "param": null
  }
}
401 Sebopeho sa Anthropic
{
  "type": "error",
  "error": {
    "type": "authentication_error",
    "message": "Invalid API key"
  }
}
Field Mofuta Tlhaloso
error.type string Mofuta oa phoso. Bona Mefuta ea liphoso ka tlase.
error.message string Polelo bakeng sa motho. Mengolo e litafoleng tse ka tlase e tsitsitse ntle le likarolo tsa eona tse fetohang, tse bontšitsoeng e le <id>, <n> kapa ….
error.code string | null E teng ho liphoso tse ling tsa sebopeho sa OpenAI: invalid_api_key le 401, request_too_large le 413, context_length_exceeded ha moqoqo o le molelele haholo, ho seng joalo ke null kapa ha e eo. Etsa qeto ho latela boemo le error.type pele mme u nke code e le tlatsetso.
error.param null E teng liphosong tse tšoanang le code. Kamehla ke null.
type string Sebopeho sa Anthropic feela. Kamehla ke error.

Mefuta ea liphoso

Mofuta Maemo Tlhaloso
invalid_request_error 400, 413, 415, 422 Kopo ka boeona e fosahetse: field, body, id ea model kapa input eo model e sa e amoheleng. Fetola kopo pele u e romela hape.
authentication_error 401 Senotlolo sa API ha se eo, ha se tsejoe kapa se hlakotsoe.
not_found_error 404 Tsela ha e eo.
rate_limit_error 429 Balance ha e koahele kopo, flood protection e e emisitse, kapa model e phathahane. Molaetsa o re ke efe.
api_error 500, 502, 503, 504 Kopo e ne e le ntle mme ho hloleha ho lehlakoreng la rona. E romele hape.
server_error 500 Kopo e ne e le ntle mme ho hloleha ho lehlakoreng la rona. E romele hape.

Likhoutu tsa boemo

Boemo Mofuta Molaetsa Neng
400 invalid_request_error Failed to parse the request body as JSON: … Body hase JSON e nepahetseng.
400 invalid_request_error unknown model: <id> model hase id e phatlalalitsoeng. Ho /v1/responses le ha model e sieo.
400 invalid_request_error No user message provided Li-tier tsa Shannon: kopo ha e na mongolo oa user.
400 invalid_request_error <id> does not accept image input Setšoantšo se rometsoe ho model e hosted ea open-weight e se nang input ea setšoantšo.
400 invalid_request_error audio and video input are not supported by any hosted model Karolo ea audio kapa video e rometsoe ho model e hosted ea open-weight.
400 invalid_request_error <id> does not accept response_format Structured output e kopiloe ho model e hosted ea open-weight e se nang eona.
400 invalid_request_error <id> does not accept response_format json_schema; use json_object JSON schema e rometsoe ho model e hosted ea open-weight e amohelang json_object feela.
400 invalid_request_error unknown reasoning effort '<value>'; expected off, low, medium or high Reasoning effort hase e 'ngoe ea litekanyo tse thathamisitsoeng. Li-model tse hosted tsa open-weight.
400 invalid_request_error count_tokens is available for the hosted open models; unknown model: <id> Ho bala tokens ho kopiloe bakeng sa model e kantle ho li-model tse hosted tsa open-weight.
401 authentication_error Missing authentication Ha ho senotlolo sa API se rometsoeng.
401 authentication_error Invalid API key Senotlolo ha se tsejoe, se nkeloe sebaka ke se secha, kapa se hlakotsoe.
404 not_found_error Not Found Tsela ha e eo, mohlala /v1/embeddings.
405 api_error Method Not Allowed Tsela e teng empa hase ka mokhoa ona oa HTTP.
413 invalid_request_error Failed to buffer the request body: … Body ea kopo e kholo ho feta 32 MiB.
415 invalid_request_error Expected request with `Content-Type: application/json` Header ea Content-Type ha e eo kapa hase application/json.
422 invalid_request_error Failed to deserialize the JSON body into the target type: … Field e hlokahalang ha e eo, joalo ka messages, kapa field e na le mofuta o fosahetseng oa JSON.
429 rate_limit_error Quota exceeded. Upgrade your plan at shannon-ai.com/plan Moeli oa output oa kopo o moholo ho feta se setseng ho balance ea hau.
429 rate_limit_error Too many requests. Retry in <n>s. Flood protection: likopo tse fetang 120 ka motsotso o le mong ho akhaonte ea hau. <n> ke palo ea metsotsoana ho fihlela motsotso o fela.
429 rate_limit_error Shannon Coder call quota reached. Upgrade your plan at shannon-ai.com/plan shannon-coder-1 ho /v1/chat/completions le /v1/messages: likopo tsa Shannon Coder tsa plan ea hau bakeng sa fensetere ea hajoale ea lihora tse 4 li felile.
429 rate_limit_error Shannon routes are temporarily busy. Please retry. Model e phathahane ka nako ena.
500 server_error The model backend failed to answer. Please retry. Model ha ea ka ea hlahisa karabo.
500 server_error An internal error occurred. Please retry. Phoso ea ka hare ha kopo e ntse e lokisoa.
502 api_error The model backend failed to answer. Please retry. Model ha ea ka ea hlahisa karabo. Lelapa la Shannon 3 le li-model tse hosted tsa open-weight.
503 api_error Could not verify your quota right now. Please retry. Balance ea hau e ne e sa balehe ka nako ena.
503 api_error token counting is temporarily unavailable for this model Ho bala tokens ha ho fumanehe bakeng sa model ena ka nako ena.
504 api_error upstream timed out Model e hosted ea open-weight e nkile nako e telele ho feta moeli oa nako oa kopo e se nang streaming.

Liphatlalatso li etsoa ka tatellano ena: senotlolo sa API, body ea kopo, id ea model, flood protection, balance. Kopo e nang le senotlolo se fosahetseng le body e fosahetseng ka hona e khutlisa 401. Kopo e hanoang ka boemo ba 4xx ha e lefisoe.

Balance le flood protection

Kopo e 'ngoe le e 'ngoe e sebeletsoa ka ho lekana: ha ho li-tier tsa rate mme ha ho quota e arohaneng ea API. Lintho tse peli li ntse li ka araba ka 429, ka bobeli le mofuta rate_limit_error. Molaetsa o li khetholla.

Balance

Balance ea hau ke allowance ea plan ea kajeno, e khutlang ka 00:00 UTC, mme ka mor'a eona credit ea hau e rekiloeng. Chat le API li ntša ho balance e le 'ngoe.

Kopo e 'ngoe le e 'ngoe e behela thoko moeli oa eona oa output pele: max_tokens, kapa max_output_tokens ho /v1/responses, 4,096 ha u sa romele ea bobeli. Ha karabo e phethahetse, palo e behetsoeng thoko e nkeloa sebaka ke seo kopo e se sebelisitseng. Haeba palo e sa kene ho balance e setseng, kopo e khutlisa Quota exceeded pele model e qala.

Likopo tse sebetsang ka nako e le 'ngoe e 'ngoe e behela thoko palo ea eona. Ka hona, likopo tse ngata tsa parallel tse nang le max_tokens e phahameng li ka fetola balance ka nakoana, esita le ha karabo e 'ngoe le e 'ngoe e khutšoane. max_tokens e tlase e behela thoko tse fokolang.

Flood protection

Flood protection e lumella likopo tse 120 ka motsotso ka akhaonte. E bala akhaonte, eseng senotlolo, ho /v1/chat/completions, /v1/responses le /v1/messages hammoho. Motsotso o qala ka kopo ea hau ea pele.

Kopo ea nomoro ea 121 ka hare ho motsotso oo e khutlisa Too many requests. Retry in <n>s. mme ha e jele letho. Likopo tse hanoang lia baloa le tsona, kahoo moreki ea romelang hape a sa emela o lula a hanoa ho fihlela motsotso o fela. Emela metsotsoana ea <n> ho tsoa molaetsing.

Likopo tse romeloang ka nako e le 'ngoe ha li hanoe ka lebaka la ho ba parallel. Li ema moleng mme li arajoa ka tatellano.

GET /v1/models le li-endpoint tsa ho bala tokens ha li baloe.

Tse ling mabapi le meeli le balance, le moo u ka bonang balance le usage ea hau: Meeli le balance Keys & usage

Seo u lokelang ho se leka hape

Romela kopo hape feela ha kopo e tšoanang e ka atleha. Li-SDK tsa OpenAI le Anthropic li se li leka hape likarabo tsa 429 le 5xx makhetlo a mabeli ka bo tsona; beha max_retries (maxRetries ho JavaScript) ho fetola sena.

Phoso Romela hape? Joang
400, 404, 405, 413, 415, 422 Che. Lokisa kopo pele. Molaetsa o reha field, model kapa input e fosahetseng.
401 Che. Sebelisa senotlolo se nepahetseng. Etsa kapa nkeloa senotlolo sebaka leqepheng la Keys & usage.
429 Too many requests Ee, ka mor'a ho ema. Emela palo ea metsotsoana e molaetsing, ebe u romela kopo e tšoanang.
429 Quota exceeded Eseng joalo ka ha e le. Fokotsa max_tokens, emela reset ea letsatsi le letsatsi ka 00:00 UTC, kapa eketsa credit.
429 Shannon Coder call quota reached Ee, fensetereng e latelang. Mafensetere a qala lihora tse 4 tse ling le tse ling ho tloha ho 00:00 UTC. Model e 'ngoe e araba hanghang.
429 … temporarily busy Ee. Emela metsotsoana e seng mekae, ebe u eketsa nako ho leka ho latelang ho leng ho leng.
500, 502, 503 Ee. Emela motsotsoana o le 1, ebe 2, 4 le 8. Ema ka mor'a boiteko bo seng bokae mme u tlaleha id ea kopo.
504 Ee. E romele ka stream e behiloeng ho true: moeli oa nako o sebetsa ho likarabo tse se nang streaming.

Retry loop e latelang tafole ena:

import re
import time

import openai
from openai import OpenAI

# max_retries=0: this loop does the retrying, the SDK does not add its own.
client = OpenAI(api_key="YOUR_API_KEY", base_url="https://api.shannon-ai.com/v1", max_retries=0)


def create_with_retry(attempts=5, **request):
    for attempt in range(attempts):
        try:
            return client.chat.completions.create(**request)
        except openai.RateLimitError as error:
            text = str(error)
            flood = re.search(r"Retry in (\d+)s", text)
            if flood:
                time.sleep(int(flood.group(1)))   # flood protection: wait out the minute
            elif "temporarily busy" in text:
                time.sleep(2 ** attempt)
            else:
                raise                             # balance: a wait of seconds does not help
        except (openai.InternalServerError, openai.APIConnectionError):
            time.sleep(2 ** attempt)              # 1, 2, 4, 8 seconds
    raise RuntimeError("the request failed after all attempts")


response = create_with_retry(
    model="shannon-3",
    messages=[{"role": "user", "content": "Hello"}],
)
print(response.choices[0].message.content)

Liphoso ka hare ho stream

Stream e na le boemo ba 200 ho tloha ho byte ea eona ea pele. Ho hloleha ka mor'a moo ho fihla e le event ka hare ho stream: chunk e nang le setho sa error ho /v1/chat/completions, event ea error ho /v1/messages, event ea response.failed kapa error ho /v1/responses. Li-event tsa ho koala tsa stream li ntse li latela. Nka karabo e joalo e le e hlolehileng mme u romele kopo hape, joalo ka ha u ka etsa ka boemo ba 5xx.

Moqoqo o molelele ho feta context window ea model o tlalehoa ka tsela ena, o nang le mofuta invalid_request_error le code context_length_exceeded. Khutsufatsa moqoqo pele u romela hape.

Li-frame tse nepahetseng li hlalositsoe le streaming. Phallela

Li-id tsa likopo

Karabo e 'ngoe le e 'ngoe, ho kenyelletsa liphoso, e na le header ea x-request-id. Ke boleng boo u bo rometseng ho header ea hau ea x-request-id, kapa litlhaku tse 12 tsa hexadecimal ha u sa romele letho. E ngole ho log, mme u e qotse ha u kopa thuso ka kopo.