Loading
Loading
The Claude API opens the full possibilities for building real AI applications. In this lesson you'll learn from authentication all the way to streaming.
# Python
pip install anthropic
# Node.js / TypeScript
npm install @anthropic-ai/sdk
Python:
import anthropic
client = anthropic.Anthropic(api_key="sk-ant-xxx")
message = client.messages.create(
model="claude-opus-4-8",
max_tokens=1024,
messages=[
{"role": "user", "content": "Explain what AI is in 3 sentences"}
]
)
print(message.content[0].text)
with client.messages.stream(
model="claude-opus-4-8",
max_tokens=1024,
messages=[{"role": "user", "content": "Write a poem about programming"}]
) as stream:
for text in stream.text_stream:
print(text, end="", flush=True)
Streaming is essential for chat applications — it shows the response as it's generated rather than waiting.
# تطبيق Chat كامل مع Claude API
# يدعم: محادثة متعددة الأدوار + Streaming + حفظ السجل
import anthropic
import json
from pathlib import Path
from datetime import datetime
client = anthropic.Anthropic() # يقرأ ANTHROPIC_API_KEY من env تلقائياً
HISTORY_FILE = Path("chat_history.json")
def load_history() -> list[dict]:
"""تحميل سجل المحادثة"""
if HISTORY_FILE.exists():
return json.loads(HISTORY_FILE.read_text(encoding="utf-8"))
return []
def save_history(messages: list[dict]) -> None:
"""حفظ سجل المحادثة"""
HISTORY_FILE.write_text(
json.dumps(messages, ensure_ascii=False, indent=2),
encoding="utf-8"
)
def chat(
user_input: str,
history: list[dict],
system_prompt: str = "أنت مساعد ذكي تتحدث العربية. أجب بإيجاز ووضوح.",
model: str = "claude-opus-4-8",
stream: bool = True
) -> tuple[str, list[dict]]:
"""
إرسال رسالة والحصول على رد مع streaming اختياري.
يُرجع (الرد, السجل المحدَّث).
"""
# إضافة رسالة المستخدم
history.append({"role": "user", "content": user_input})
full_response = ""
if stream:
print("Claude: ", end="", flush=True)
with client.messages.stream(
model=model,
max_tokens=2048,
system=system_prompt,
messages=history
) as stream_ctx:
for text in stream_ctx.text_stream:
print(text, end="", flush=True)
full_response += text
print() # سطر جديد بعد الرد
else:
message = client.messages.create(
model=model,
max_tokens=2048,
system=system_prompt,
messages=history
)
full_response = message.content[0].text
print(f"Claude: {full_response}")
# إضافة رد Claude للسجل
history.append({"role": "assistant", "content": full_response})
return full_response, history
def main():
print("=" * 50)
print("🤖 Claude Chat — اكتب 'خروج' للإنهاء")
print("=" * 50)
# تحميل السجل السابق أو البدء من جديد
choice = input("
هل تريد استئناف المحادثة السابقة؟ (y/n): ").strip().lower()
history = load_history() if choice == "y" else []
if history:
print(f"✅ تم تحميل {len(history)} رسالة سابقة")
system_prompt = """أنت مساعد AI متخصص للطلاب في أكاديمية Darhous.
مهامك:
- شرح مفاهيم AI وBrainomvation بطريقة مبسطة
- مساعدة في الكود والأخطاء التقنية
- تقديم أمثلة عملية وواقعية
أسلوبك: ودود، واضح، موجز — بالعربية."""
session_messages: list[dict] = [] # رسائل الجلسة الحالية فقط
while True:
user_input = input("
أنت: ").strip()
if not user_input:
continue
if user_input in ["خروج", "exit", "quit"]:
# دمج رسائل الجلسة مع السجل وحفظه
full_history = history + session_messages
save_history(full_history)
print(f"
✅ تم حفظ {len(full_history)} رسالة في {HISTORY_FILE}")
break
_, session_messages = chat(
user_input=user_input,
history=history + session_messages, # السياق الكامل
system_prompt=system_prompt
)
# نبقي فقط رسائل الجلسة الحالية في session_messages
# لتجنب التكرار مع history
if len(session_messages) > 2:
session_messages = session_messages[-20:] # آخر 10 أزواج
if __name__ == "__main__":
main()