|
| 1 | +""" |
| 2 | +Ch. 4 — Context Windows |
| 3 | +Assignment: Make the context window visible |
| 4 | +
|
| 5 | +Run this as-is. Then add a 4th turn that asks the model to recall |
| 6 | +something from turn 1. Watch whether it does. |
| 7 | +
|
| 8 | +No API key needed. The mock server starts automatically in Ona. |
| 9 | +To use a real model: add OPENAI_API_KEY as an Ona User Secret at |
| 10 | +https://app.gitpod.io/ai?user-settings=secrets |
| 11 | +The starter detects it and switches with no code changes. |
| 12 | +Docs: https://ona.com/docs/ona/configuration/secrets/user-secrets |
| 13 | +""" |
| 14 | + |
| 15 | +import os |
| 16 | +import json |
| 17 | +from openai import OpenAI |
| 18 | + |
| 19 | +# Auto-detects mock vs. real: if OPENAI_API_KEY is set, uses it directly. |
| 20 | +# Otherwise falls back to the local mock server. |
| 21 | +if os.environ.get("OPENAI_API_KEY"): |
| 22 | + client = OpenAI() |
| 23 | + print("Real OpenAI API detected.") |
| 24 | +else: |
| 25 | + client = OpenAI( |
| 26 | + base_url=os.environ.get("OPENAI_BASE_URL", "http://localhost:8001/v1"), |
| 27 | + api_key="mock", |
| 28 | + ) |
| 29 | + print("No API key found. Using mock server.") |
| 30 | + print("Add OPENAI_API_KEY as an Ona User Secret to use a real model.") |
| 31 | + print("https://app.gitpod.io/ai?user-settings=secrets\n") |
| 32 | + |
| 33 | +MODEL = os.environ.get("MODEL", "gpt-4o-mini") |
| 34 | + |
| 35 | +# Try to import tiktoken for accurate token counts; fall back to estimate. |
| 36 | +try: |
| 37 | + import tiktoken |
| 38 | + enc = tiktoken.encoding_for_model("gpt-4o") |
| 39 | + def count_tokens(messages: list) -> int: |
| 40 | + total = 0 |
| 41 | + for m in messages: |
| 42 | + total += 4 # per-message overhead |
| 43 | + total += len(enc.encode(str(m.get("content") or ""))) |
| 44 | + return total |
| 45 | + print("tiktoken found. Token counts are accurate.\n") |
| 46 | +except ImportError: |
| 47 | + def count_tokens(messages: list) -> int: |
| 48 | + # Rough estimate: 1 token per 4 chars |
| 49 | + raw = json.dumps(messages) |
| 50 | + return len(raw) // 4 |
| 51 | + print("tiktoken not installed. Token counts are estimates.") |
| 52 | + print("Run: pip install tiktoken\n") |
| 53 | + |
| 54 | + |
| 55 | +def print_context(messages: list, label: str = "") -> None: |
| 56 | + tokens = count_tokens(messages) |
| 57 | + bar = "─" * 56 |
| 58 | + print(f"\n┌{bar}┐") |
| 59 | + header = f" Context window {label} ({len(messages)} messages, ~{tokens} tokens)" |
| 60 | + print(f"│{header:<56}│") |
| 61 | + print(f"├{bar}┤") |
| 62 | + for m in messages: |
| 63 | + role = m["role"].upper() |
| 64 | + content = str(m.get("content") or "") |
| 65 | + preview = content[:120].replace("\n", " ") |
| 66 | + if len(content) > 120: |
| 67 | + preview += "…" |
| 68 | + print(f"│ [{role:<9}] {preview:<44}│") |
| 69 | + print(f"└{bar}┘") |
| 70 | + |
| 71 | + |
| 72 | +def chat(messages: list, user_message: str) -> str: |
| 73 | + messages.append({"role": "user", "content": user_message}) |
| 74 | + print_context(messages, label="→ sending") |
| 75 | + |
| 76 | + response = client.chat.completions.create( |
| 77 | + model=MODEL, |
| 78 | + messages=messages, |
| 79 | + ) |
| 80 | + reply = response.choices[0].message.content |
| 81 | + messages.append({"role": "assistant", "content": reply}) |
| 82 | + print_context(messages, label="← received") |
| 83 | + return reply |
| 84 | + |
| 85 | + |
| 86 | +# ── Conversation ────────────────────────────────────────────────────────────── |
| 87 | + |
| 88 | +messages = [ |
| 89 | + { |
| 90 | + "role": "system", |
| 91 | + "content": ( |
| 92 | + "You are a concise technical assistant. " |
| 93 | + "Keep answers to 2–3 sentences unless asked for more." |
| 94 | + ), |
| 95 | + } |
| 96 | +] |
| 97 | + |
| 98 | +print_context(messages, label="initial") |
| 99 | + |
| 100 | +# Turn 1 — plant a specific fact early in the context |
| 101 | +turn1 = chat(messages, "What is a context window? Give me one concrete number to remember.") |
| 102 | +print(f"\nAssistant: {turn1}\n") |
| 103 | + |
| 104 | +# Turn 2 — add noise in the middle |
| 105 | +turn2 = chat(messages, "Why does the order of information in the context window matter?") |
| 106 | +print(f"\nAssistant: {turn2}\n") |
| 107 | + |
| 108 | +# Turn 3 — add more noise |
| 109 | +turn3 = chat(messages, "What is the 'lost in the middle' problem?") |
| 110 | +print(f"\nAssistant: {turn3}\n") |
| 111 | + |
| 112 | +# ── Your turn ───────────────────────────────────────────────────────────────── |
| 113 | +# Add a 4th turn. Ask the model to recall the specific number from turn 1. |
| 114 | +# Does it remember? |
| 115 | +# |
| 116 | +# turn4 = chat(messages, "What was the specific number you mentioned first?") |
| 117 | +# print(f"\nAssistant: {turn4}\n") |
| 118 | +# |
| 119 | +# Then add 5 to 10 more turns of unrelated content before asking again. |
| 120 | +# Does recall degrade? |
| 121 | +# ───────────────────────────────────────────────────────────────────────────── |
| 122 | + |
| 123 | +print("\n── Summary ──────────────────────────────────────────────────────────────") |
| 124 | +print(f"Messages in context : {len(messages)}") |
| 125 | +print(f"Tokens used : ~{count_tokens(messages)}") |
| 126 | +print(f"Turns completed : {(len(messages) - 1) // 2}") |
| 127 | +print() |
| 128 | +print("Questions to answer:") |
| 129 | +print(" 1. At what turn did recall start to degrade?") |
| 130 | +print(" 2. Which messages would you drop first to stay under budget?") |
0 commit comments