Lesson 12 of 23 · Part 1: API Basics

Few-Shot Learning

Teach the AI new tasks by providing examples in the conversation.

Last time: JSON mode (response_format) makes the AI reply in valid JSON that programs can read.
Today: We teach the AI a brand new task just by showing it a few examples first.
OpenAI
client
print()
messages
Source Code
1# 4_few_shot_learning.py
2from openai import OpenAI
3client = OpenAI()
4
5print("Teaching the AI a new task (sentiment analysis) with examples...")
6
7messages = [
8    {"role": "system", "content": "You are a sentiment classifier. Respond with only 'Positive', 'Negative', or 'Neutral'."},
9
10    # Example 1
11    {"role": "user", "content": "I love this product!"},
12    {"role": "assistant", "content": "Positive"},
13
14    # Example 2
15    {"role": "user", "content": "This is terrible."},
16    {"role": "assistant", "content": "Negative"},
17
18    # Now, the real question
19    {"role": "user", "content": "It's okay, not great."}
20]
21
22response = client.chat.completions.create(
23    model="gpt-4o-mini",
24    messages=messages
25)
26
27print(f"\nAI's classification for 'It's okay, not great.':")
28print(response.choices[0].message.content)

No output yet...

← Prev
1/0
Next: Challenge →