Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -1,31 +1,63 @@
|
|
1 |
-
|
|
|
|
|
|
|
|
|
|
|
2 |
|
3 |
-
|
4 |
-
|
5 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
6 |
fillable_mobile=True,
|
7 |
)
|
8 |
|
9 |
-
#
|
10 |
-
|
11 |
-
""
|
12 |
-
|
13 |
-
|
14 |
-
|
15 |
-
|
|
|
|
|
|
|
16 |
)
|
17 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
18 |
|
19 |
-
def server(input, output, session):
|
20 |
-
chat = ui.Chat(id="chat", messages=[welcome])
|
21 |
|
22 |
-
|
23 |
-
|
24 |
-
|
25 |
-
|
26 |
-
|
27 |
-
|
28 |
-
|
|
|
|
|
29 |
|
30 |
|
31 |
app = App(app_ui, server)
|
|
|
1 |
+
# ------------------------------------------------------------------------------------
|
2 |
+
# A simple recipe extractor chatbot that extracts recipes from URLs using the OpenAI API.
|
3 |
+
# To run it, you'll need an OpenAI API key.
|
4 |
+
# To get one, follow the instructions at https://platform.openai.com/docs/quickstart
|
5 |
+
# ------------------------------------------------------------------------------------
|
6 |
+
import os
|
7 |
|
8 |
+
from openai import AsyncOpenAI
|
9 |
+
from utils import recipe_prompt, scrape_page_with_url
|
10 |
+
|
11 |
+
from shiny.express import ui
|
12 |
+
|
13 |
+
# Provide your API key here (or set the environment variable)
|
14 |
+
llm = AsyncOpenAI(api_key=os.environ.get("OPENAI_API_KEY"))
|
15 |
+
|
16 |
+
# Set some Shiny page options
|
17 |
+
ui.page_opts(
|
18 |
+
title="Recipe Extractor Chat",
|
19 |
+
fillable=True,
|
20 |
fillable_mobile=True,
|
21 |
)
|
22 |
|
23 |
+
# Initialize the chat (with a system prompt and starting message)
|
24 |
+
chat = ui.Chat(
|
25 |
+
id="chat",
|
26 |
+
messages=[
|
27 |
+
{"role": "system", "content": recipe_prompt},
|
28 |
+
{
|
29 |
+
"role": "assistant",
|
30 |
+
"content": "Hello! I'm a recipe extractor. Please enter a URL to a recipe page. For example, <https://www.thechunkychef.com/epic-dry-rubbed-baked-chicken-wings/>",
|
31 |
+
},
|
32 |
+
],
|
33 |
)
|
34 |
|
35 |
+
chat.ui(placeholder="Enter a recipe URL...")
|
36 |
+
|
37 |
+
|
38 |
+
# A function to transform user input
|
39 |
+
# Note that, if an exception occurs, the function will return a message to the user
|
40 |
+
# "short-circuiting" the conversation and asking the user to try again.
|
41 |
+
@chat.transform_user_input
|
42 |
+
async def try_scrape_page(input: str) -> str | None:
|
43 |
+
try:
|
44 |
+
return await scrape_page_with_url(input)
|
45 |
+
except Exception:
|
46 |
+
await chat.append_message(
|
47 |
+
"I'm sorry, I couldn't extract content from that URL. Please try again. "
|
48 |
+
)
|
49 |
+
return None
|
50 |
|
|
|
|
|
51 |
|
52 |
+
@chat.on_user_submit
|
53 |
+
async def _():
|
54 |
+
response = await llm.chat.completions.create(
|
55 |
+
model="gpt-4o",
|
56 |
+
messages=chat.messages(format="openai"),
|
57 |
+
temperature=0,
|
58 |
+
stream=True,
|
59 |
+
)
|
60 |
+
await chat.append_message_stream(response)
|
61 |
|
62 |
|
63 |
app = App(app_ui, server)
|