akupriyanovhse

openrouter ai test

Feb 26th, 2026
161
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.38 KB | None | 0 0
  1. import requests
  2. import json
  3. from my_config import openrouter_api
  4.  
  5. question = "How would you build the tallest building ever?"
  6.  
  7. url = "https://openrouter.ai/api/v1/chat/completions"
  8. headers = {
  9.     "Authorization": f"Bearer {openrouter_api}",
  10.     "Content-Type": "application/json"
  11. }
  12.  
  13. payload = {
  14.     "model": "openai/gpt-4o",  # или "anthropic/claude-3.5-sonnet", "google/gemini-pro"
  15.     "messages": [{"role": "user", "content": question}],
  16.     "stream": True,  # Потоковый режим для вывода по частям
  17.     "max_tokens": 1000
  18. }
  19.  
  20. print(f"❓ Вопрос: {question}\n")
  21. print("🤖 Ответ: ", end="", flush=True)
  22.  
  23. # Отправляем запрос
  24. response = requests.post(url, headers=headers, json=payload, stream=True)
  25.  
  26. # Обрабатываем потоковый ответ
  27. for line in response.iter_lines():
  28.     if line:
  29.         line = line.decode('utf-8')
  30.         if line.startswith('data: '):
  31.             data = line[6:]  # Убираем "data: "
  32.             if data != '[DONE]':
  33.                 try:
  34.                     chunk = json.loads(data)
  35.                     if chunk['choices'][0]['delta'].get('content'):
  36.                         content = chunk['choices'][0]['delta']['content']
  37.                         print(content, end='', flush=True)
  38.                 except:
  39.                     pass
  40.  
  41. print("\n\n✅ Готово!")
Advertisement
Add Comment
Please, Sign In to add comment