forked from IncomeStreamSurfer/context-engineering-intro
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathopenai_example.py
More file actions
163 lines (139 loc) · 4.67 KB
/
openai_example.py
File metadata and controls
163 lines (139 loc) · 4.67 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
import os
from openai import OpenAI
from typing import List, Dict
import asyncio
# Initialize the OpenAI client
client = OpenAI(api_key=os.getenv("OPENAI_API_KEY"))
def generate_story(prompt: str, max_tokens: int = 500) -> str:
"""
Generate a creative story using OpenAI's API.
Args:
prompt: The story prompt to start with
max_tokens: Maximum number of tokens to generate
Returns:
str: The generated story
"""
try:
response = client.responses.create(
model="gpt-4.1",
input=f"Write a creative story based on this prompt: {prompt}",
max_tokens=max_tokens,
temperature=0.8
)
return response.output_text
except Exception as e:
return f"Error generating story: {str(e)}"
def analyze_sentiment(texts: List[str]) -> List[Dict[str, str]]:
"""
Analyze sentiment of multiple texts using OpenAI.
Args:
texts: List of texts to analyze
Returns:
List of sentiment analysis results
"""
results = []
for text in texts:
try:
response = client.responses.create(
model="gpt-4.1",
input=f"Analyze the sentiment of this text and respond with only one word: POSITIVE, NEGATIVE, or NEUTRAL\n\nText: {text}",
max_tokens=10,
temperature=0
)
sentiment = response.output_text.strip()
results.append({"text": text[:50] + "...", "sentiment": sentiment})
except Exception as e:
results.append({"text": text[:50] + "...", "error": str(e)})
return results
def use_web_search(query: str) -> str:
"""
Example of using OpenAI's web search tool.
Args:
query: The search query
Returns:
str: The search results
"""
try:
response = client.responses.create(
model="gpt-4.1",
tools=[{"type": "web_search_preview"}],
input=query
)
return response.output_text
except Exception as e:
return f"Error with web search: {str(e)}"
async def stream_response(prompt: str):
"""
Stream a response from OpenAI.
Args:
prompt: The prompt to generate from
"""
try:
stream = client.responses.create(
model="gpt-4.1",
input=[{"role": "user", "content": prompt}],
stream=True
)
full_response = ""
for event in stream:
if hasattr(event, 'output_text'):
chunk = event.output_text
full_response += chunk
print(chunk, end='', flush=True)
return full_response
except Exception as e:
return f"Error streaming: {str(e)}"
def analyze_image(image_url: str, question: str) -> str:
"""
Analyze an image using OpenAI's vision capabilities.
Args:
image_url: URL of the image to analyze
question: Question about the image
Returns:
str: Analysis result
"""
try:
response = client.responses.create(
model="gpt-4.1",
input=[
{"role": "user", "content": question},
{
"role": "user",
"content": [
{
"type": "input_image",
"image_url": image_url
}
]
}
]
)
return response.output_text
except Exception as e:
return f"Error analyzing image: {str(e)}"
if __name__ == "__main__":
# Example usage
print("1. Story Generation:")
story = generate_story("A robot discovers emotions for the first time")
print(story[:200] + "...\n")
print("2. Sentiment Analysis:")
sentiments = analyze_sentiment([
"This product exceeded all my expectations!",
"The service was terrible and slow.",
"The weather today is cloudy."
])
for result in sentiments:
print(f" - {result}\n")
print("3. Web Search Example:")
search_result = use_web_search("What are the latest AI breakthroughs in 2024?")
print(search_result[:200] + "...\n")
print("4. Streaming Example:")
print("Streaming response: ")
asyncio.run(stream_response("Tell me a joke about programming"))
print("\n")
print("5. Image Analysis:")
image_result = analyze_image(
"https://upload.wikimedia.org/wikipedia/commons/thumb/0/0c/GoldenGateBridge-001.jpg/1200px-GoldenGateBridge-001.jpg",
"What landmark is shown in this image?"
)
print(image_result)