-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathopenai_demo.py
More file actions
152 lines (124 loc) · 5.75 KB
/
Copy pathopenai_demo.py
File metadata and controls
152 lines (124 loc) · 5.75 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
"""
OpenAI API in Python — Project Demo
====================================
Covers:
- Client setup with python-dotenv
- Basic chat completion
- System messages
- Temperature experimentation
- Max-token limits
- Interactive chat loop
"""
import os
from dotenv import load_dotenv
from openai import OpenAI
# ── 1. Load API key from .env ──────────────────────────────────────────────────
load_dotenv()
client = OpenAI() # reads OPENAI_API_KEY from the environment automatically
MODEL = "gpt-4o-mini" # cheap & fast; swap for "gpt-4o" when you need more power
# ── 2. Helper: single completion ───────────────────────────────────────────────
def chat(
user_message: str,
system_message: str = "You are a helpful assistant.",
temperature: float = 0.7,
max_tokens: int = 512,
) -> str:
"""
Send one user message and return the assistant reply as a string.
Parameters
----------
user_message : The text prompt from the user.
system_message : Sets the model's persona / behaviour.
temperature : 0 = deterministic, 2 = very random. Default 0.7.
max_tokens : Hard cap on reply length (1 token ≈ 4 chars in English).
"""
response = client.chat.completions.create(
model = MODEL,
temperature = temperature,
max_tokens = max_tokens,
messages = [
{"role": "system", "content": system_message},
{"role": "user", "content": user_message},
],
)
return response.choices[0].message.content
# ── 3. Demo A – Basic call ──────────────────────────────────────────────────────
def demo_basic():
print("\n" + "="*60)
print("DEMO A — Basic API call")
print("="*60)
reply = chat("What is a large language model? Answer in two sentences.")
print(reply)
# ── 4. Demo B – Custom system message ──────────────────────────────────────────
def demo_system_message():
print("\n" + "="*60)
print("DEMO B — Custom system message")
print("="*60)
personas = {
"Pirate": "You are a salty pirate. Answer every question using pirate slang.",
"Professor": "You are a university professor. Give rigorous, academic answers.",
"ELI5": "Explain everything as if talking to a 5-year-old.",
}
question = "How does the internet work?"
for name, system_msg in personas.items():
print(f"\n[{name}]")
print(chat(question, system_message=system_msg, max_tokens=120))
# ── 5. Demo C – Temperature comparison ─────────────────────────────────────────
def demo_temperature():
print("\n" + "="*60)
print("DEMO C — Temperature comparison (same prompt, 3 runs each)")
print("="*60)
prompt = "Give me a creative name for a coffee shop."
for temp in [0.0, 0.9, 1.8]:
print(f"\n temperature = {temp}")
for _ in range(3):
reply = chat(prompt, temperature=temp, max_tokens=20)
print(f" → {reply.strip()}")
# ── 6. Demo D – Max-tokens limit ───────────────────────────────────────────────
def demo_max_tokens():
print("\n" + "="*60)
print("DEMO D — max_tokens comparison")
print("="*60)
prompt = "Explain quantum computing."
for limit in [20, 80, 256]:
print(f"\n max_tokens = {limit}")
reply = chat(prompt, max_tokens=limit)
tokens_used = len(reply.split()) # rough word count
print(f" (~{tokens_used} words) {reply[:200]}{'…' if len(reply)>200 else ''}")
# ── 7. Demo E – Interactive chat loop ──────────────────────────────────────────
def demo_interactive():
"""
A simple multi-turn chat that keeps conversation history
so the model remembers what was said earlier in the session.
"""
print("\n" + "="*60)
print("DEMO E — Interactive chat (type 'quit' to exit)")
print("="*60)
system_msg = "You are a concise, friendly assistant. Keep replies under 3 sentences."
history: list[dict] = [{"role": "system", "content": system_msg}]
while True:
user_input = input("\nYou: ").strip()
if user_input.lower() in {"quit", "exit", "q"}:
print("Goodbye!")
break
if not user_input:
continue
history.append({"role": "user", "content": user_input})
response = client.chat.completions.create(
model = MODEL,
temperature = 0.7,
max_tokens = 256,
messages = history,
)
assistant_reply = response.choices[0].message.content
history.append({"role": "assistant", "content": assistant_reply})
print(f"\nAssistant: {assistant_reply}")
# ── Main ────────────────────────────────────────────────────────────────────────
if __name__ == "__main__":
demo_basic()
demo_system_message()
demo_temperature()
demo_max_tokens()
run_interactive = input("\n\nLaunch interactive chat? [y/N]: ").strip().lower()
if run_interactive == "y":
demo_interactive()