Skip to content

Commit 8c9136f

Browse files
Auto-write assistant id to .env file and auto-switch between create or modify
1 parent 6579109 commit 8c9136f

File tree

2 files changed

+69
-22
lines changed

2 files changed

+69
-22
lines changed

.env.example

Lines changed: 2 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,2 @@
1-
# DO NOT COMMIT THIS FILE - IT WILL CONTAIN YOUR SENSITIVE KEYS.
2-
# Instead, rename this file to ".env" instead of ".env.example". (.env will not be committed)
3-
4-
# Create an OpenAI API key at https://platform.openai.com/account/api-keys
5-
OPENAI_API_KEY="sk-123..."
6-
7-
# (optional) Create an OpenAI Assistant at https://platform.openai.com/assistants.
8-
# IMPORTANT! Be sure to enable file search and code interpreter tools.
9-
OPENAI_ASSISTANT_ID="123..."
1+
OPENAI_API_KEY=
2+
ASSISTANT_ID=

create_assistant.py

Lines changed: 67 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,6 @@
1+
import os
2+
import sys
3+
import logging
14
import asyncio
25
from dotenv import load_dotenv
36
from openai import AsyncOpenAI
@@ -6,6 +9,11 @@
69
from openai.types.beta.assistant import Assistant
710
from openai.types import FunctionDefinition
811

12+
# Configure logger to stream to console
13+
logging.basicConfig(level=logging.INFO, stream=sys.stdout)
14+
logger: logging.Logger = logging.getLogger(__name__)
15+
16+
917
request: AssistantCreateParams = AssistantCreateParams(
1018
instructions="You are a helpful assistant.",
1119
name="Quickstart Assistant",
@@ -36,25 +44,71 @@
3644
)
3745

3846

39-
async def main():
40-
# Create a new assistant using the OpenAI client
41-
assistant: Assistant = await openai.beta.assistants.create(**request)
42-
return assistant
47+
def update_env_file(assistant_id, logger):
48+
"""
49+
Update the .env file with a new assistant ID.
50+
51+
If the .env file already contains an ASSISTANT_ID, it will be removed.
52+
The new assistant ID will be appended to the .env file. If the .env file
53+
does not exist, it will be created.
54+
"""
55+
if os.path.exists('.env'):
56+
with open('.env', 'r') as env_file:
57+
lines = env_file.readlines()
58+
59+
# Remove any existing ASSISTANT_ID line
60+
lines = [line for line in lines if not line.startswith("ASSISTANT_ID=")]
61+
62+
# Write back the modified lines
63+
with open('.env', 'w') as env_file:
64+
env_file.writelines(lines)
65+
66+
# Write the new assistant ID to the .env file
67+
with open('.env', 'a') as env_file:
68+
env_file.write(f"ASSISTANT_ID={assistant_id}\n")
69+
logger.info(f"Assistant ID written to .env: {assistant_id}")
70+
71+
72+
async def create_or_update_assistant(
73+
client: AsyncOpenAI,
74+
assistant_id: str,
75+
request: AssistantCreateParams,
76+
logger: logging.Logger
77+
):
78+
"""
79+
Create or update the assistant based on the presence of an assistant_id.
80+
"""
81+
try:
82+
if assistant_id:
83+
# Update the existing assistant
84+
assistant: Assistant = await client.beta.assistants.update(
85+
assistant_id,
86+
**request
87+
)
88+
logger.info(f"Updated assistant with ID: {assistant_id}")
89+
else:
90+
# Create a new assistant
91+
assistant: Assistant = await client.beta.assistants.create(**request)
92+
logger.info(f"Created new assistant: {assistant}")
93+
94+
# Update the .env file with the new assistant ID
95+
update_env_file(assistant.id, logger)
96+
97+
except Exception as e:
98+
action = "update" if assistant_id else "create"
99+
logger.error(f"Failed to {action} assistant: {e}")
43100

44101

45102
# Run the assistant creation in an asyncio event loop
46103
if __name__ == "__main__":
47-
import logging
48-
import sys
104+
load_dotenv()
105+
assistant_id = os.getenv("ASSISTANT_ID")
49106

50107
# Initialize the OpenAI client
51-
load_dotenv()
52108
openai: AsyncOpenAI = AsyncOpenAI()
53109

54-
# Configure logger to stream to console
55-
logging.basicConfig(level=logging.INFO, stream=sys.stdout)
56-
logger: logging.Logger = logging.getLogger(__name__)
57-
58110
# Run the main function in an asyncio event loop
59-
assistant: Assistant = asyncio.run(main())
60-
logger.info(f"Assistant created with ID: {assistant.id}")
111+
new_assistant_id: Assistant = asyncio.run(
112+
create_or_update_assistant(openai, assistant_id, request, logger)
113+
)
114+
logger.info(f"Assistant created with ID: {new_assistant_id}")

0 commit comments

Comments
 (0)