ورقة مرجعية سريعة عن OpenAI API

التثبيت

pip install openai

الإعداد الأساسي

from openai import OpenAI
import os

client = OpenAI(api_key=os.getenv("OPENAI_API_KEY"))

إكمال الدردشة (بدون بث)

response = client.chat.completions.create(
    model="gpt-4o-mini",
    messages=[
        {"role": "system", "content": "You are a helpful assistant."},
        {"role": "user", "content": "What is Python?"}
    ],
    temperature=0.7,        # 0 = حتمي، 2 = عشوائي جدًا
    max_tokens=500,         # الحد الأقصى لكلمات الاستجابة
)

reply = response.choices[0].message.content
print(reply)
print(f"Tokens used: {response.usage.total_tokens}")

إكمال الدردشة (مع البث)

stream = client.chat.completions.create(
    model="gpt-4o-mini",
    messages=[{"role": "user", "content": "Tell me a story"}],
    stream=True,
)

full_response = ""
for chunk in stream:
    if chunk.choices[0].delta.content:
        content = chunk.choices[0].delta.content
        print(content, end="")  # اطبع النص فور وصوله
        full_response += content

صيغة الرسائل

messages = [
    {"role": "system", "content": "You speak like a pirate."},
    {"role": "user", "content": "Hello!"},
    {"role": "assistant", "content": "Ahoy, matey!"},
    {"role": "user", "content": "What's the weather?"},
]

معالجة الأخطاء

try:
    response = client.chat.completions.create(
        model="gpt-4o-mini",
        messages=[{"role": "user", "content": "Hello"}]
    )
except openai.AuthenticationError:
    print("Invalid API key. Check your .env file.")
except openai.RateLimitError:
    print("Rate limited. Waiting before retrying...")
    time.sleep(10)
except openai.APIError as e:
    print(f"API error: {e}")

استدعاء الدوال (للوكلاء)

tools = [
    {
        "type": "function",
        "function": {
            "name": "get_weather",
            "description": "Get the weather for a city",
            "parameters": {
                "type": "object",
                "properties": {
                    "city": {"type": "string"}
                },
                "required": ["city"]
            }
        }
    }
]

response = client.chat.completions.create(
    model="gpt-4o-mini",
    messages=[{"role": "user", "content": "What's the weather in Paris?"}],
    tools=tools,
    tool_choice="auto"
)

# تحقق مما إذا كان النموذج يريد استدعاء دالة
if response.choices[0].message.tool_calls:
    tool_call = response.choices[0].message.tool_calls[0]
    function_name = tool_call.function.name
    arguments = json.loads(tool_call.function.arguments)
    print(f"Calling {function_name} with {arguments}")

النماذج المتاحة (2025)

النموذج الأنسب لـ نافذة السياق
gpt-4o الأفضل بشكل عام 128K رمز
gpt-4o-mini اقتصادي وسريع 128K رمز
gpt-4-turbo عالي الجودة من الجيل السابق 128K رمز
gpt-3.5-turbo اقتصادي من الجيل السابق 16K رمز