Skip to content

← First steps

Your first call

Your first chat-completions request via curl and the OpenAI SDK pointed at OpenRouter, with model choice and reading the response.

7 slides 5 min read
  1. OpenRouter · Primers passos

    Your first call

    From key to your first model response, two ways.

    OpenRouter · First steps arlaf.dev
  2. OpenAI-compatible

    OpenRouter speaks the same protocol as the OpenAI API. You just change the base URL to https://openrouter.ai/api/v1 and put your key in the Authorization header.

    OpenRouter · First steps arlaf.dev
  3. The call with curl

    curl https://openrouter.ai/api/v1/chat/completions \
      -H "Authorization: Bearer $OPENROUTER_API_KEY" \
      -H "Content-Type: application/json" \
      -H "HTTP-Referer: https://elmeudomini.com" \
      -H "X-Title: La meva app" \
      -d '{
        "model": "openai/gpt-4o",
        "messages": [
          { "role": "user", "content": "Hola en una frase." }
        ]
      }'
    
    OpenRouter · First steps arlaf.dev
  4. The same call with the OpenAI SDK

    from openai import OpenAI
    import os
    
    client = OpenAI(
        base_url="https://openrouter.ai/api/v1",
        api_key=os.environ["OPENROUTER_API_KEY"],
    )
    
    resp = client.chat.completions.create(
        model="anthropic/claude-3.5-sonnet",
        messages=[{"role": "user", "content": "Hola en una frase."}],
    )
    print(resp.choices[0].message.content)
    
    OpenRouter · First steps arlaf.dev
  5. Choosing the model

    The model field is a slug shaped provider/model. Swap it and you change engines without touching anything else.

    • openai/gpt-4o — example of an OpenAI model.
    • anthropic/claude-3.5-sonnet — example of an Anthropic model.
    • The :free suffix points to a free variant with stricter limits.
    OpenRouter · First steps arlaf.dev
  6. Reading the response

    The response has the same shape as OpenAI. The text lives in choices[0].message.content and the usage block tells you how many tokens you spent.

    OpenRouter · First steps arlaf.dev
  7. If you can call OpenAI, you can call OpenRouter — only the address changes.
    OpenRouter · First steps arlaf.dev
Read the full note

La gràcia d’OpenRouter és que no has d’aprendre res nou: parla el mateix protocol que l’API d’OpenAI. La teva primera crida és una petició de chat completions a https://openrouter.ai/api/v1/chat/completions, autenticada amb el header Authorization: Bearer i la teva key.

Amb curl

La manera més directa de comprovar que tot funciona és un curl. Envies un JSON amb dos camps mínims: el model (un slug com openai/gpt-4o) i la llista de messages. Amb la key al header, ja tens resposta.

Hi ha dos headers opcionals que val la pena posar: HTTP-Referer i X-Title. Serveixen per atribuir l’app — el teu domini i el nom apareixen als rànquings públics d’OpenRouter i identifiquen el trànsit. No són obligatoris, però són bona pràctica si publiques una app.

Amb el SDK d’OpenAI

Si ja fas servir el SDK oficial d’OpenAI, només canvies dues coses: el base_url cap a OpenRouter i la api_key per la teva. La resta del codi és idèntic. Això vol dir que pots reaprofitar qualsevol projecte existent gairebé sense tocar-lo.

Llegir el que torna

La resposta segueix l’estructura d’OpenAI. El text generat viu a choices[0].message.content, i el bloc usage et diu els tokens d’entrada i de sortida — la base del que et descomptaran del crèdit.

Nota: els slugs concrets (openai/gpt-4o, anthropic/claude-3.5-sonnet) són exemples i el catàleg canvia sovint. Consulta la llista de models a la documentació per veure quins hi ha disponibles ara mateix.