CS 212, AI Programming 1

Calling a Chat-Completion API

Contents

[TOC]

AI Model APIs

Model APIs are used when adding AI features to your own apps (chat, summarizing, translating, classifying, answering questions).

Chatbot Clients vs. the API

Most AI companies offer the same models in two different ways:

AI Model API Providers

Frontier Proprietary Model Providers

These companies provide access to proprietary models that can only be run on servers they control.

Company Model Family Most Capable Second Third Fourth
OpenAI ChatGPT GPT-6.2 Astra GPT-6.2 Sol GPT-6.1 Terra GPT-6 Luna
Anthropic Claude Claude Fable 5.2 Claude Opus 5.5 Claude Sonnet 5.5 Claude Haiku 5.5
Google Gemini Gemini 4 Carbon Gemini 4 Argon Gemini 4 Hydrogen Gemini 3.8 Flash
Meta Muse Muse Wonder Muse Spark Muse Ember  

Open Model Providers

These companies release open-weight models, which anyone can download and run on their own servers. Many of them also provide access to the models from their own servers.

LLM API Aggregators

An LLM API aggregator provides developers with access to many different models and hosting providers through a single, standardized API endpoint.

Working with an API Key

Get an API Key

  1. Create an account at openrouter.ai.
  2. Open the API Keys page and click “Create API Key”.
    • Give the key a name.
    • Optionally set a credit limit on the key.
    • Copy the key right away; it is shown only once.
  3. Models whose names end in :free cost nothing. They have low daily request limits, which are higher if you have purchased credits. Other models are billed per token from prepaid credits.

Treat the key like a password: don’t put it in your code or commit it to a repository.

Install the SDK

OpenRouter uses the same API format as OpenAI, so the OpenAI Python SDK works with it. The python-dotenv package reads your API key from a .env file:

pip install openai python-dotenv

Save the Key in a .env File

To keep the key out of your code, save it in a file named .env in your project folder:

OPENROUTER_API_KEY=YOUR_API_KEY

Make a Request

from dotenv import dotenv_values
from openai import OpenAI

# Read the settings in .env into a dictionary.
settings = dotenv_values(".env")

# Point the OpenAI client at OpenRouter instead of OpenAI.
client = OpenAI(
    base_url="https://openrouter.ai/api/v1",
    api_key=settings["OPENROUTER_API_KEY"],
)

response = client.chat.completions.create(
    # Model names have the form provider/model. Pick one on openrouter.ai/models.
    model="google/gemma-4-31b-it:free",
    messages=[{"role": "user", "content": "Explain how AI works in a few words"}],
)
print(response.choices[0].message.content)

Messages and Roles

A chat-completion request contains a list of messages. Each message is a dictionary with a role and content.

Role Who writes it Purpose
system The developer Sets the model’s behavior, tone, and rules (e.g., “You are a helpful tutor. Answer in two sentences.”). Usually the first message.
user The person using the app The question or instruction.
assistant The model The model’s earlier replies.
messages = [
    {"role": "system", "content": "You are a helpful tutor. Answer in two sentences."},
    {"role": "user", "content": "What is a token?"},
]
response = client.chat.completions.create(model="google/gemma-4-31b-it:free", messages=messages)
print(response.choices[0].message.content)

Multi-Turn Chats

The API is stateless: the model does not remember earlier requests. To have a conversation, the app must resend the whole conversation with every request.

  1. Start a list of messages (usually with a system message).
  2. Append the user’s message and send the list.
  3. Append the model’s reply to the list as an assistant message.
  4. Repeat from step 2 for each new user message.
messages = [{"role": "system", "content": "You are a helpful tutor. Answer in two sentences."}]

while True:
    user_input = input("You: ")
    if user_input.lower() in ("quit", "exit"):
        break
    messages.append({"role": "user", "content": user_input})

    response = client.chat.completions.create(
        model="google/gemma-4-31b-it:free",
        messages=messages,
    )
    reply = response.choices[0].message.content
    print("AI:", reply)

    messages.append({"role": "assistant", "content": reply})

Appendix

Model Parameters

Most chat models, including those available through OpenRouter, offer several key parameters (hyperparameters) that control the quality, style, and structure of the generated output. Understanding these allows you to fine-tune the model’s behavior for specific tasks, balancing creativity and factual consistency.

Here are the main model generation parameters. In the API request they are written in lowercase with underscores (temperature, top_p, max_tokens, stop, frequency_penalty). Not every model supports every parameter.

Parameter Description Typical Range Impact of Higher Value
Temperature Controls the randomness or creativity of the response. It mathematically scales the probability distribution of the next token selection. 0.0 - 2.0 More Creative/Diverse: The model is more likely to select lower-probability tokens, leading to more varied, surprising, and sometimes less coherent output.
Top-P (Nucleus Sampling) Selects the smallest set of most probable tokens whose cumulative probability exceeds the value P. 0.0 - 1.0 More Diverse/Adaptive: Dynamically increases the selection pool size in contexts where the probability distribution is flat (many good options) and narrows it when the distribution is sharp (one clear choice).
Top-K Limits the number of most probable tokens the model can choose from for the next word. 1 to the vocabulary size More Diverse/Wider Pool: Allows the model to sample from a larger, but fixed, set of the most likely next tokens. A value of K=1 is greedy decoding (always picks the single most probable token).
Max Output Tokens Sets the maximum length (in tokens) the model is allowed to generate in a single response. Model-Dependent Longer Responses: Allows for more extensive and detailed output, up to the model’s context window limit.
Stop Sequences A list of specific strings (e.g., \n\n, ---, \nUser:) that, if generated, will cause the model to immediately stop generating further text. Custom strings Structured Output: Enforces a specific end-point, which is crucial for creating structured outputs like code blocks or delimited lists.
Frequency Penalty Controls the likelihood of the model using tokens that have already appeared in the generated output. -2.0 - 2.0 Less Repetitive: Penalizes frequently used words, discouraging repetition and promoting new, more diverse vocabulary within the response.

A common strategy is to use Temperature as the primary control for creativity and leave Top-P and Top-K at their default values so they don’t restrict the model.

The OpenAI SDK has arguments for temperature, top_p, max_tokens, stop, and frequency_penalty. Other parameters, such as top_k, must be passed with the extra_body argument, and not every model supports them.

Installing the OpenAI SDK on macOS

OpenRouter can be used from Python with the OpenAI SDK, which is installed with the Python package installer, pip, not Homebrew (brew). Homebrew is primarily a package manager for macOS system tools and command-line applications.

Python SDK Installation

pip install openai python-dotenv

Best Practice: Use a Virtual Environment

It’s highly recommended to use a virtual environment to manage dependencies for your Python projects and avoid conflicts with other applications:

  1. Create a virtual environment:

    python3 -m venv venv-openrouter
    
  2. Activate the environment:

    source venv-openrouter/bin/activate
    
  3. Install the SDK:

    pip install openai python-dotenv
    
  4. Deactivate when done:

    deactivate
    

Reference

Parts of this document were drafted using Gemini Flash 2.5 and revised using Claude Sonnet 5.5.


Creative Commons License AI Programming 1 lecture notes by Brian Bird, written in 2025 and revised in , are licensed under a Creative Commons Attribution-ShareAlike 4.0 International License.