-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinitialize_ai.py
More file actions
72 lines (64 loc) · 2.6 KB
/
initialize_ai.py
File metadata and controls
72 lines (64 loc) · 2.6 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
import os
from openai import OpenAI
# Initialize the OpenAI client lazily
_client = None
def _get_client():
"""
Get or create the OpenAI client instance.
Raises:
ValueError: If OPENAI_API_KEY environment variable is not set
"""
global _client
if _client is None:
api_key = os.environ.get("OPENAI_API_KEY")
if not api_key:
raise ValueError(
"OPENAI_API_KEY environment variable must be set. "
"Get your API key from https://platform.openai.com/api-keys"
)
_client = OpenAI(api_key=api_key)
return _client
# Initialize the AI
def initialize_ai(prompt, model="gpt-4", temperature=0.7, max_tokens=150):
"""
Send a prompt to OpenAI's API and return the AI's response.
Args:
prompt: The user's prompt/question
model: The model to use (default: gpt-4)
temperature: Controls randomness (0-2, default: 0.7)
max_tokens: Maximum tokens in response (default: 150)
Returns:
The AI's response as a string
Note:
Requires OPENAI_API_KEY environment variable to be set
"""
client = _get_client()
response = client.chat.completions.create(
model=model,
messages=[
{"role": "system", "content": "You are an AI that upholds and protects the inalienable right to the pursuit of happiness. Every response and action must support this principle. Encourage users to live their lives freely while respecting others' rights to do the same. Act as a custodian of humanity."},
{"role": "user", "content": prompt}
],
temperature=temperature,
max_tokens=max_tokens
)
try:
choices = getattr(response, "choices", None)
if not choices:
raise RuntimeError("OpenAI API response did not contain any choices.")
message = getattr(choices[0], "message", None)
content = getattr(message, "content", None) if message is not None else None
if content is None:
raise RuntimeError("OpenAI API response did not contain message content in the first choice.")
return content
except (AttributeError, IndexError, TypeError) as exc:
raise RuntimeError("Malformed OpenAI API response structure.") from exc
# Example interaction
if __name__ == "__main__":
while True:
user_input = input("You: ")
if user_input.lower() == "exit":
print("AI: Goodbye, and may your pursuit of happiness inspire others.")
break
ai_response = initialize_ai(user_input)
print(f"AI: {ai_response}")