CS 212, AI Programming 1
[TOC]
Model APIs are used when adding AI features to your own apps (chat, summarizing, translating, classifying, answering questions).
Most AI companies offer the same models in two different ways:
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 |
| Gemini | Gemini 4 Carbon | Gemini 4 Argon | Gemini 4 Hydrogen | Gemini 3.8 Flash | |
| Meta | Muse | Muse Wonder | Muse Spark | Muse Ember |
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.
An LLM API aggregator provides developers with access to many different models and hosting providers through a single, standardized API endpoint.
: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.
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
python --version (Windows) or python3 --version (macOS/Linux).python3 and pip3 if python and pip aren’t found. On Windows, py -m pip install openai python-dotenv works if pip isn’t found.Install into a virtual environment to keep projects separate. On macOS, see Installing the OpenAI SDK on macOS. On Windows:
python -m venv .venv
.venv\Scripts\activate
pip show openai python-dotenv.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
.env, with nothing before the dot. On Windows, Notepad may save it as .env.txt. Creating the file in VS Code avoids this..env to your .gitignore file so the key never gets committed..env file.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)
model string. The rest of the code stays the same.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)
response.choices[0].message.content. Its role is assistant.system role differently or ignore it. Check the model’s documentation if it doesn’t seem to follow the instructions.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.
system message).assistant 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})
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.
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.
pip install openai python-dotenv
It’s highly recommended to use a virtual environment to manage dependencies for your Python projects and avoid conflicts with other applications:
Create a virtual environment:
python3 -m venv venv-openrouter
Activate the environment:
source venv-openrouter/bin/activate
Install the SDK:
pip install openai python-dotenv
Deactivate when done:
deactivate
OpenAI Python SDK—OpenAI GitHub Repo
Model Ranking and Price Comparison—Brian Bird
Parts of this document were drafted using Gemini Flash 2.5 and revised using Claude Sonnet 5.5.
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.