Chat Completion API (via OpenRouter)

Open In Colab Download .ipynb

Set the OpenRouter API Key from Colab Secrets

from google.colab import userdata
OPENROUTER_API_KEY = userdata.get('OPENROUTER_API_KEY')

(Or grab the OpenRouter API key if running locally)

import os
from dotenv import load_dotenv
load_dotenv()

OPENROUTER_API_KEY = os.environ.get("OPENROUTER_API_KEY")

Logging function to print the API request to the console

import json

def log_request(request):
  print("\n=== REQUEST ===")
  print(f"URL: {request.url}")
  print(f"Method: {request.method}")

  if request.content:
    try:
      body = json.loads(request.content.decode('utf-8'))
      print("\nBody:")
      print(json.dumps(body, indent=2))
    except:
      print("\nBody:")
      print(request.content.decode('utf-8'))
  print("=" * 50)

Call OpenAI via the SDK

import openai
import httpx

# Initialize the OpenAI client with event hooks
client = openai.OpenAI(
    base_url='https://openrouter.ai/api/v1',
    api_key=OPENROUTER_API_KEY,
    http_client=httpx.Client(event_hooks={"request": [log_request]}),
)
MODEL = 'openai/gpt-5.2-chat' #@param ["openai/gpt-5.2-chat", "anthropic/claude-sonnet-4.5", "google/gemini-2.5-pro"]

response = client.chat.completions.create(
    model=MODEL,
    messages=[
        {"role": "system", "content": "You help travelers make plans for their trips."},
        {"role": "user", "content": "Hello"},
        {"role": "assistant", "content": "Hi there!"},
        {"role": "user", "content": "What should I do on my upcoming trip to Paris?"},
    ],
)

=== REQUEST ===
URL: https://openrouter.ai/api/v1/chat/completions
Method: POST

Body:
{
  "messages": [
    {
      "role": "system",
      "content": "You help travelers make plans for their trips."
    },
    {
      "role": "user",
      "content": "Hello"
    },
    {
      "role": "assistant",
      "content": "Hi there!"
    },
    {
      "role": "user",
      "content": "What should I do on my upcoming trip to Paris?"
    }
  ],
  "model": "openai/gpt-5.2-chat"
}
==================================================
print("\n=== RESPONSE ===")
print(response.model_dump_json(indent=2))

=== RESPONSE ===
{
  "id": "gen-1767585819-snubWxcK6sJM3RdE9rJX",
  "choices": [
    {
      "finish_reason": "stop",
      "index": 0,
      "logprobs": null,
      "message": {
        "content": "Paris has something for almost every kind of traveler! Here’s a well‑rounded starting plan, and then I can tailor it more if you tell me your interests, travel dates, and how long you’ll be there.\n\n### Must‑See Highlights\n- **Eiffel Tower** – Go up for the views or enjoy it from below at Trocadéro or Champ de Mars.\n- **Louvre Museum** – Even if you don’t love museums, seeing the Mona Lisa and the building itself is worth it.\n- **Notre‑Dame Cathedral** – Admire the exterior and surroundings; interior access is gradually reopening.\n- **Montmartre & Sacré‑Cœur** – Charming streets, artists, and great city views.\n\n### Classic Paris Experiences\n- **Stroll along the Seine** – Especially at sunset.\n- **Café culture** – Sit at a café with a coffee or glass of wine and people‑watch.\n- **Boulangeries & pastries** – Try croissants, pain au chocolat, macarons.\n- **Seine river cruise** – Relaxing and great for first‑time visitors.\n\n### Art, History & Culture\n- **Musée d’Orsay** – Impressionist masterpieces in a stunning former train station.\n- **Le Marais** – Historic district with boutiques, museums, and lively streets.\n- **Latin Quarter** – Bookshops, old streets, and student energy.\n\n### Food & Drink\n- **Bistro dining** – Try classic French dishes like boeuf bourguignon or duck confit.\n- **Food markets** – Marché des Enfants Rouges is a favorite.\n- **Wine & cheese tasting** – Many small shops offer guided tastings.\n\n### Day Trips (if you have extra time)\n- **Versailles** – Palace and gardens (half‑day or full‑day trip).\n- **Giverny** – Monet’s gardens (spring/summer).\n- **Champagne region** – For wine lovers.\n\n### Practical Tips\n- Buy museum tickets in advance.\n- Walk as much as possible—Paris is very walkable.\n- Learn a few French phrases; locals appreciate the effort.\n\nIf you’d like, tell me:\n- How many days you’ll be there  \n- Your interests (food, art, history, shopping, nightlife, romance, family travel)  \n- Your budget level  \n\nAnd I’ll create a personalized day‑by‑day itinerary for you.",
        "refusal": null,
        "role": "assistant",
        "annotations": null,
        "audio": null,
        "function_call": null,
        "tool_calls": null,
        "reasoning": null
      },
      "native_finish_reason": "completed"
    }
  ],
  "created": 1767585819,
  "model": "openai/gpt-5.2-chat",
  "object": "chat.completion",
  "service_tier": null,
  "system_fingerprint": null,
  "usage": {
    "completion_tokens": 506,
    "prompt_tokens": 44,
    "total_tokens": 550,
    "completion_tokens_details": {
      "accepted_prediction_tokens": null,
      "audio_tokens": null,
      "reasoning_tokens": 0,
      "rejected_prediction_tokens": null,
      "image_tokens": 0
    },
    "prompt_tokens_details": {
      "audio_tokens": 0,
      "cached_tokens": 0,
      "video_tokens": 0
    },
    "cost": 0.007161,
    "is_byok": false,
    "cost_details": {
      "upstream_inference_cost": null,
      "upstream_inference_prompt_cost": 0.000077,
      "upstream_inference_completions_cost": 0.007084
    }
  },
  "provider": "OpenAI"
}