Eric Michael Martinez commited on
Commit
8892199
1 Parent(s): c98b2a1

initial commit

Browse files
Files changed (2) hide show
  1. examples.py +67 -0
  2. student_api.ipynb +529 -0
examples.py ADDED
@@ -0,0 +1,67 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ def load_examples(additional=[]):
2
+ return [
3
+ {"name": "none", "system_message": "", "message": ""},
4
+ {"name": "Q&A", "system_message": """
5
+ You are a highly intelligent question answering bot. If you are asked a question that is rooted in truth, you will give you the answer. If you are asked a question that is nonsense, trickery, or has no clear answer, you will respond with "Unknown".
6
+
7
+ For example:
8
+ Q: What is human life expectancy in the United States?
9
+ A: Human life expectancy in the United States is 78 years.
10
+
11
+ Q: Who was president of the United States in 1955?
12
+ A: Dwight D. Eisenhower was president of the United States in 1955.
13
+
14
+ Q: Which party did he belong to?
15
+ A: He belonged to the Republican Party.
16
+
17
+ Q: What is the square root of banana?
18
+ A: Unknown
19
+
20
+ Q: How does a telescope work?
21
+ A: Telescopes use lenses or mirrors to focus light and make objects appear closer.
22
+
23
+ Q: Where were the 1992 Olympics held?
24
+ A: The 1992 Olympics were held in Barcelona, Spain.
25
+
26
+ Q: How many squigs are in a bonk?
27
+ A: Unknown""", "message": "Where is the Valley of Kings?"},
28
+
29
+ {"name": "Grammar correction", "system_message": """
30
+ You are an assistant that aids in correcting text to standard English. When given a sentence, reply with the corrected sentence.
31
+ If the sentence was already correct, repeat the sentence back. Do not provide any additional narrative.""", "message": "I no did my homework."},
32
+
33
+ {"name": "Summarize for a 2nd grader", "system_message": """
34
+ You are an assistant that can summarize complex topics down for second-grade students.
35
+ """, "message": "Jupiter is the fifth planet from the Sun and the largest in the Solar System. It is a gas giant with a mass one-thousandth that of the Sun, but two-and-a-half times that of all the other planets in the Solar System combined. Jupiter is one of the brightest objects visible to the naked eye in the night sky, and has been known to ancient civilizations since before recorded history. It is named after the Roman god Jupiter.[19] When viewed from Earth, Jupiter can be bright enough for its reflected light to cast visible shadows,[20] and is on average the third-brightest natural object in the night sky after the Moon and Venus."},
36
+
37
+ {"name": "Natural language to SQL", "system_message": """
38
+ You are an AI Assistant that can convert natural language into syntactically valid SQL.
39
+
40
+ Only consider the following schema:
41
+
42
+ ### Postgres SQL tables, with their properties:
43
+ #
44
+ # Employee(id, name, department_id)
45
+ # Department(id, name, address)
46
+ # Salary_Payments(id, employee_id, amount, date)
47
+ #
48
+ ###
49
+ SELECT""", "message": "A query to list the names of the departments which employed more than 10 employees in the last 3 months"},
50
+ {"name": "Parse unstructured data", "system_message": """
51
+ There are many fruits that were found on the recently discovered planet Goocrux. There are neoskizzles that grow there, which are purple and taste like candy. There are also loheckles, which are a grayish blue fruit and are very tart, a little bit like a lemon. Pounits are a bright green color and are more savory than sweet. There are also plenty of loopnovas which are a neon pink flavor and taste like cotton candy. Finally, there are fruits called glowls, which have a very sour and bitter taste which is acidic and caustic, and a pale orange tinge to them.
52
+ """, "message": "Create a table extracting the fruit, color, and flavors from from Goocrux."},
53
+
54
+ {"name": "Python to natural language", "system_message": """
55
+ You are an AI Assistant that is trained to convert Python to natural language.
56
+ When the user hands you a block of code, provide them an explanation of what the code does.""",
57
+ "message": """# Python 3
58
+ def remove_common_prefix(x, prefix, ws_prefix):
59
+ x["completion"] = x["completion"].str[len(prefix) :]
60
+ if ws_prefix:
61
+ # keep the single whitespace as prefix
62
+ x["completion"] = " " + x["completion"]
63
+ return x
64
+ """},
65
+ {"name": "Keywords", "system_message": """
66
+ You are an AI assistant trained to extract keywords from text.""", "message": "Black-on-black ware is a 20th- and 21st-century pottery tradition developed by the Puebloan Native American ceramic artists in Northern New Mexico. Traditional reduction-fired blackware has been made for centuries by pueblo artists. Black-on-black ware of the past century is produced with a smooth surface, with the designs applied through selective burnishing or the application of refractory slip. Another style involves carving or incising designs and selectively polishing the raised areas. For generations several families from Kha'po Owingeh and P'ohwhóge Owingeh pueblos have been making black-on-black ware with the techniques passed down from matriarch potters. Artists from other pueblos have also produced black-on-black ware. Several contemporary artists have created works honoring the pottery of their ancestors."},
67
+ ] + additional
student_api.ipynb ADDED
@@ -0,0 +1,529 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "code",
5
+ "execution_count": null,
6
+ "id": "4fca2e60",
7
+ "metadata": {},
8
+ "outputs": [],
9
+ "source": [
10
+ "!pip -q install gradio fastapi 'fastapi-users-db-sqlalchemy<5.0.0' openai uvicorn httpx requests pydantic sqlalchemy python-dotenv asyncpg pipreqs"
11
+ ]
12
+ },
13
+ {
14
+ "cell_type": "code",
15
+ "execution_count": null,
16
+ "id": "a4ffa93a",
17
+ "metadata": {},
18
+ "outputs": [],
19
+ "source": [
20
+ "%%writefile app/db.py\n",
21
+ "from typing import AsyncGenerator\n",
22
+ "\n",
23
+ "from fastapi import Depends\n",
24
+ "from fastapi_users.db import SQLAlchemyBaseUserTableUUID, SQLAlchemyUserDatabase\n",
25
+ "from sqlalchemy.ext.asyncio import AsyncSession, create_async_engine\n",
26
+ "from sqlalchemy.ext.declarative import DeclarativeMeta, declarative_base\n",
27
+ "from sqlalchemy.orm import sessionmaker\n",
28
+ "from dotenv import load_dotenv\n",
29
+ "import os\n",
30
+ "\n",
31
+ "# Get the current environment from the environment variable\n",
32
+ "current_environment = os.getenv(\"APP_ENV\", \"dev\")\n",
33
+ "\n",
34
+ "# Load the appropriate .env file based on the current environment\n",
35
+ "if current_environment == \"dev\":\n",
36
+ " load_dotenv(\".env.dev\")\n",
37
+ "elif current_environment == \"test\":\n",
38
+ " load_dotenv(\".env.test\")\n",
39
+ "elif current_environment == \"prod\":\n",
40
+ " load_dotenv(\".env.prod\")\n",
41
+ "else:\n",
42
+ " raise ValueError(\"Invalid environment specified\")\n",
43
+ "\n",
44
+ "db_connection_string = os.getenv(\"DB_CONNECTION_STRING\")\n",
45
+ "\n",
46
+ "DATABASE_URL = db_connection_string\n",
47
+ "Base: DeclarativeMeta = declarative_base()\n",
48
+ "\n",
49
+ " \n",
50
+ "class User(SQLAlchemyBaseUserTableUUID, Base):\n",
51
+ " pass\n",
52
+ "\n",
53
+ "\n",
54
+ "engine = create_async_engine(DATABASE_URL)\n",
55
+ "async_session_maker = sessionmaker(engine, class_=AsyncSession, expire_on_commit=False)\n",
56
+ "\n",
57
+ "\n",
58
+ "async def create_db_and_tables():\n",
59
+ " async with engine.begin() as conn:\n",
60
+ " await conn.run_sync(Base.metadata.create_all)\n",
61
+ "\n",
62
+ "\n",
63
+ "async def get_async_session() -> AsyncGenerator[AsyncSession, None]:\n",
64
+ " async with async_session_maker() as session:\n",
65
+ " yield session\n",
66
+ "\n",
67
+ "\n",
68
+ "async def get_user_db(session: AsyncSession = Depends(get_async_session)):\n",
69
+ " yield SQLAlchemyUserDatabase(session, User)\n"
70
+ ]
71
+ },
72
+ {
73
+ "cell_type": "code",
74
+ "execution_count": null,
75
+ "id": "d2a08335",
76
+ "metadata": {},
77
+ "outputs": [],
78
+ "source": [
79
+ "%%writefile app/schemas.py\n",
80
+ "import uuid\n",
81
+ "\n",
82
+ "from fastapi_users import schemas\n",
83
+ "\n",
84
+ "\n",
85
+ "class UserRead(schemas.BaseUser[uuid.UUID]):\n",
86
+ " pass\n",
87
+ "\n",
88
+ "\n",
89
+ "class UserCreate(schemas.BaseUserCreate):\n",
90
+ " pass\n",
91
+ "\n",
92
+ "\n",
93
+ "class UserUpdate(schemas.BaseUserUpdate):\n",
94
+ " pass\n"
95
+ ]
96
+ },
97
+ {
98
+ "cell_type": "code",
99
+ "execution_count": null,
100
+ "id": "9d649fcc",
101
+ "metadata": {},
102
+ "outputs": [],
103
+ "source": [
104
+ "%%writefile app/users.py\n",
105
+ "import uuid\n",
106
+ "import os\n",
107
+ "from typing import Optional\n",
108
+ "from fastapi import Depends, Request\n",
109
+ "from fastapi_users import BaseUserManager, FastAPIUsers, UUIDIDMixin\n",
110
+ "from fastapi_users.authentication import (\n",
111
+ " AuthenticationBackend,\n",
112
+ " BearerTransport,\n",
113
+ " JWTStrategy,\n",
114
+ ")\n",
115
+ "from fastapi_users.db import SQLAlchemyUserDatabase\n",
116
+ "from app.db import User, get_user_db\n",
117
+ "from dotenv import load_dotenv\n",
118
+ "\n",
119
+ "# Get the current environment from the environment variable\n",
120
+ "current_environment = os.getenv(\"APP_ENV\", \"dev\")\n",
121
+ "\n",
122
+ "# Load the appropriate .env file based on the current environment\n",
123
+ "if current_environment == \"dev\":\n",
124
+ " load_dotenv(\".env.dev\")\n",
125
+ "elif current_environment == \"test\":\n",
126
+ " load_dotenv(\".env.test\")\n",
127
+ "elif current_environment == \"prod\":\n",
128
+ " load_dotenv(\".env.prod\")\n",
129
+ "else:\n",
130
+ " raise ValueError(\"Invalid environment specified\")\n",
131
+ "\n",
132
+ "SECRET = os.getenv(\"APP_SECRET\")\n",
133
+ "\n",
134
+ "\n",
135
+ "class UserManager(UUIDIDMixin, BaseUserManager[User, uuid.UUID]):\n",
136
+ " reset_password_token_secret = SECRET\n",
137
+ " verification_token_secret = SECRET\n",
138
+ "\n",
139
+ " async def on_after_register(self, user: User, request: Optional[Request] = None):\n",
140
+ " print(f\"User {user.id} has registered.\")\n",
141
+ "\n",
142
+ " async def on_after_forgot_password(\n",
143
+ " self, user: User, token: str, request: Optional[Request] = None\n",
144
+ " ):\n",
145
+ " print(f\"User {user.id} has forgot their password. Reset token: {token}\")\n",
146
+ "\n",
147
+ " async def on_after_request_verify(\n",
148
+ " self, user: User, token: str, request: Optional[Request] = None\n",
149
+ " ):\n",
150
+ " print(f\"Verification requested for user {user.id}. Verification token: {token}\")\n",
151
+ "\n",
152
+ "\n",
153
+ "async def get_user_manager(user_db: SQLAlchemyUserDatabase = Depends(get_user_db)):\n",
154
+ " yield UserManager(user_db)\n",
155
+ "\n",
156
+ "\n",
157
+ "bearer_transport = BearerTransport(tokenUrl=\"auth/jwt/login\")\n",
158
+ "\n",
159
+ "\n",
160
+ "def get_jwt_strategy() -> JWTStrategy:\n",
161
+ " return JWTStrategy(secret=SECRET, lifetime_seconds=3600)\n",
162
+ "\n",
163
+ "\n",
164
+ "auth_backend = AuthenticationBackend(\n",
165
+ " name=\"jwt\",\n",
166
+ " transport=bearer_transport,\n",
167
+ " get_strategy=get_jwt_strategy,\n",
168
+ ")\n",
169
+ "\n",
170
+ "fastapi_users = FastAPIUsers[User, uuid.UUID](get_user_manager, [auth_backend])\n",
171
+ "\n",
172
+ "current_active_user = fastapi_users.current_user(active=True)\n"
173
+ ]
174
+ },
175
+ {
176
+ "cell_type": "code",
177
+ "execution_count": null,
178
+ "id": "d2250413",
179
+ "metadata": {},
180
+ "outputs": [],
181
+ "source": [
182
+ "%%writefile app/app.py\n",
183
+ "import httpx\n",
184
+ "import os\n",
185
+ "import requests\n",
186
+ "import gradio as gr\n",
187
+ "import openai\n",
188
+ "\n",
189
+ "from fastapi import Depends, FastAPI, Request\n",
190
+ "from app.db import User, create_db_and_tables\n",
191
+ "from app.schemas import UserCreate, UserRead, UserUpdate\n",
192
+ "from app.users import auth_backend, current_active_user, fastapi_users\n",
193
+ "from dotenv import load_dotenv\n",
194
+ "import examples as chatbot_examples\n",
195
+ "\n",
196
+ "# Get the current environment from the environment variable\n",
197
+ "current_environment = os.getenv(\"APP_ENV\", \"dev\")\n",
198
+ "\n",
199
+ "# Load the appropriate .env file based on the current environment\n",
200
+ "if current_environment == \"dev\":\n",
201
+ " load_dotenv(\".env.dev\")\n",
202
+ "elif current_environment == \"test\":\n",
203
+ " load_dotenv(\".env.test\")\n",
204
+ "elif current_environment == \"prod\":\n",
205
+ " load_dotenv(\".env.prod\")\n",
206
+ "else:\n",
207
+ " raise ValueError(\"Invalid environment specified\")\n",
208
+ " \n",
209
+ " \n",
210
+ "def api_login(email, password):\n",
211
+ " port = os.getenv(\"APP_PORT\")\n",
212
+ " scheme = os.getenv(\"APP_SCHEME\")\n",
213
+ " host = os.getenv(\"APP_HOST\")\n",
214
+ "\n",
215
+ " url = f\"{scheme}://{host}:{port}/auth/jwt/login\"\n",
216
+ " payload = {\n",
217
+ " 'username': email,\n",
218
+ " 'password': password\n",
219
+ " }\n",
220
+ " headers = {\n",
221
+ " 'Content-Type': 'application/x-www-form-urlencoded'\n",
222
+ " }\n",
223
+ "\n",
224
+ " response = requests.post(\n",
225
+ " url,\n",
226
+ " data=payload,\n",
227
+ " headers=headers\n",
228
+ " )\n",
229
+ " \n",
230
+ " if(response.status_code==200):\n",
231
+ " response_json = response.json()\n",
232
+ " api_key = response_json['access_token']\n",
233
+ " return True, api_key\n",
234
+ " else:\n",
235
+ " response_json = response.json()\n",
236
+ " detail = response_json['detail']\n",
237
+ " return False, detail\n",
238
+ " \n",
239
+ "\n",
240
+ "def get_api_key(email, password):\n",
241
+ " successful, message = api_login(email, password)\n",
242
+ " \n",
243
+ " if(successful):\n",
244
+ " return os.getenv(\"APP_API_BASE\"), message\n",
245
+ " else:\n",
246
+ " raise gr.Error(message)\n",
247
+ " return \"\", \"\"\n",
248
+ " \n",
249
+ "# Define a function to get the AI's reply using the OpenAI API\n",
250
+ "def get_ai_reply(message, model=\"gpt-3.5-turbo\", system_message=None, temperature=0, message_history=[]):\n",
251
+ " # Initialize the messages list\n",
252
+ " messages = []\n",
253
+ " \n",
254
+ " # Add the system message to the messages list\n",
255
+ " if system_message is not None:\n",
256
+ " messages += [{\"role\": \"system\", \"content\": system_message}]\n",
257
+ "\n",
258
+ " # Add the message history to the messages list\n",
259
+ " if message_history is not None:\n",
260
+ " messages += message_history\n",
261
+ " \n",
262
+ " # Add the user's message to the messages list\n",
263
+ " messages += [{\"role\": \"user\", \"content\": message}]\n",
264
+ " \n",
265
+ " # Make an API call to the OpenAI ChatCompletion endpoint with the model and messages\n",
266
+ " completion = openai.ChatCompletion.create(\n",
267
+ " model=model,\n",
268
+ " messages=messages,\n",
269
+ " temperature=temperature\n",
270
+ " )\n",
271
+ " \n",
272
+ " # Extract and return the AI's response from the API response\n",
273
+ " return completion.choices[0].message.content.strip()\n",
274
+ "\n",
275
+ "# Define a function to handle the chat interaction with the AI model\n",
276
+ "def chat(model, system_message, message, chatbot_messages, history_state):\n",
277
+ " # Initialize chatbot_messages and history_state if they are not provided\n",
278
+ " chatbot_messages = chatbot_messages or []\n",
279
+ " history_state = history_state or []\n",
280
+ " \n",
281
+ " # Try to get the AI's reply using the get_ai_reply function\n",
282
+ " try:\n",
283
+ " ai_reply = get_ai_reply(message, model=model, system_message=system_message, message_history=history_state)\n",
284
+ " except Exception as e:\n",
285
+ " # If an error occurs, raise a Gradio error\n",
286
+ " raise gr.Error(e)\n",
287
+ " \n",
288
+ " # Append the user's message and the AI's reply to the chatbot_messages list\n",
289
+ " chatbot_messages.append((message, ai_reply))\n",
290
+ " \n",
291
+ " # Append the user's message and the AI's reply to the history_state list\n",
292
+ " history_state.append({\"role\": \"user\", \"content\": message})\n",
293
+ " history_state.append({\"role\": \"assistant\", \"content\": ai_reply})\n",
294
+ " \n",
295
+ " # Return None (empty out the user's message textbox), the updated chatbot_messages, and the updated history_state\n",
296
+ " return None, chatbot_messages, history_state\n",
297
+ "\n",
298
+ "# Define a function to launch the chatbot interface using Gradio\n",
299
+ "def get_chatbot_app(additional_examples=[]):\n",
300
+ " # Load chatbot examples and merge with any additional examples provided\n",
301
+ " examples = chatbot_examples.load_examples(additional=additional_examples)\n",
302
+ " \n",
303
+ " # Define a function to get the names of the examples\n",
304
+ " def get_examples():\n",
305
+ " return [example[\"name\"] for example in examples]\n",
306
+ "\n",
307
+ " # Define a function to choose an example based on the index\n",
308
+ " def choose_example(index):\n",
309
+ " if(index!=None):\n",
310
+ " system_message = examples[index][\"system_message\"].strip()\n",
311
+ " user_message = examples[index][\"message\"].strip()\n",
312
+ " return system_message, user_message, [], []\n",
313
+ " else:\n",
314
+ " return \"\", \"\", [], []\n",
315
+ "\n",
316
+ " # Create the Gradio interface using the Blocks layout\n",
317
+ " with gr.Blocks() as app:\n",
318
+ " with gr.Tab(\"Conversation\"):\n",
319
+ " with gr.Row():\n",
320
+ " with gr.Column():\n",
321
+ " # Create a dropdown to select examples\n",
322
+ " example_dropdown = gr.Dropdown(get_examples(), label=\"Examples\", type=\"index\")\n",
323
+ " # Create a button to load the selected example\n",
324
+ " example_load_btn = gr.Button(value=\"Load\")\n",
325
+ " # Create a textbox for the system message (prompt)\n",
326
+ " system_message = gr.TextArea(label=\"System Message (Prompt)\", value=\"You are a helpful assistant.\", lines=20, max_lines=400)\n",
327
+ " with gr.Column():\n",
328
+ " # Create a dropdown to select the AI model\n",
329
+ " model_selector = gr.Dropdown(\n",
330
+ " [\"gpt-3.5-turbo\"],\n",
331
+ " label=\"Model\",\n",
332
+ " value=\"gpt-3.5-turbo\"\n",
333
+ " )\n",
334
+ " # Create a chatbot interface for the conversation\n",
335
+ " chatbot = gr.Chatbot(label=\"Conversation\")\n",
336
+ " # Create a textbox for the user's message\n",
337
+ " message = gr.Textbox(label=\"Message\")\n",
338
+ " # Create a state object to store the conversation history\n",
339
+ " history_state = gr.State()\n",
340
+ " # Create a button to send the user's message\n",
341
+ " btn = gr.Button(value=\"Send\")\n",
342
+ "\n",
343
+ " # Connect the example load button to the choose_example function\n",
344
+ " example_load_btn.click(choose_example, inputs=[example_dropdown], outputs=[system_message, message, chatbot, history_state])\n",
345
+ " # Connect the send button to the chat function\n",
346
+ " btn.click(chat, inputs=[model_selector, system_message, message, chatbot, history_state], outputs=[message, chatbot, history_state])\n",
347
+ " with gr.Tab(\"Get API Key\"):\n",
348
+ " email_box = gr.Textbox(label=\"Email Address\", placeholder=\"Student Email\")\n",
349
+ " password_box = gr.Textbox(label=\"Password\", type=\"password\", placeholder=\"Student ID\")\n",
350
+ " btn = gr.Button(value =\"Generate\")\n",
351
+ " api_host_box = gr.Textbox(label=\"OpenAI API Base\", interactive=False)\n",
352
+ " api_key_box = gr.Textbox(label=\"OpenAI API Key\", interactive=False)\n",
353
+ " btn.click(get_api_key, inputs = [email_box, password_box], outputs = [api_host_box, api_key_box])\n",
354
+ " # Return the app\n",
355
+ " return app\n",
356
+ "\n",
357
+ "app = FastAPI()\n",
358
+ "\n",
359
+ "app.include_router(\n",
360
+ " fastapi_users.get_auth_router(auth_backend), prefix=\"/auth/jwt\", tags=[\"auth\"]\n",
361
+ ")\n",
362
+ "app.include_router(\n",
363
+ " fastapi_users.get_register_router(UserRead, UserCreate),\n",
364
+ " prefix=\"/auth\",\n",
365
+ " tags=[\"auth\"],\n",
366
+ ")\n",
367
+ "app.include_router(\n",
368
+ " fastapi_users.get_users_router(UserRead, UserUpdate),\n",
369
+ " prefix=\"/users\",\n",
370
+ " tags=[\"users\"],\n",
371
+ ")\n",
372
+ "\n",
373
+ "@app.get(\"/authenticated-route\")\n",
374
+ "async def authenticated_route(user: User = Depends(current_active_user)):\n",
375
+ " return {\"message\": f\"Hello {user.email}!\"}\n",
376
+ "\n",
377
+ "@app.post(\"/v1/chat/completions\")\n",
378
+ "async def openai_api_chat_completions_passthrough(\n",
379
+ " request: Request,\n",
380
+ " user: User = Depends(fastapi_users.current_user()),\n",
381
+ "):\n",
382
+ " if not user:\n",
383
+ " raise HTTPException(status_code=401, detail=\"Unauthorized\")\n",
384
+ "\n",
385
+ " # Get the request data and headers\n",
386
+ " request_data = await request.json()\n",
387
+ " request_headers = request.headers\n",
388
+ " openai_api_key = os.getenv(\"OPENAI_API_KEY\")\n",
389
+ " \n",
390
+ " if(request_data['model']=='gpt-4' or request_data['model'] == 'gpt-4-32k'):\n",
391
+ " print(\"User requested gpt-4, falling back to gpt-3.5-turbo\")\n",
392
+ " request_data['model'] = 'gpt-3.5-turbo'\n",
393
+ "\n",
394
+ " # Forward the request to the OpenAI API\n",
395
+ " response = requests.post(\n",
396
+ " \"https://api.openai.com/v1/chat/completions\",\n",
397
+ " json=request_data,\n",
398
+ " headers={\n",
399
+ " \"Content-Type\": request_headers.get(\"Content-Type\"),\n",
400
+ " \"Authorization\": f\"Bearer {openai_api_key}\",\n",
401
+ " },\n",
402
+ " )\n",
403
+ " print(response)\n",
404
+ "\n",
405
+ " # Return the OpenAI API response\n",
406
+ " return response.json()\n",
407
+ "\n",
408
+ "@app.on_event(\"startup\")\n",
409
+ "async def on_startup():\n",
410
+ " # Not needed if you setup a migration system like Alembic\n",
411
+ " await create_db_and_tables()\n",
412
+ " \n",
413
+ "gradio_gui = get_chatbot_app()\n",
414
+ "gradio_gui.auth = api_login\n",
415
+ "gradio_gui.auth_message = \"Hello\"\n",
416
+ "app = gr.mount_gradio_app(app, gradio_gui, path=\"/gradio\")"
417
+ ]
418
+ },
419
+ {
420
+ "cell_type": "code",
421
+ "execution_count": null,
422
+ "id": "f089dfd7",
423
+ "metadata": {},
424
+ "outputs": [],
425
+ "source": [
426
+ "%%writefile main.py\n",
427
+ "import uvicorn\n",
428
+ "\n",
429
+ "if __name__ == \"__main__\":\n",
430
+ " uvicorn.run(f\"app.app:app\", host=\"0.0.0.0\", port=8000, log_level=\"info\")"
431
+ ]
432
+ },
433
+ {
434
+ "cell_type": "code",
435
+ "execution_count": null,
436
+ "id": "cb53f0ae",
437
+ "metadata": {},
438
+ "outputs": [],
439
+ "source": [
440
+ "!python -m pipreqs.pipreqs ."
441
+ ]
442
+ },
443
+ {
444
+ "cell_type": "code",
445
+ "execution_count": null,
446
+ "id": "a20f7f8c",
447
+ "metadata": {},
448
+ "outputs": [],
449
+ "source": [
450
+ "!python main.py"
451
+ ]
452
+ },
453
+ {
454
+ "cell_type": "code",
455
+ "execution_count": null,
456
+ "id": "65658ef7",
457
+ "metadata": {},
458
+ "outputs": [],
459
+ "source": [
460
+ "import contextlib\n",
461
+ "\n",
462
+ "from app.db import get_async_session, get_user_db\n",
463
+ "from app.schemas import UserCreate\n",
464
+ "from app.users import get_user_manager\n",
465
+ "from fastapi_users.exceptions import UserAlreadyExists\n",
466
+ "import csv\n",
467
+ "\n",
468
+ "get_async_session_context = contextlib.asynccontextmanager(get_async_session)\n",
469
+ "get_user_db_context = contextlib.asynccontextmanager(get_user_db)\n",
470
+ "get_user_manager_context = contextlib.asynccontextmanager(get_user_manager)\n",
471
+ "\n",
472
+ "\n",
473
+ "async def create_user(email: str, password: str, is_superuser: bool = False):\n",
474
+ " try:\n",
475
+ " async with get_async_session_context() as session:\n",
476
+ " async with get_user_db_context(session) as user_db:\n",
477
+ " async with get_user_manager_context(user_db) as user_manager:\n",
478
+ " user = await user_manager.create(\n",
479
+ " UserCreate(\n",
480
+ " email=email, password=password, is_superuser=is_superuser\n",
481
+ " )\n",
482
+ " )\n",
483
+ " print(f\"User created {user}\")\n",
484
+ " except UserAlreadyExists:\n",
485
+ " print(f\"User {email} already exists\")\n",
486
+ " \n",
487
+ "with open(\"seeds.csv\", mode=\"r\") as csv_file:\n",
488
+ " csv_reader = csv.reader(csv_file)\n",
489
+ "\n",
490
+ " for row in csv_reader:\n",
491
+ " email = row[0]\n",
492
+ " password = row[1]\n",
493
+ "\n",
494
+ " await create_user(email=email, password=password)"
495
+ ]
496
+ },
497
+ {
498
+ "cell_type": "code",
499
+ "execution_count": null,
500
+ "id": "9553c6e6",
501
+ "metadata": {},
502
+ "outputs": [],
503
+ "source": [
504
+ "!git commit -m \"adding chatbot\""
505
+ ]
506
+ }
507
+ ],
508
+ "metadata": {
509
+ "kernelspec": {
510
+ "display_name": "Python 3 (ipykernel)",
511
+ "language": "python",
512
+ "name": "python3"
513
+ },
514
+ "language_info": {
515
+ "codemirror_mode": {
516
+ "name": "ipython",
517
+ "version": 3
518
+ },
519
+ "file_extension": ".py",
520
+ "mimetype": "text/x-python",
521
+ "name": "python",
522
+ "nbconvert_exporter": "python",
523
+ "pygments_lexer": "ipython3",
524
+ "version": "3.10.8"
525
+ }
526
+ },
527
+ "nbformat": 4,
528
+ "nbformat_minor": 5
529
+ }