Papa Programmer
Lesson 16 of 20

Call a model from code

10 min read

Optional

Two ways to run a model

Before you write code, choose where the Large language modelA model trained on a huge amount of text to predict the next token. Chat replies, summaries and code all come from repeating that prediction. Often shortened to LLM. runs.

Open model on your machineHosted API
SetupDownload the weights and install a libraryCreate an account and an API key
CostYour own hardware and electricityA price for each million tokens
Your dataStays on your machineGoes to the provider
Best quality availableLimited by the memory you haveThe provider's largest models
Running a model yourself and calling a hosted API

A small open model is the fastest way to learn, because it needs no account and no key. A hosted API is usually the better choice for a product, because the largest models do not fit on one computer.

Run a small open model

The Hugging Face transformers library runs thousands of open models. Install it with PyTorch:

bash
pip install transformers torch

The program below loads SmolLM2-135M-Instruct, a model with 135 million parameters. The first run downloads a few hundred megabytes of weights. It needs no account, and it runs on an ordinary laptop processor.

python
from transformers import AutoModelForCausalLM, AutoTokenizer

name = "HuggingFaceTB/SmolLM2-135M-Instruct"
tokenizer = AutoTokenizer.from_pretrained(name)
model = AutoModelForCausalLM.from_pretrained(name)

messages = [
	{"role": "system", "content": "You are a patient teacher. Answer in two sentences."},
	{"role": "user", "content": "What is a token?"},
]

inputs = tokenizer.apply_chat_template(
	messages, add_generation_prompt=True, return_dict=True, return_tensors="pt"
)
output = model.generate(**inputs, max_new_tokens=80)
new_tokens = output[0][inputs["input_ids"].shape[-1]:]
print(tokenizer.decode(new_tokens, skip_special_tokens=True))

Each line does one job.

  1. apply_chat_template builds the string with the model's own chat markers, as in Lesson 13. The option add_generation_prompt=True adds the start of an assistant turn at the end.
  2. generate runs the reply loop from Lesson 5. It stops at the model's end token or after 80 new tokens.
  3. The output holds the prompt and the reply together. The slice keeps only the new tokens, and decode turns them back into text.

A model this small writes simple and sometimes wrong answers. The code stays the same for larger models. Change name to a bigger model when your computer has the memory for it. Lesson 9 shows how to work out how much it needs.

The model has no memory

The model reads only what you send in one request. To hold a conversation, add the model's reply and the next question to the list, then send the whole list again.

python
messages = [
	{"role": "system", "content": "You are a patient teacher. Answer in two sentences."},
	{"role": "user", "content": "What is a token?"},
]

reply = "A token is a small piece of text, such as a word or part of a word. Models read and write text one token at a time."
messages.append({"role": "assistant", "content": reply})
messages.append({"role": "user", "content": "How many tokens is a page of English?"})

for message in messages:
	print(f"{message['role']:9} {message['content'][:48]}")

It prints the four messages that the next request sends:

text
system    You are a patient teacher. Answer in two sentenc
user      What is a token?
assistant A token is a small piece of text, such as a word
user      How many tokens is a page of English?

Every turn makes the next request longer. In a long chat, old turns use up the context window and add cost, so many apps summarise or drop the oldest turns.

Hosted APIs take the same messages

Hosted APIs, such as those from Anthropic and OpenAI, use the same idea. A request names the model, passes the list of messages and sets the longest reply. The response holds the reply and a count of input and output tokens, which is what the provider charges for. The System promptThe instructions at the start of a prompt that set the model's role, its rules and the format of its answer. It stays the same on every call. goes in its own field in some APIs and in the message list in others. Check the provider's documentation for the exact names.

Keep the API key out of your code. Store it in an environment variable, and read it when the program starts. A key in a code file ends up in version control sooner or later.

Settings worth knowing

  • Maximum length. The most tokens the reply may have. max_new_tokens in transformers, and a similar name in most APIs.
  • Temperature. How much randomness goes into each pick. Lesson 17 explains TemperatureA setting that sharpens or flattens the probabilities before a token is picked. A low temperature makes the most likely token win more often. A high temperature gives unlikely tokens more chances. and the related settings.
  • Stop sequences. Text that ends the reply as soon as it appears.
Same shape everywhereA list of messages goes in, and the next message comes out.
Send the whole conversationThe model keeps no memory between requests.
Keep keys out of codeRead the API key from an environment variable.

Your reading position is saved

0%

0 of 20 complete

Contents

Learning tools