Ukuphatha imposiso
Isicelo esiyaleza sibuyisa ikhowudi yesimo se-HTTP nomzimba we-JSON onohlobo lwempazamo nomyalezo. Eli phepha lidwelisa yonke imo, libonisa umzimba wempazamo wefomethi nganye ye-API kwaye lithi zeziphi iimpazamo ezifanele ukuthunyelwa kwakhona.
Ii-SDK zivelisa i-object yempazamo ethwala ikhowudi yesimo neentsimi zomzimba. Esi sicelo sibiza imodeli engekhoyo:
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"}]
}' Sibuyisa isimo 400 nalo mzimba:
{
"error": {
"type": "invalid_request_error",
"message": "unknown model: no-such-model"
}
} Umzimba wempazamo
Kukho imizimba emibini. I-/v1/messages iphendula ngefomethi ye-Anthropic; yonke enye i-endpoint iphendula ngefomethi ye-OpenAI. Kuzo zozibini, iinkcukacha zikwi-error.type nakwi-error.message, ngoko umfundi omnye usebenzela zonke ii-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"
}
} | Intsimi | Uhlobo | Inkcazelo |
|---|---|---|
error.type | string | Uhlobo lwempazamo. Jonga Iindidi zeempazamo ngezantsi. |
error.message | string | Isivakalisi somntu. Imibhalo kwiitheyibhile ezingezantsi izinzile ngaphandle kweendawo ezitshintshayo, ezibonakaliswe njenge-<id>, <n> okanye …. |
error.code | string | null | Ikhona kwezinye iimpazamo zefomethi ye-OpenAI: invalid_api_key nge-401, request_too_large nge-413, context_length_exceeded xa incoko ide kakhulu, ngaphandle koko null okanye ayikho. Nquma ngokwesimo ne-error.type kuqala kwaye uthathe i-code njengesongezo. |
error.param | null | Ikhona kwiimpazamo ezifanayo ne-code. Ihlala i-null. |
type | string | Kwifomethi ye-Anthropic kuphela. Ihlala i-error. |
Iindidi zeempazamo
| Uhlobo | Izimo | Inkcazelo |
|---|---|---|
invalid_request_error | 400, 413, 415, 422 | Isicelo ngokwaso asilunganga: intsimi, umzimba, i-id yemodeli okanye i-input engayamkeliyo imodeli. Tshintsha isicelo phambi kokuba usithumele kwakhona. |
authentication_error | 401 | I-API key ilahlekile, ayaziwa okanye irhoxisiwe. |
not_found_error | 404 | Indlela ayikho. |
rate_limit_error | 429 | Ibhalansi ayiluboni isicelo, i-flood protection yasimisa, okanye imodeli ixakekile. Umyalezo uthi nguwuphi. |
api_error | 500, 502, 503, 504 | Isicelo besilungile kwaye ukusilela kwicala lethu. Sithumele kwakhona. |
server_error | 500 | Isicelo besilungile kwaye ukusilela kwicala lethu. Sithumele kwakhona. |
Iikhowudi zesimo
| Isimo | Uhlobo | Umyalezo | Xa |
|---|---|---|---|
400 | invalid_request_error | Failed to parse the request body as JSON: … | Umzimba awuyiyo i-JSON esebenzayo. |
400 | invalid_request_error | unknown model: <id> | I-model ayiyiyo i-id epapashiweyo. Kwi-/v1/responses nakuxa i-model ilahlekile. |
400 | invalid_request_error | No user message provided | Amanqanaba eShannon: isicelo asinambhalo womsebenzisi. |
400 | invalid_request_error | <id> does not accept image input | Umfanekiso uthunyelwe kwimodeli ye-open-weight esingathiweyo engenayo i-image input. |
400 | invalid_request_error | audio and video input are not supported by any hosted model | Inxalenye yeaudiyo okanye yevidiyo ithunyelwe kwimodeli ye-open-weight esingathiweyo. |
400 | invalid_request_error | <id> does not accept response_format | I-structured output iceliwe kwimodeli ye-open-weight esingathiweyo engenayo. |
400 | invalid_request_error | <id> does not accept response_format json_schema; use json_object | I-JSON schema ithunyelwe kwimodeli ye-open-weight esingathiweyo yamkela i-json_object kuphela. |
400 | invalid_request_error | count_tokens is available for the hosted open models; unknown model: <id> | Ukubala ii-token kuceliwe kwimodeli engaphandle kweemodeli ze-open-weight ezisingathiweyo. |
401 | authentication_error | Missing authentication | Akukho API key ithunyelweyo. |
401 | authentication_error | Invalid API key | Isitshixo asaziwa, sathatyathelwa indawo esitsha, okanye sarhoxiswa. |
404 | not_found_error | Not Found | Indlela ayikho, umzekelo i-/v1/embeddings. |
405 | api_error | Method Not Allowed | Indlela ikhona kodwa hayi ngale 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 okanye ayiyo i-application/json. |
422 | invalid_request_error | Failed to deserialize the JSON body into the target type: … | Intsimi efunekayo ilahlekile, njenge-messages, okanye intsimi inohlobo olungalunganga 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 | Umda we-output wesicelo mkhulu kunokushiyekileyo kwibhalansi yakho. |
429 | rate_limit_error | Too many requests. Retry in <n>s. | I-flood protection: izicelo ezingaphezu kwe-120 kumzuzu omnye kwiakhawunti yakho. I-<n> linani lemizuzwana ukuya ekupheleni komzuzu uphele. |
429 | rate_limit_error | Shannon routes are temporarily busy. Please retry. | Imodeli ixakekile ngeli xesha. |
500 | server_error | The model backend failed to answer. Please retry. | Imodeli ayivelisanga mpendulo. |
500 | server_error | An internal error occurred. Please retry. | Ukusilela kwangaphakathi ngoxa isicelo silungiswa. |
502 | api_error | The model backend failed to answer. Please retry. | Imodeli ayivelisanga mpendulo. Intsapho yeShannon 3 neemodeli ze-open-weight ezisingathiweyo. |
503 | api_error | Could not verify your quota right now. Please retry. | Ibhalansi yakho ayikwazanga ukufundwa ngeli xesha. |
503 | api_error | token counting is temporarily unavailable for this model | Ukubala ii-token akufumaneki kule modeli ngeli xesha. |
504 | api_error | upstream timed out | Imodeli ye-open-weight esingathiweyo ithathe ixesha elide kunomda wexesha wesicelo esingekho kwi-stream. |
Ukuhlolwa kuqhutywa ngolu landelelwano: i-API key, umzimba wesicelo, i-id yemodeli, i-flood protection, ibhalansi. Isicelo esinesitshixo esingalunganga nomzimba ongalunganga ngoko sibuyisa i-401. Isicelo esenqatshwe ngesimo se-4xx asihlawulwa.
Ibhalansi ne-flood protection
Isicelo ngasinye sikhonzwa ngokulinganayo: akukho manqanaba ereyithi kwaye akukho quota ye-API eyahlukileyo. Izinto ezimbini zisenokuphendula nge-429, zombini ngohlobo rate_limit_error. Umyalezo ubonisa umahluko.
Ibhalansi
Ibhalansi yakho yisabelo seplani sanamhlanje, esiqala kwakhona ngentsimbi ye-00:00 UTC, kwaye emva kwaso yikhredithi othengiweyo. Incoko ne-API zitsala kwibhalansi enye.
Isicelo ngasinye siqala sibeke bucala umda wemveliso waso: max_tokens, okanye max_output_tokens kwi-/v1/responses, ngu-4,096 ukuba awuthumelanga nanye. Xa impendulo igqityiwe, inani elibekelwe bucala litshintshwa ngalo isicelo esilisebenzisileyo. Ukuba inani alingeneli kubhalansi eseleyo, isicelo sibuyisa Not enough API credit ngaphambi kokuba imodeli iqale.
Izicelo eziqhubeka ngaxeshanye nganye ibeka bucala inani layo. Izicelo ezininzi ezihambelanayo ezine-max_tokens ephezulu zisenokuyisebenzisa ibhalansi okwexeshana, nokuba impendulo nganye imfutshane. I-max_tokens ephantsi ibeka bucala okuncinci.
I-flood protection
I-flood protection ivumela izicelo ezili-120 ngomzuzu ngeakhawunti. Ibala iakhawunti, hayi isitshixo, kuyo i-/v1/chat/completions, i-/v1/responses ne-/v1/messages zidibene. Umzuzu uqala ngesicelo sakho sokuqala.
Isicelo esinombolo 121 ngaphakathi kwaloo mzuzu sibuyisa Too many requests. Retry in <n>s. kwaye asixabisi nto. Izicelo ezenqatshiweyo nazo ziyabalwa, ngoko i-client ethumela kwakhona ngaphandle kokulinda ihlala yenqatshiwe de umzuzu uphele. Linda imizuzwana ye-<n> evela kumyalezo.
Izicelo ezithunyelwe ngokuhambelana azenqatshwa ngenxa yokuhambelana. Zilinda kumgca kwaye ziphendulwa ngokulandelelana.
I-GET /v1/models nee-endpoint zokubala ii-token azibalwa.
Okungakumbi malunga nemida nebhalansi, nokuba ubone phi ibhalansi nokusetyenziswa kwakho: Imida nebhalansi Izitshixo nokusetyenziswa
Oko kufuneka ukuzame kwakhona
Thumela isicelo kwakhona kuphela xa isicelo esifanayo sinokuphumelela. Ii-SDK ze-OpenAI ne-Anthropic sele ziphinda iimpendulo ze-429 ne-5xx kabini ngokwazo; seta i-max_retries (maxRetries kwi-JavaScript) ukuze utshintshe oko.
| Impazamo | Thumela kwakhona? | Njani |
|---|---|---|
400, 404, 405, 413, 415, 422 | Hayi. Lungisa isicelo kuqala. | Umyalezo ubiza intsimi, imodeli okanye i-input engalunganga. |
401 | Hayi. Sebenzisa isitshixo esisebenzayo. | Yenza okanye utshintshe isitshixo kwiphepha leZitshixo nokusetyenziswa. |
429 Too many requests | Ewe, emva kokulinda. | Linda inani lemizuzwana ekumyalezo, emva koko uthumele isicelo esifanayo. |
429 Not enough API credit | Hayi njengoko injalo. | Yehlisa i-max_tokens, linda ukuseta kwakhona kosuku ngentsimbi ye-00:00 UTC, okanye yongeza ikhredithi. |
429 … temporarily busy | Ewe. | Linda imizuzwana embalwa, emva koko ixesha elide kuzama ngalinye olandelayo. |
500, 502, 503 | Ewe. | Linda umzuzwana we-1, emva koko ii-2, ii-4 nee-8. Yeka emva kwemizamo embalwa kwaye uxele i-id yesicelo. |
504 | Ewe. | Yithumele ne-stream isetwe ku-true: umda wexesha usebenza kwiimpendulo ezingekho kwi-stream. |
Iluphu yokuphinda elandela le theyibhile:
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); Iimpazamo ngaphakathi kwe-stream
I-stream inesimo 200 ukusuka kwibhayithi yayo yokuqala. Ukusilela emva koko kufika njengesiganeko ngaphakathi kwe-stream: i-chunk enelungu le-error kwi-/v1/chat/completions, isiganeko se-error kwi-/v1/messages, isiganeko se-response.failed okanye se-error kwi-/v1/responses. Iziganeko zokuvala ze-stream zisalandela. Thatha impendulo enjalo njengengaphumelelanga kwaye uthumele isicelo kwakhona, njengakwisimo se-5xx.
Incoko ende kunefestile yomxholo yemodeli ixelwa ngale ndlela, ngohlobo invalid_request_error nekhowudi context_length_exceeded. Finyeza incoko phambi kokuba uyithumele kwakhona.
Ii-frame ezichanekileyo zichazwe nge-streaming. Umsinga
Ii-id zezicelo
Impendulo nganye, kubandakanywa iimpazamo, inayo i-header ye-x-request-id. Lixabiso olithumele kwi-header yakho ye-x-request-id, okanye oonobumba abayi-12 ze-hexadecimal xa ungathumelanga nanye. Yigcine kwi-log, uyicaphule xa ucela uncedo ngesicelo.
