Ukuphathwa kwamaphutha
Isicelo esihlulekayo sibuyisela ikhodi yesimo se-HTTP nomzimba we-JSON onohlobo lwephutha nomlayezo. Leli khasi libala zonke izimo, libonisa umzimba wephutha wefomethi ngayinye ye-API futhi lithi yimaphi amaphutha afanele ukuthunyelwa futhi.
Ama-SDK adala into yephutha ephethe ikhodi yesimo nama-field omzimba. Lesi sicelo siqamba i-model engekho:
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 import OpenAI from "openai";
const client = new OpenAI({
apiKey: "YOUR_API_KEY",
baseURL: "https://api.shannon-ai.com/v1",
});
try {
await client.chat.completions.create({
model: "no-such-model",
messages: [{ role: "user", content: "Hello" }],
});
} catch (error) {
if (!(error instanceof OpenAI.APIError)) throw error;
console.log(error.status); // 400
console.log(error.type); // invalid_request_error
console.log(error.error.message); // unknown model: no-such-model
} curl -i https://api.shannon-ai.com/v1/chat/completions \
-H "Authorization: Bearer YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "no-such-model",
"messages": [{"role": "user", "content": "Hello"}]
}' Sibuyisela isimo 400 nalo mzimba:
{
"error": {
"type": "invalid_request_error",
"message": "unknown model: no-such-model"
}
} Umzimba wephutha
Kunemizimba emibili. I-/v1/messages iphendula ngefomethi ye-Anthropic; wonke amanye ama-endpoint aphendula ngefomethi ye-OpenAI. Kuzo zombili, imininingwane ikuyi-error.type ne-error.message, ngakho umfundi oyedwa usebenza kuwo wonke ama-endpoint.
{
"error": {
"type": "authentication_error",
"message": "Invalid API key",
"code": "invalid_api_key",
"param": null
}
} {
"type": "error",
"error": {
"type": "authentication_error",
"message": "Invalid API key"
}
} | I-field | Uhlobo | Incazelo |
|---|---|---|
error.type | string | Uhlobo lwephutha. Bheka Izinhlobo zamaphutha ngezansi. |
error.message | string | Umusho wabantu. Imibhalo emathebuleni angezansi izinzile ngaphandle kwezingxenye zayo eziguquguqukayo, ezibonisiwe njenge-<id>, <n> noma …. |
error.code | string | null | Ikhona kwamanye amaphutha efomethi ye-OpenAI: i-invalid_api_key ne-401, i-request_too_large ne-413, i-context_length_exceeded uma ingxoxo mide kakhulu, kungenjalo i-null noma ayikho. Nquma kuqala ngesimo ne-error.type bese uthatha i-code njengesengezo. |
error.param | null | Ikhona emaphutheni afanayo ne-code. Njalo null. |
type | string | Ifomethi ye-Anthropic kuphela. Njalo error. |
Izinhlobo zamaphutha
| Uhlobo | Izimo | Incazelo |
|---|---|---|
invalid_request_error | 400, 413, 415, 422 | Isicelo ngokwaso asilungile: i-field, umzimba, i-id ye-model noma okufakwayo i-model engakwamukeli. Shintsha isicelo ngaphambi kokusithumela futhi. |
authentication_error | 401 | I-API key ilahlekile, ayaziwa noma ihoxisiwe. |
not_found_error | 404 | Indlela ayikho. |
rate_limit_error | 429 | I-balance ayilaleli isicelo, i-flood protection isimisile, noma i-model iyatshwa. Umlayezo usho ukuthi yiliphi. |
api_error | 500, 502, 503, 504 | Isicelo besilungile futhi ukwehluleka kohlangothini lwethu. Sithumele futhi. |
server_error | 500 | Isicelo besilungile futhi ukwehluleka kohlangothini lwethu. Sithumele futhi. |
Amakhodi esimo
| Isimo | Uhlobo | Umlayezo | Nini |
|---|---|---|---|
400 | invalid_request_error | Failed to parse the request body as JSON: … | Umzimba awuyona i-JSON evumelekile. |
400 | invalid_request_error | unknown model: <id> | I-model akuyona i-id eshicilelwe. Ku-/v1/responses nalapho i-model ilahlekile. |
400 | invalid_request_error | No user message provided | Amazinga e-Shannon: isicelo asiphethe mbhalo womsebenzisi. |
400 | invalid_request_error | <id> does not accept image input | Isithombe sithunyelwe ku-model ye-open-weight ehlinzekiwe engenakho ukufakwa kwezithombe. |
400 | invalid_request_error | audio and video input are not supported by any hosted model | Ingxenye yomsindo noma yevidiyo ithunyelwe ku-model ye-open-weight ehlinzekiwe. |
400 | invalid_request_error | <id> does not accept response_format | Okuphumayo okuhleliwe kucelwe ku-model ye-open-weight ehlinzekiwe engenakho. |
400 | invalid_request_error | <id> does not accept response_format json_schema; use json_object | I-JSON schema ithunyelwe ku-model ye-open-weight ehlinzekiwe eyamukela i-json_object kuphela. |
400 | invalid_request_error | count_tokens is available for the hosted open models; unknown model: <id> | Ukubalwa kwama-token kucelwe ku-model engaphandle kwama-model e-open-weight ahlinzekiwe. |
401 | authentication_error | Missing authentication | Ayikho i-API key ethunyelwe. |
401 | authentication_error | Invalid API key | I-key ayaziwa, ishintshelwe eyisha, noma ihoxisiwe. |
404 | not_found_error | Not Found | Indlela ayikho, isibonelo /v1/embeddings. |
405 | api_error | Method Not Allowed | Indlela ikhona kodwa hhayi nale ndlela ye-HTTP. |
413 | invalid_request_error | Failed to buffer the request body: … | Umzimba wesicelo mkhulu kuno-32 MiB. |
415 | invalid_request_error | Expected request with `Content-Type: application/json` | I-header ye-Content-Type ilahlekile noma ayiyona i-application/json. |
422 | invalid_request_error | Failed to deserialize the JSON body into the target type: … | I-field edingekayo ilahlekile, njenge-messages, noma i-field inohlobo olungalungile lwe-JSON. |
429 | insufficient_quota | Not enough API credit. Top up at shannon-ai.com/tokens or get a GPU plan at shannon-ai.com/docs/api/plans | Umkhawulo wokuphumayo wesicelo mkhulu kunalokho okusele ku-balance yakho. |
429 | rate_limit_error | Too many requests. Retry in <n>s. | I-flood protection: izicelo ezingaphezu kwe-120 ngomzuzu owodwa ku-akhawunti yakho. I-<n> yinani lemizuzwana kuze kuphele umzuzu. |
429 | rate_limit_error | Shannon routes are temporarily busy. Please retry. | I-model iyatshwa kulo mzuzu. |
500 | server_error | The model backend failed to answer. Please retry. | I-model ayikhiqizanga mpendulo. |
500 | server_error | An internal error occurred. Please retry. | Ukwehluleka kwangaphakathi ngenkathi isicelo silungiselelwa. |
502 | api_error | The model backend failed to answer. Please retry. | I-model ayikhiqizanga mpendulo. Umndeni we-Shannon 3 nama-model e-open-weight ahlinzekiwe. |
503 | api_error | Could not verify your quota right now. Please retry. | I-balance yakho ayikwazanga ukufundwa kulo mzuzu. |
503 | api_error | token counting is temporarily unavailable for this model | Ukubalwa kwama-token akutholakali kule model kulo mzuzu. |
504 | api_error | upstream timed out | I-model ye-open-weight ehlinzekiwe ithathe isikhathi eside kunomkhawulo wesikhathi wesicelo esingasakazwa. |
Ukuhlola kwenziwa ngalolu hlelo: i-API key, umzimba wesicelo, i-id ye-model, i-flood protection, i-balance. Isicelo esine-key engalungile nomzimba ongalungile ngakho sibuyisela i-401. Isicelo esinqatshwa ngesimo se-4xx asibiziswa.
I-balance ne-flood protection
Isicelo ngasinye sisetshenziswa ngokulinganayo: awekho amazinga omkhawulo wezinga futhi akukho ikhwota ye-API ehlukile. Izinto ezimbili zisengaphendula nge-429, zombili ngohlobo rate_limit_error. Umlayezo uzihlukanisa.
I-balance
I-balance yakho iyi-allowance yepulani yanamuhla, esha ngo-00:00 UTC, nangemva kwayo i-credit yakho ethengiwe. Ingxoxo ne-API zisebenzisa i-balance efanayo.
Isicelo ngasinye siqala sibeke eceleni umkhawulo waso wokuphumayo: max_tokens, noma max_output_tokens ku-/v1/responses, ngu-4,096 uma ungathumelanga lutho. Uma impendulo iphelele, inani elibekelwe eceleni lishintshwa yilokho isicelo esikusebenzisile. Uma inani lingangeni ebhalansini esele, isicelo sibuyisa Not enough API credit ngaphambi kokuba imodeli iqale.
Izicelo ezisebenza ngesikhathi esisodwa ngasinye sibeka eceleni inani laso. Izicelo eziningi ezifanayo ezine-max_tokens ephezulu zingasebenzisa i-balance okwesikhashana, noma impendulo ngayinye imfushane. I-max_tokens ephansi ibeka eceleni okuncane.
I-flood protection
I-flood protection ivumela izicelo ezingu-120 ngomzuzu nge-akhawunti. Ibala i-akhawunti, hhayi i-key, kuma-/v1/chat/completions, /v1/responses na-/v1/messages ndawonye. Umzuzu uqala ngesicelo sakho sokuqala.
Isicelo inombolo 121 phakathi kwaleso mzuzu sibuyisela Too many requests. Retry in <n>s. futhi asibizi lutho. Izicelo ezinqatshiwe nazo ziyabalwa, ngakho iklayenti elithumela futhi ngaphandle kokulinda lihlala linqatshwa kuze kuphele umzuzu. Linda imizuzwana engu-<n> evela emlayezweni.
Izicelo ezithunyelwe ngokufana azinqatshwa ngenxa yokuba zifana. Zilinda emgqeni bese ziphendulwa ngokulandelana.
I-GET /v1/models nama-endpoint okubala ama-token awabalwa.
Okwengeziwe ngemikhawulo ne-balance, nalapho ubona khona i-balance nokusetshenziswa kwakho: Imikhawulo ne-balance Ama-key nokusetshenziswa
Okufanele kuzanywe futhi
Thumela isicelo futhi kuphela uma isicelo esifanayo singaphumelela. Ama-OpenAI ne-Anthropic SDK asevele azama futhi izimpendulo ze-429 ne-5xx kabili ngokwawo; setha i-max_retries (maxRetries ku-JavaScript) ukuze ushintshe lokho.
| Iphutha | Thumela futhi? | Kanjani |
|---|---|---|
400, 404, 405, 413, 415, 422 | Cha. Lungisa isicelo kuqala. | Umlayezo uqamba i-field, i-model noma okufakwayo okungalungile. |
401 | Cha. Sebenzisa i-key evumelekile. | Dala noma shintsha i-key ekhasini le-Ama-key nokusetshenziswa. |
429 Too many requests | Yebo, ngemva kokulinda. | Linda inani lemizuzwana elisemlayezweni, bese uthumela isicelo esifanayo. |
429 Not enough API credit | Hhayi njengoba injalo. | Yehlisa i-max_tokens, linda ukusha kwansuku zonke ngo-00:00 UTC, noma engeza i-credit. |
429 … temporarily busy | Yebo. | Linda imizuzwana embalwa, bese ulinda isikhathi eside ngemizamo elandelayo. |
500, 502, 503 | Yebo. | Linda umzuzwana o-1, bese u-2, u-4 no-8. Yeka ngemva kwemizamo embalwa bese ubika i-id yesicelo. |
504 | Yebo. | Yithumele nge-stream esethelwe ku-true: umkhawulo wesikhathi usebenza ezimpendulweni ezingasakazwa. |
Isiyingi sokuzama futhi esilandela leli thebula:
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) import OpenAI from "openai";
// maxRetries: 0 — this loop does the retrying, the SDK does not add its own.
const client = new OpenAI({ apiKey: "YOUR_API_KEY", baseURL: "https://api.shannon-ai.com/v1", maxRetries: 0 });
const sleep = (seconds) => new Promise((resolve) => setTimeout(resolve, seconds * 1000));
async function createWithRetry(request, attempts = 5) {
for (let attempt = 0; attempt < attempts; attempt++) {
try {
return await client.chat.completions.create(request);
} catch (error) {
const text = String(error.message);
const flood = text.match(/Retry in (\d+)s/);
if (error.status === 429 && flood) {
await sleep(Number(flood[1])); // flood protection: wait out the minute
} else if (error.status === 429 && text.includes("temporarily busy")) {
await sleep(2 ** attempt);
} else if (error.status >= 500 || error instanceof OpenAI.APIConnectionError) {
await sleep(2 ** attempt); // 1, 2, 4, 8 seconds
} else {
throw error; // wrong request, wrong key or balance
}
}
}
throw new Error("the request failed after all attempts");
}
const response = await createWithRetry({
model: "shannon-3",
messages: [{ role: "user", content: "Hello" }],
});
console.log(response.choices[0].message.content); Amaphutha ngaphakathi kwe-stream
I-stream inesimo 200 kusukela ku-byte yayo yokuqala. Ukwehluleka ngemva kwalokho kufika njengomcimbi ngaphakathi kwe-stream: i-chunk enelungu le-error ku-/v1/chat/completions, umcimbi we-error ku-/v1/messages, umcimbi we-response.failed noma we-error ku-/v1/responses. Imicimbi yokuvala ye-stream isalandela. Thatha impendulo enjalo njengehlulekile bese uthumela isicelo futhi, njengasesimeni se-5xx.
Ingxoxo ende kunewindi lomongo le-model ibikwa ngale ndlela, ngohlobo invalid_request_error nekhodi context_length_exceeded. Finyeza ingxoxo ngaphambi kokuthumela futhi.
Ama-frame aqondile achazwe nge-streaming. Ukusakaza
Ama-id ezicelo
Yonke impendulo, kufaka amaphutha, inayo i-header ye-x-request-id. Liyinani olithumele ku-header yakho ye-x-request-id, noma izinhlamvu ze-hexadecimal ezingu-12 uma ungathumelanga lutho. Yirekhode, futhi yicaphune uma ucela usizo ngesicelo.
