Merge pull request #324 from PraveenRepswal/main

Fix #255: Allow Chatbot template to run without OpenAI API key
This commit is contained in:
Mad Cow
2026-01-08 19:48:07 +01:00
committed by GitHub
3 changed files with 32 additions and 16 deletions

View File

@@ -27,7 +27,7 @@ class Conversation:
# The entire message history
messages: list[ChatMessage] = dataclasses.field(default_factory=list)
async def respond(self, client: openai.AsyncOpenAI) -> ChatMessage:
async def respond(self, client: openai.AsyncOpenAI | None) -> ChatMessage:
"""
Creates an AI generated response for this conversation and appends it
to the messages list. Also returns the new message.
@@ -56,18 +56,26 @@ class Conversation:
]
# Generate a response
api_response = await client.chat.completions.create(
model="gpt-3.5-turbo",
messages=api_messages,
max_tokens=500,
)
if client is None:
response_text = """
This template requires an OpenAI API key to work
assert isinstance(api_response.choices[0].message.content, str)
You can get your API key from https://platform.openai.com/api-keys
Make sure to enter your key into the `__init__.py` file before trying to run the project.
""".strip()
else:
api_response = await client.chat.completions.create(
model="gpt-3.5-turbo",
messages=api_messages,
max_tokens=500,
)
assert isinstance(api_response.choices[0].message.content, str)
response_text = api_response.choices[0].message.content
response = ChatMessage(
role="assistant",
timestamp=datetime.now(tz=timezone.utc),
text=api_response.choices[0].message.content,
text=response_text,
)
# Append the message and return it as well

View File

@@ -81,10 +81,15 @@ class ChatPage(rio.Component):
self.is_loading = True
self.force_refresh()
try:
openai_client = self.session[openai.AsyncOpenAI]
except KeyError:
openai_client = None
# Generate a response
try:
await self.conversation.respond(
client=self.session[openai.AsyncOpenAI],
client=openai_client,
)
# Don't get stuck in loading state if an error occurs

View File

@@ -14,20 +14,23 @@ OPENAI_API_KEY = "<placeholder>" # Replace this with your OpenAI API key
# yet. Feel free to delete this code if you've already replaced the key.
if OPENAI_API_KEY == "<placeholder>":
message = """
print(
"""
This template requires an OpenAI API key to work
You can get your API key from [OpenAI's website](https://platform.openai.com/api-keys
Make sure to enter your key into the `__init__.py` file before trying to run the project
You can get your API key from https://platform.openai.com/api-keys
Make sure to enter your key into the `__init__.py` file before trying to run the project.
""".strip()
print(message)
raise RuntimeError(message)
)
OPENAI_CLIENT = None
else:
OPENAI_CLIENT = openai.AsyncOpenAI(api_key=OPENAI_API_KEY)
def on_app_start(app: rio.App) -> None:
# Create the OpenAI client and attach it to the app
app.default_attachments.append(openai.AsyncOpenAI(api_key=OPENAI_API_KEY))
if OPENAI_CLIENT is not None:
app.default_attachments.append(OPENAI_CLIENT)
# </additional-code>