Call a model from code
10 min read
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 machine | Hosted API | |
|---|---|---|
| Setup | Download the weights and install a library | Create an account and an API key |
| Cost | Your own hardware and electricity | A price for each million tokens |
| Your data | Stays on your machine | Goes to the provider |
| Best quality available | Limited by the memory you have | The provider's largest models |
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:
pip install transformers torchThe 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.
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.
apply_chat_templatebuilds the string with the model's own chat markers, as in Lesson 13. The optionadd_generation_prompt=Trueadds the start of an assistant turn at the end.generateruns the reply loop from Lesson 5. It stops at the model's end token or after 80 new tokens.- The output holds the prompt and the reply together. The slice keeps only the new tokens, and
decodeturns 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.
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:
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_tokensintransformers, 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.
Why does the model forget the user's name?
Your app sends only the newest user message to the model on each request.
A model reads only what one request sends. Send the earlier messages again to keep the conversation.
Where should the API key go?
You are about to commit a script that calls a hosted model.
A key in a code file ends up in version control. Read it from the environment instead.
What does add_generation_prompt=True do?
You build the prompt with tokenizer.apply_chat_template.
The template ends with the start of an assistant turn, so the next tokens the model writes are the assistant's reply.
Your reading position is saved
0 of 20 complete
Lesson complete
Call a model from code
Up next