استخدم CometAPI POST /v1/chat/completions لإرسال محادثات متعددة الرسائل والحصول على ردود LLM مع عناصر تحكم في Streaming وtemperature وmax_tokens.
from openai import OpenAI
client = OpenAI(
base_url="https://api.cometapi.com/v1",
api_key="<COMETAPI_KEY>",
)
completion = client.chat.completions.create(
model="gpt-5.4",
messages=[
{"role": "system", "content": "You are a helpful assistant."},
{"role": "user", "content": "Hello!"},
],
)
print(completion.choices[0].message){
"id": "chatcmpl-DNA27oKtBUL8TmbGpBM3B3zhWgYfZ",
"object": "chat.completion",
"created": 1774412483,
"model": "gpt-4.1-nano-2025-04-14",
"choices": [
{
"index": 0,
"message": {
"role": "assistant",
"content": "Four",
"refusal": null,
"annotations": []
},
"logprobs": null,
"finish_reason": "stop"
}
],
"usage": {
"prompt_tokens": 29,
"completion_tokens": 2,
"total_tokens": 31,
"prompt_tokens_details": {
"cached_tokens": 0,
"audio_tokens": 0
},
"completion_tokens_details": {
"reasoning_tokens": 0,
"audio_tokens": 0,
"accepted_prediction_tokens": 0,
"rejected_prediction_tokens": 0
}
},
"service_tier": "default",
"system_fingerprint": "fp_490a4ad033"
}model.
base_url إلى https://api.cometapi.com/v1.reasoning_effort ينطبق فقط على نماذج الاستدلال (o-series, GPT-5.1+)، وقد لا تدعم بعض النماذج logprobs أو n > 1.o1-pro)، استخدم نقطة النهاية responses بدلًا من ذلك.| Role | Description |
|---|---|
system | يحدد سلوك المساعد وشخصيته. يوضع في بداية المحادثة. |
developer | يستبدل system في النماذج الأحدث (o1+). يوفّر تعليمات يجب على النموذج اتباعها بغض النظر عن مدخلات المستخدم. |
user | رسائل من المستخدم النهائي. |
assistant | استجابات النموذج السابقة، وتُستخدم للحفاظ على سجل المحادثة. |
tool | نتائج استدعاءات الأدوات/الدوال. يجب أن تتضمن tool_call_id يطابق استدعاء الأداة الأصلي. |
developer بدلًا من system لرسائل التعليمات. كلاهما يعمل، لكن developer يوفّر سلوكًا أقوى في اتباع التعليمات.content لإرسال رسائل متعددة الوسائط:
{
"role": "user",
"content": [
{"type": "text", "text": "Describe this image"},
{
"type": "image_url",
"image_url": {
"url": "https://example.com/image.png",
"detail": "high"
}
}
]
}
detail في عمق تحليل الصورة:
low — أسرع، ويستخدم عددًا أقل من Tokens (تكلفة ثابتة)high — تحليل مفصل، مع استهلاك عدد أكبر من Tokensauto — يقرر النموذج ذلك (الافتراضي)stream إلى true، يتم تسليم الاستجابة على شكل Server-Sent Events (SSE). يحتوي كل حدث على كائن chat.completion.chunk مع محتوى تزايدي:
data: {"id":"chatcmpl-xxx","object":"chat.completion.chunk","choices":[{"index":0,"delta":{"role":"assistant"},"finish_reason":null}]}
data: {"id":"chatcmpl-xxx","object":"chat.completion.chunk","choices":[{"index":0,"delta":{"content":"Hello"},"finish_reason":null}]}
data: {"id":"chatcmpl-xxx","object":"chat.completion.chunk","choices":[{"index":0,"delta":{"content":"!"},"finish_reason":null}]}
data: {"id":"chatcmpl-xxx","object":"chat.completion.chunk","choices":[{"index":0,"delta":{},"finish_reason":"stop"}]}
data: [DONE]
stream_options.include_usage إلى true. تظهر بيانات الاستخدام في الجزء الأخير قبل [DONE].response_format:
{
"response_format": {
"type": "json_schema",
"json_schema": {
"name": "result",
"strict": true,
"schema": {
"type": "object",
"properties": {
"answer": {"type": "string"},
"confidence": {"type": "number"}
},
"required": ["answer", "confidence"],
"additionalProperties": false
}
}
}
}
json_schema) أن يطابق الإخراج schema الخاص بك تمامًا. أما وضع JSON Object (json_object) فيضمن فقط JSON صالحًا — ولا يتم فرض البنية.{
"tools": [
{
"type": "function",
"function": {
"name": "get_weather",
"description": "Get current weather for a city",
"parameters": {
"type": "object",
"properties": {
"location": {"type": "string", "description": "City name"}
},
"required": ["location"]
}
}
}
],
"tool_choice": "auto"
}
finish_reason: "tool_calls" وستحتوي المصفوفة message.tool_calls على اسم الوظيفة والوسائط. بعد ذلك، تنفّذ الوظيفة وترسل النتيجة مرة أخرى كرسالة tool مع tool_call_id المطابق.
| Field | Description |
|---|---|
id | معرّف فريد للإكمال (مثلًا chatcmpl-abc123). |
object | دائمًا chat.completion. |
model | الـ model الذي أنشأ الاستجابة (قد يتضمن لاحقة إصدار). |
choices | مصفوفة من خيارات الإكمال (عادةً 1 ما لم يكن n > 1). |
choices[].message | رسالة استجابة المساعد وتتضمن role وcontent وtool_calls اختياريًا. |
choices[].finish_reason | سبب توقف model: stop أو length أو tool_calls أو content_filter. |
usage | تفصيل استهلاك Token: prompt_tokens وcompletion_tokens وtotal_tokens بالإضافة إلى الأعداد الفرعية التفصيلية. |
system_fingerprint | بصمة إعدادات الواجهة الخلفية لأغراض تصحيح قابلية إعادة الإنتاج. |
دعم المعلمات عبر المزوّدين
| Parameter | OpenAI GPT | Claude (via compat) | Gemini (via compat) |
|---|---|---|---|
temperature | 0–2 | 0–1 | 0–2 |
top_p | 0–1 | 0–1 | 0–1 |
n | 1–128 | 1 فقط | 1–8 |
stop | حتى 4 | حتى 4 | حتى 5 |
tools | ✅ | ✅ | ✅ |
response_format | ✅ | ✅ (json_schema) | ✅ |
logprobs | ✅ | ❌ | ❌ |
reasoning_effort | o-series، GPT-5.1+ | ❌ | ❌ (استخدم thinking لـ Gemini native) |
max_tokens مقابل max_completion_tokens
max_tokens — المعلمة القديمة. تعمل مع معظم النماذج لكنها مهجورة في نماذج OpenAI الأحدث.max_completion_tokens — المعلمة الموصى بها لسلسلة GPT-4.1 وGPT-5 ونماذج o-series. وهي مطلوبة لنماذج reasoning لأنها تشمل كلاً من output tokens وreasoning tokens.دور system مقابل developer
system — دور التعليمات التقليدي. يعمل مع جميع النماذج.developer — تم تقديمه مع نماذج o1. يوفّر اتباعًا أقوى للتعليمات في النماذج الأحدث. ويعود إلى سلوك system في النماذج الأقدم.developer في المشاريع الجديدة التي تستهدف GPT-4.1+ أو نماذج o-series.429 Too Many Requests، نفّذ exponential backoff:
import time
import random
from openai import OpenAI, RateLimitError
client = OpenAI(
base_url="https://api.cometapi.com/v1",
api_key="<COMETAPI_KEY>",
)
def chat_with_retry(messages, max_retries=3):
for i in range(max_retries):
try:
return client.chat.completions.create(
model="gpt-5.4",
messages=messages,
)
except RateLimitError:
if i < max_retries - 1:
wait_time = (2 ** i) + random.random()
time.sleep(wait_time)
else:
raise
messages:
messages = [
{"role": "developer", "content": "You are a helpful assistant."},
{"role": "user", "content": "What is Python?"},
{"role": "assistant", "content": "Python is a high-level programming language..."},
{"role": "user", "content": "What are its main advantages?"},
]
finish_reason؟| Value | Meaning |
|---|---|
stop | اكتمال طبيعي أو الوصول إلى stop sequence. |
length | تم الوصول إلى حد max_tokens أو max_completion_tokens. |
tool_calls | استدعى النموذج استدعاء أداة/دالة واحدًا أو أكثر. |
content_filter | تمت تصفية المخرجات بسبب سياسة المحتوى. |
max_completion_tokens لتحديد حد أقصى لطول المخرجات.gpt-5.4-mini أو gpt-5.4-nano للمهام الأبسط).usage.Bearer token authentication. Use your CometAPI key.
Model ID to use for this request. See the Models page for current options.
"gpt-4.1"
A list of messages forming the conversation. Each message has a role (system, user, assistant, or developer) and content (text string or multimodal content array).
Show child attributes
If true, partial response tokens are delivered incrementally via server-sent events (SSE). The stream ends with a data: [DONE] message.
Sampling temperature between 0 and 2. Higher values (e.g., 0.8) produce more random output; lower values (e.g., 0.2) make output more focused and deterministic. Recommended to adjust this or top_p, but not both.
0 <= x <= 2Nucleus sampling parameter. The model considers only the tokens whose cumulative probability reaches top_p. For example, 0.1 means only the top 10% probability tokens are considered. Recommended to adjust this or temperature, but not both.
0 <= x <= 1Number of completion choices to generate for each input message. Defaults to 1.
Up to 4 sequences where the API will stop generating further tokens. Can be a string or an array of strings.
Maximum number of tokens to generate in the completion. The total of input + output tokens is capped by the model's context length.
Number between -2.0 and 2.0. Positive values penalize tokens based on whether they have already appeared, encouraging the model to explore new topics.
-2 <= x <= 2Number between -2.0 and 2.0. Positive values penalize tokens proportionally to how often they have appeared, reducing verbatim repetition.
-2 <= x <= 2A JSON object mapping token IDs to bias values from -100 to 100. The bias is added to the model's logits before sampling. Values between -1 and 1 subtly adjust likelihood; -100 or 100 effectively ban or force selection of a token.
A unique identifier for your end-user. Helps with abuse detection and monitoring.
An upper bound for the number of tokens to generate, including visible output tokens and reasoning tokens. Use this instead of max_tokens for GPT-4.1+, GPT-5 series, and o-series models.
Specifies the output format. Use {"type": "json_object"} for JSON mode, or {"type": "json_schema", "json_schema": {...}} for strict structured output.
Show child attributes
A list of tools the model may call. Currently supports function type tools.
Show child attributes
Controls how the model selects tools. auto (default): model decides. none: no tools. required: must call a tool.
Whether to return log probabilities of the output tokens.
Number of most likely tokens to return at each position (0-20). Requires logprobs to be true.
0 <= x <= 20Controls the reasoning effort for o-series and GPT-5.1+ models.
low, medium, high Options for streaming. Only valid when stream is true.
Show child attributes
Specifies the processing tier.
auto, default, flex, priority Successful chat completion response.
Unique completion identifier.
"chatcmpl-abc123"
chat.completion "chat.completion"
Unix timestamp of creation.
1774412483
The model used (may include version suffix).
"gpt-5.4-2025-07-16"
Array of completion choices.
Show child attributes
Show child attributes
"default"
"fp_490a4ad033"
from openai import OpenAI
client = OpenAI(
base_url="https://api.cometapi.com/v1",
api_key="<COMETAPI_KEY>",
)
completion = client.chat.completions.create(
model="gpt-5.4",
messages=[
{"role": "system", "content": "You are a helpful assistant."},
{"role": "user", "content": "Hello!"},
],
)
print(completion.choices[0].message){
"id": "chatcmpl-DNA27oKtBUL8TmbGpBM3B3zhWgYfZ",
"object": "chat.completion",
"created": 1774412483,
"model": "gpt-4.1-nano-2025-04-14",
"choices": [
{
"index": 0,
"message": {
"role": "assistant",
"content": "Four",
"refusal": null,
"annotations": []
},
"logprobs": null,
"finish_reason": "stop"
}
],
"usage": {
"prompt_tokens": 29,
"completion_tokens": 2,
"total_tokens": 31,
"prompt_tokens_details": {
"cached_tokens": 0,
"audio_tokens": 0
},
"completion_tokens_details": {
"reasoning_tokens": 0,
"audio_tokens": 0,
"accepted_prediction_tokens": 0,
"rejected_prediction_tokens": 0
}
},
"service_tier": "default",
"system_fingerprint": "fp_490a4ad033"
}