-
-
Notifications
You must be signed in to change notification settings - Fork 25
Expand file tree
/
Copy pathpython-openai.html
More file actions
479 lines (415 loc) · 21.4 KB
/
python-openai.html
File metadata and controls
479 lines (415 loc) · 21.4 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
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="icon" type="image/png" href="images/logo.png">
<link rel="apple-touch-icon" href="images/logo.png">
<title>Python OpenAI API - Developer Toolkit | DevDunia</title>
<meta name="description" content="Python OpenAI API examples and code snippets. ChatGPT, GPT-4, and other OpenAI API integrations for developers.">
<script src="https://cdn.tailwindcss.com"></script>
<script src="js/common.js"></script>
<style>
body {
background: linear-gradient(135deg, #0f172a 0%, #1e293b 50%, #0f172a 100%);
}
</style>
</head>
<body class="h-screen lg:ml-72">
<!-- Background: Consistent Subtle Dark Gradient -->
<div class="fixed inset-0 -z-10 bg-gradient-to-br from-gray-900 via-slate-900 to-gray-900"></div>
<!-- Main Container -->
<div class="main-content">
<div class="relative z-10 container mx-auto px-4 pt-16 pb-24 sm:px-6 lg:px-8">
<!-- Page Header -->
<div class="text-center mb-12">
<h1 class="text-3xl sm:text-4xl font-bold mb-4 tracking-tight
text-transparent bg-clip-text bg-gradient-to-r from-emerald-400 to-teal-500">
Python OpenAI API
</h1>
<p class="text-lg text-gray-400 max-w-2xl mx-auto">
ChatGPT, GPT-4, and other OpenAI API integrations with Python examples.
</p>
</div>
<!-- Tool Container -->
<div class="max-w-6xl mx-auto">
<div class="bg-slate-800/70 backdrop-blur-md rounded-lg shadow-lg border border-slate-700/60 p-6">
<!-- Setup Section -->
<div class="mb-8">
<h2 class="text-xl font-semibold text-emerald-300 mb-4">Setup & Installation</h2>
<div class="bg-slate-700/30 rounded-lg p-4 border border-slate-600/50">
<div class="flex items-center justify-between mb-3">
<h3 class="text-lg font-medium text-emerald-300">Installation & Basic Setup</h3>
<button class="copy-btn px-3 py-1 bg-emerald-600 hover:bg-emerald-700 text-white text-xs rounded transition-colors duration-200 flex items-center space-x-1" data-target="setup-code">
<svg class="w-3 h-3" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 16H6a2 2 0 01-2-2V6a2 2 0 012-2h8a2 2 0 012 2v8a2 2 0 01-2 2h-2m-6-4l2 2m0 0l2-2m-2 2V10"></path>
</svg>
<span>Copy</span>
</button>
</div>
<textarea
id="setup-code"
rows="8"
class="w-full px-3 py-2 bg-slate-800/50 border border-slate-600 rounded text-gray-200 font-mono text-sm resize-none"
readonly
># Install OpenAI library
pip install openai
# Basic setup
import openai
import os
# Set your API key
openai.api_key = "your-api-key-here"
# Or set as environment variable
# os.environ["OPENAI_API_KEY"] = "your-api-key-here"
# Initialize client (for newer versions)
from openai import OpenAI
client = OpenAI(api_key="your-api-key-here")</textarea>
</div>
</div>
<!-- ChatGPT Examples Section -->
<div class="mb-8">
<h2 class="text-xl font-semibold text-emerald-300 mb-4">ChatGPT Examples</h2>
<div class="grid grid-cols-1 md:grid-cols-2 gap-6">
<!-- Simple Chat -->
<div class="bg-slate-700/30 rounded-lg p-4 border border-slate-600/50">
<div class="flex items-center justify-between mb-3">
<h3 class="text-lg font-medium text-emerald-300">Simple Chat</h3>
<button class="copy-btn px-3 py-1 bg-emerald-600 hover:bg-emerald-700 text-white text-xs rounded transition-colors duration-200 flex items-center space-x-1" data-target="chat-code">
<svg class="w-3 h-3" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 16H6a2 2 0 01-2-2V6a2 2 0 012-2h8a2 2 0 012 2v8a2 2 0 01-2 2h-2m-6-4l2 2m0 0l2-2m-2 2V10"></path>
</svg>
<span>Copy</span>
</button>
</div>
<textarea
id="chat-code"
rows="12"
class="w-full px-3 py-2 bg-slate-800/50 border border-slate-600 rounded text-gray-200 font-mono text-sm resize-none"
readonly
>import openai
def simple_chat(message):
response = openai.ChatCompletion.create(
model="gpt-3.5-turbo",
messages=[
{"role": "system", "content": "You are a helpful assistant."},
{"role": "user", "content": message}
],
max_tokens=150,
temperature=0.7
)
return response.choices[0].message.content
# Usage
message = "Explain quantum computing in simple terms"
response = simple_chat(message)
print(response)
# With newer API
from openai import OpenAI
client = OpenAI()
def chat_with_gpt(message):
response = client.chat.completions.create(
model="gpt-3.5-turbo",
messages=[
{"role": "user", "content": message}
]
)
return response.choices[0].message.content</textarea>
</div>
<!-- Conversation History -->
<div class="bg-slate-700/30 rounded-lg p-4 border border-slate-600/50">
<div class="flex items-center justify-between mb-3">
<h3 class="text-lg font-medium text-emerald-300">Conversation History</h3>
<button class="copy-btn px-3 py-1 bg-emerald-600 hover:bg-emerald-700 text-white text-xs rounded transition-colors duration-200 flex items-center space-x-1" data-target="conversation-code">
<svg class="w-3 h-3" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 16H6a2 2 0 01-2-2V6a2 2 0 012-2h8a2 2 0 012 2v8a2 2 0 01-2 2h-2m-6-4l2 2m0 0l2-2m-2 2V10"></path>
</svg>
<span>Copy</span>
</button>
</div>
<textarea
id="conversation-code"
rows="12"
class="w-full px-3 py-2 bg-slate-800/50 border border-slate-600 rounded text-gray-200 font-mono text-sm resize-none"
readonly
>from openai import OpenAI
client = OpenAI()
class ChatBot:
def __init__(self):
self.conversation_history = []
def add_message(self, role, content):
self.conversation_history.append({"role": role, "content": content})
def chat(self, user_message):
self.add_message("user", user_message)
response = client.chat.completions.create(
model="gpt-3.5-turbo",
messages=self.conversation_history,
max_tokens=200
)
assistant_message = response.choices[0].message.content
self.add_message("assistant", assistant_message)
return assistant_message
def get_history(self):
return self.conversation_history
# Usage
bot = ChatBot()
response1 = bot.chat("Hello, how are you?")
response2 = bot.chat("What's the weather like?")
print("History:", bot.get_history())</textarea>
</div>
</div>
</div>
<!-- GPT-4 Examples Section -->
<div class="mb-8">
<h2 class="text-xl font-semibold text-emerald-300 mb-4">GPT-4 Examples</h2>
<div class="grid grid-cols-1 md:grid-cols-2 gap-6">
<!-- Code Generation -->
<div class="bg-slate-700/30 rounded-lg p-4 border border-slate-600/50">
<div class="flex items-center justify-between mb-3">
<h3 class="text-lg font-medium text-emerald-300">Code Generation</h3>
<button class="copy-btn px-3 py-1 bg-emerald-600 hover:bg-emerald-700 text-white text-xs rounded transition-colors duration-200 flex items-center space-x-1" data-target="code-gen-code">
<svg class="w-3 h-3" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 16H6a2 2 0 01-2-2V6a2 2 0 012-2h8a2 2 0 012 2v8a2 2 0 01-2 2h-2m-6-4l2 2m0 0l2-2m-2 2V10"></path>
</svg>
<span>Copy</span>
</button>
</div>
<textarea
id="code-gen-code"
rows="12"
class="w-full px-3 py-2 bg-slate-800/50 border border-slate-600 rounded text-gray-200 font-mono text-sm resize-none"
readonly
>from openai import OpenAI
client = OpenAI()
def generate_code(description, language="python"):
prompt = f"""Generate {language} code for the following task:
{description}
Please provide:
1. Clean, well-commented code
2. Brief explanation of the approach
3. Example usage if applicable"""
response = client.chat.completions.create(
model="gpt-4",
messages=[
{"role": "system", "content": "You are an expert programmer. Generate clean, efficient code with proper comments."},
{"role": "user", "content": prompt}
],
max_tokens=1000,
temperature=0.3
)
return response.choices[0].message.content
# Usage
description = "Create a function to find the longest common subsequence between two strings"
code = generate_code(description, "python")
print(code)</textarea>
</div>
<!-- Text Analysis -->
<div class="bg-slate-700/30 rounded-lg p-4 border border-slate-600/50">
<div class="flex items-center justify-between mb-3">
<h3 class="text-lg font-medium text-emerald-300">Text Analysis</h3>
<button class="copy-btn px-3 py-1 bg-emerald-600 hover:bg-emerald-700 text-white text-xs rounded transition-colors duration-200 flex items-center space-x-1" data-target="analysis-code">
<svg class="w-3 h-3" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 16H6a2 2 0 01-2-2V6a2 2 0 012-2h8a2 2 0 012 2v8a2 2 0 01-2 2h-2m-6-4l2 2m0 0l2-2m-2 2V10"></path>
</svg>
<span>Copy</span>
</button>
</div>
<textarea
id="analysis-code"
rows="12"
class="w-full px-3 py-2 bg-slate-800/50 border border-slate-600 rounded text-gray-200 font-mono text-sm resize-none"
readonly
>from openai import OpenAI
client = OpenAI()
def analyze_text(text, analysis_type="sentiment"):
analysis_prompts = {
"sentiment": "Analyze the sentiment of this text (positive, negative, neutral) and provide a confidence score.",
"summary": "Provide a concise summary of this text in 2-3 sentences.",
"keywords": "Extract the main keywords and key phrases from this text.",
"tone": "Analyze the tone and writing style of this text."
}
prompt = f"{analysis_prompts.get(analysis_type, 'Analyze this text')}\n\nText: {text}"
response = client.chat.completions.create(
model="gpt-4",
messages=[
{"role": "system", "content": "You are a text analysis expert. Provide clear, structured analysis."},
{"role": "user", "content": prompt}
],
max_tokens=300,
temperature=0.2
)
return response.choices[0].message.content
# Usage
text = "I'm really excited about this new project! It's going to be amazing."
sentiment = analyze_text(text, "sentiment")
summary = analyze_text(text, "summary")
print(f"Sentiment: {sentiment}")
print(f"Summary: {summary}")</textarea>
</div>
</div>
</div>
<!-- Advanced Features Section -->
<div class="mb-8">
<h2 class="text-xl font-semibold text-emerald-300 mb-4">Advanced Features</h2>
<div class="grid grid-cols-1 md:grid-cols-2 gap-6">
<!-- Function Calling -->
<div class="bg-slate-700/30 rounded-lg p-4 border border-slate-600/50">
<div class="flex items-center justify-between mb-3">
<h3 class="text-lg font-medium text-emerald-300">Function Calling</h3>
<button class="copy-btn px-3 py-1 bg-emerald-600 hover:bg-emerald-700 text-white text-xs rounded transition-colors duration-200 flex items-center space-x-1" data-target="function-code">
<svg class="w-3 h-3" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 16H6a2 2 0 01-2-2V6a2 2 0 012-2h8a2 2 0 012 2v8a2 2 0 01-2 2h-2m-6-4l2 2m0 0l2-2m-2 2V10"></path>
</svg>
<span>Copy</span>
</button>
</div>
<textarea
id="function-code"
rows="15"
class="w-full px-3 py-2 bg-slate-800/50 border border-slate-600 rounded text-gray-200 font-mono text-sm resize-none"
readonly
>from openai import OpenAI
import json
client = OpenAI()
# Define functions that the model can call
functions = [
{
"name": "get_weather",
"description": "Get current weather for a location",
"parameters": {
"type": "object",
"properties": {
"location": {
"type": "string",
"description": "City name"
}
},
"required": ["location"]
}
}
]
def get_weather(location):
# Mock weather function
return f"Weather in {location}: Sunny, 25°C"
def chat_with_functions(message):
response = client.chat.completions.create(
model="gpt-3.5-turbo",
messages=[{"role": "user", "content": message}],
functions=functions,
function_call="auto"
)
message = response.choices[0].message
if message.function_call:
function_name = message.function_call.name
function_args = json.loads(message.function_call.arguments)
if function_name == "get_weather":
result = get_weather(function_args["location"])
# Send function result back to the model
response = client.chat.completions.create(
model="gpt-3.5-turbo",
messages=[
{"role": "user", "content": message},
{"role": "function", "name": function_name, "content": result}
]
)
return response.choices[0].message.content
return message.content
# Usage
result = chat_with_functions("What's the weather like in Tokyo?")
print(result)</textarea>
</div>
<!-- Streaming Responses -->
<div class="bg-slate-700/30 rounded-lg p-4 border border-slate-600/50">
<div class="flex items-center justify-between mb-3">
<h3 class="text-lg font-medium text-emerald-300">Streaming Responses</h3>
<button class="copy-btn px-3 py-1 bg-emerald-600 hover:bg-emerald-700 text-white text-xs rounded transition-colors duration-200 flex items-center space-x-1" data-target="streaming-code">
<svg class="w-3 h-3" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 16H6a2 2 0 01-2-2V6a2 2 0 012-2h8a2 2 0 012 2v8a2 2 0 01-2 2h-2m-6-4l2 2m0 0l2-2m-2 2V10"></path>
</svg>
<span>Copy</span>
</button>
</div>
<textarea
id="streaming-code"
rows="15"
class="w-full px-3 py-2 bg-slate-800/50 border border-slate-600 rounded text-gray-200 font-mono text-sm resize-none"
readonly
>from openai import OpenAI
import sys
client = OpenAI()
def stream_chat(message):
stream = client.chat.completions.create(
model="gpt-3.5-turbo",
messages=[{"role": "user", "content": message}],
stream=True
)
full_response = ""
for chunk in stream:
if chunk.choices[0].delta.content is not None:
content = chunk.choices[0].delta.content
print(content, end='', flush=True)
full_response += content
return full_response
def stream_with_callback(message, callback=None):
stream = client.chat.completions.create(
model="gpt-3.5-turbo",
messages=[{"role": "user", "content": message}],
stream=True
)
full_response = ""
for chunk in stream:
if chunk.choices[0].delta.content is not None:
content = chunk.choices[0].delta.content
full_response += content
if callback:
callback(content)
return full_response
# Usage
def print_chunk(chunk):
print(chunk, end='', flush=True)
message = "Write a short story about a robot learning to paint"
response = stream_with_callback(message, print_chunk)</textarea>
</div>
</div>
</div>
<!-- Quick Reference Section -->
<div class="mt-8 p-4 bg-slate-700/30 rounded-lg border border-slate-600/50">
<h3 class="text-lg font-semibold text-emerald-400 mb-3">Quick Reference</h3>
<div class="grid grid-cols-1 md:grid-cols-2 gap-4 text-sm">
<div>
<p class="text-gray-300 font-medium mb-2">Popular Models:</p>
<ul class="text-gray-400 space-y-1">
<li>• <code>gpt-3.5-turbo</code> - Fast, cost-effective</li>
<li>• <code>gpt-4</code> - Most capable, higher cost</li>
<li>• <code>gpt-4-turbo</code> - Latest GPT-4 variant</li>
<li>• <code>text-embedding-ada-002</code> - Embeddings</li>
</ul>
</div>
<div>
<p class="text-gray-300 font-medium mb-2">Key Parameters:</p>
<ul class="text-gray-400 space-y-1">
<li>• <code>max_tokens</code> - Response length limit</li>
<li>• <code>temperature</code> - Creativity (0-2)</li>
<li>• <code>top_p</code> - Nucleus sampling</li>
<li>• <code>stream</code> - Real-time responses</li>
</ul>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- Include Final Sidebar -->
<div id="sidebar-container"></div>
<script>
// Load final_sidebar.html content
fetch('final_sidebar.html')
.then(response => response.text())
.then(html => {
document.getElementById('sidebar-container').innerHTML = html;
})
.catch(error => {
console.error('Error loading sidebar:', error);
});
</script>
</body>
</html>