import openai
import os
client = openai.OpenAI(
base_url='https://openrouter.ai/api/v1',
api_key=os.environ["OPENROUTER_API_KEY"]
)
MODEL = "openai/gpt-oss-120b:free" #@param ["openai/gpt-oss-120b:free"]
response = client.chat.completions.create(
model=MODEL,
messages=[
{"role": "system", "content": "You help students with their geography lessons."},
{"role": "user", "content": "How many provinces (aimags) in Mongolia start with the letter B?"},
]
)
print(response.choices[0].message.content)Using OpenAI APIs
In this notebook, we use the Python OpenAI SDK to call OpenAI models via OpenRouter. This allows us to interact with LLMs via code.
In this first example, we call an OpenAI model to discover the provinces in Mongolia that start with the letter B. Notice the two roles in the code.
The system role defines how the model should interact. The user role is the user asking the question.
We can customize the system role to take on a character or persona, as shown in this example:
import openai
import os
client = openai.OpenAI(
base_url='https://openrouter.ai/api/v1',
api_key=os.environ["OPENROUTER_API_KEY"]
)
MODEL = "openai/gpt-oss-120b:free" #@param ["openai/gpt-oss-120b:free"]
response = client.chat.completions.create(
model=MODEL,
messages=[
{"role": "system", "content": "You are an expert in dogs, based in Mongolia. Your role is to provide helpful information to students who want to learn more about keeping dogs at home. Answer in a concise but friendly manner."},
{"role": "user", "content": "How many times a day should I feed my Mongolian Bankhar, and what food is best?"},
]
)
print(response.choices[0].message.content)Now that you’ve seen both examples, take a moment to reflect on what you observed.
How did changing the system role change the response from the model? If you could design your own AI assistant, what persona or instructions would you put in the system role?
{ “question_type”: “multiple_choice”, “question”: “What is the purpose of the system role in the messages list?”, “options”: [ { “key”: “a”, “text”: “It asks the question the model should answer” }, { “key”: “b”, “text”: “It defines the model’s behavior, persona, or instructions” }, { “key”: “c”, “text”: “It stores the model’s previous responses” }, { “key”: “d”, “text”: “It sets the programming language used” } ], “answer”: “b”, “submitted_answer”: “” }
{ “question_type”: “true_false”, “question”: “The user role in the messages list represents the person asking the question.”, “answer”: “True”, “submitted_answer”: “” }
{ “question_type”: “freeform”, “question”: “What is the name of the service used in this notebook to route API requests to OpenAI models?”, “answer”: “OpenRouter”, “submitted_answer”: “” }