File size: 11,962 Bytes
7b70181
6e8003f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7b70181
 
6e8003f
 
 
 
 
 
7b70181
 
6e8003f
7b70181
 
 
6e8003f
7b70181
6e8003f
 
 
7b70181
6e8003f
7b70181
6e8003f
 
 
7b70181
 
6e8003f
 
 
 
7b70181
 
6e8003f
7b70181
 
 
 
 
 
 
6e8003f
 
7b70181
6e8003f
 
 
 
 
 
 
7b70181
6e8003f
 
7b70181
6e8003f
 
7b70181
6e8003f
7b70181
6e8003f
 
 
7b70181
7515e7a
7b70181
 
7515e7a
 
7b70181
7515e7a
7b70181
7515e7a
 
 
7b70181
7515e7a
 
 
 
 
 
 
7b70181
 
7515e7a
 
 
 
 
 
 
7b70181
 
6e8003f
fd85e62
21a7ced
6e8003f
21a7ced
 
 
 
 
7b70181
6e8003f
 
7b70181
 
 
 
21a7ced
 
7b70181
6e8003f
 
 
7b70181
6e8003f
 
7b70181
21a7ced
 
6e8003f
7b70181
6e8003f
 
 
 
7b70181
6e8003f
 
 
 
 
 
7b70181
6e8003f
 
 
 
 
 
 
 
 
 
 
 
7b70181
 
 
6e8003f
 
 
7b70181
 
 
 
 
 
6e8003f
21a7ced
 
 
 
 
 
 
 
fd85e62
21a7ced
6e8003f
 
 
 
 
 
 
 
7b70181
 
 
21a7ced
7b70181
6e8003f
7b70181
 
 
fd85e62
 
7b70181
21a7ced
7b70181
 
21a7ced
7b70181
7515e7a
7b70181
 
 
7515e7a
 
 
 
 
 
 
7b70181
 
 
6e8003f
 
7b70181
 
 
 
6e8003f
 
7b70181
 
 
 
 
6e8003f
 
 
7b70181
6e8003f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7b70181
6e8003f
 
 
 
7b70181
e926e13
 
 
 
 
 
 
 
 
 
 
 
 
7b70181
 
 
 
 
 
 
 
 
7483975
7b70181
e926e13
 
 
 
 
6e8003f
 
 
 
 
 
 
 
 
 
 
 
7b70181
 
 
6e8003f
 
7b70181
 
 
 
 
 
 
 
7483975
7b70181
6e8003f
 
 
 
7b70181
6e8003f
 
 
 
7b70181
 
6e8003f
 
4541105
eba7095
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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
from httpx import AsyncClient
import os
import requests
import gradio as gr
import openai

from fastapi import Depends, FastAPI, Request
from app.db import User, create_db_and_tables
from app.schemas import UserCreate, UserRead, UserUpdate
from app.users import auth_backend, current_active_user, fastapi_users
from dotenv import load_dotenv
import examples as chatbot_examples

# Get the current environment from the environment variable
current_environment = os.getenv("APP_ENV", "dev")

# Load the appropriate .env file based on the current environment
if current_environment == "dev":
    load_dotenv(".env.dev")
elif current_environment == "test":
    load_dotenv(".env.test")
elif current_environment == "prod":
    load_dotenv(".env.prod")
else:
    raise ValueError("Invalid environment specified")


def api_login(email, password):
    port = os.getenv("APP_PORT")
    scheme = os.getenv("APP_SCHEME")
    host = os.getenv("APP_HOST")

    url = f"{scheme}://{host}:{port}/auth/jwt/login"
    payload = {"username": email, "password": password}
    headers = {"Content-Type": "application/x-www-form-urlencoded"}

    response = requests.post(url, data=payload, headers=headers)

    if response.status_code == 200:
        response_json = response.json()
        api_key = response_json["access_token"]
        return True, api_key
    else:
        response_json = response.json()
        detail = response_json["detail"]
        return False, detail


def get_api_key(email, password):
    successful, message = api_login(email, password)

    if successful:
        return os.getenv("APP_API_BASE"), message
    else:
        raise gr.Error(message)
        return "", ""


# Define a function to get the AI's reply using the OpenAI API
def get_ai_reply(
    message,
    model="gpt-3.5-turbo",
    system_message=None,
    temperature=0,
    message_history=[],
):
    # Initialize the messages list
    messages = []

    # Add the system message to the messages list
    if system_message is not None:
        messages += [{"role": "system", "content": system_message}]

    # Add the message history to the messages list
    if message_history is not None:
        messages += message_history

    # Add the user's message to the messages list
    messages += [{"role": "user", "content": message}]

    # Make an API call to the OpenAI ChatCompletion endpoint with the model and messages
    completion = openai.ChatCompletion.create(
        model=model, messages=messages, temperature=temperature
    )

    # Extract and return the AI's response from the API response
    return completion.choices[0].message.content.strip()


def get_ai_image(prompt, size="512x512"):
    response = openai.Image.create(prompt=prompt, n=1, size=size)
    image_1_url = response.data[0]["url"]
    return image_1_url


def get_ai_transcript(path_to_audio, language=None):
    audio_file = open(path_to_audio, "rb")
    transcript = openai.Audio.transcribe("whisper-1", audio_file, language=language)
    return transcript.text


def generate_transcription(path_to_audio_file):
    try:
        transcript = get_ai_transcript(path_to_audio_file)
        return transcript
    except Exception as e:
        raise gr.Error(e)
        return ""


def generate_image(prompt):
    try:
        image_url = get_ai_image(prompt)
        return image_url
    except Exception as e:
        raise gr.Error(e)
        return None


# Define a function to handle the chat interaction with the AI model
def chat(message, chatbot_messages, model, temperature, system_message):
    # Initialize chatbot_messages
    chatbot_messages = chatbot_messages or []

    history_openai_format = []
    for human, assistant in chatbot_messages:
        history_openai_format.append({"role": "user", "content": human})
        history_openai_format.append({"role": "assistant", "content": assistant})

    # Try to get the AI's reply using the get_ai_reply function
    try:
        ai_reply = get_ai_reply(
            message,
            model=model,
            system_message=system_message,
            message_history=history_openai_format,
            temperature=temperature,
        )
    except Exception as e:
        # If an error occurs, raise a Gradio error
        raise gr.Error(e)

    # Append the user's message and the AI's reply to the chatbot_messages list
    chatbot_messages.append((message, ai_reply))

    # Return None (empty out the user's message textbox), the updated chatbot_messages
    return None, chatbot_messages


# Define a function to launch the chatbot interface using Gradio
def get_chatbot_app(additional_examples=[]):
    # Load chatbot examples and merge with any additional examples provided
    examples = chatbot_examples.load_examples(additional=additional_examples)

    # Define a function to get the names of the examples
    def get_examples():
        return [example["name"] for example in examples]

    # Define a function to choose an example based on the index
    def choose_example(index):
        if index != None:
            system_message = examples[index]["system_message"].strip()
            user_message = examples[index]["message"].strip()
            return system_message, user_message, [], []
        else:
            return "", "", [], []

    # Create the Gradio interface using the Blocks layout
    with gr.Blocks() as app:
        with gr.Tab("Conversation"):
            with gr.Row():
                with gr.Column():
                    # Create a dropdown to select examples
                    example_dropdown = gr.Dropdown(
                        get_examples(), label="Examples", type="index"
                    )
                    # Create a button to load the selected example
                    example_load_btn = gr.Button(value="Load")
                    # Create a textbox for the system message (prompt)
                    system_message = gr.TextArea(
                        label="System Message (Prompt)",
                        value="You are a helpful assistant.",
                        lines=20,
                        max_lines=400,
                    )
                with gr.Column():
                    with gr.Row():
                        # Create a dropdown to select the AI model
                        model_selector = gr.Dropdown(
                            ["gpt-3.5-turbo", "gpt-3.5-turbo-16k"],
                            label="Model",
                            value="gpt-3.5-turbo",
                        )
                        temperature_slider = gr.Slider(
                            label="Temperature", minimum=0, maximum=2, step=0.1, value=0
                        )
                    # Create a chatbot interface for the conversation
                    chatbot = gr.Chatbot(label="Conversation")
                    # Create a textbox for the user's message
                    message = gr.Textbox(label="Message")
                    # Create a button to send the user's message
                    btn = gr.Button(value="Send")

                # Connect the example load button to the choose_example function
                example_load_btn.click(
                    choose_example,
                    inputs=[example_dropdown],
                    outputs=[system_message, message, chatbot],
                )
                # Connect the send button to the chat function
                btn.click(
                    chat,
                    inputs=[
                        message,
                        chatbot,
                        model_selector,
                        temperature_slider,
                        system_message,
                    ],
                    outputs=[message, chatbot],
                )
        with gr.Tab("Image Generation"):
            image_prompt = gr.Textbox(
                label="Prompt", placeholder="A cute puppy wearing sunglasses."
            )
            image_btn = gr.Button(value="Generate")
            image = gr.Image(label="Result", interactive=False, type="filepath")
            image_btn.click(generate_image, inputs=[image_prompt], outputs=[image])
        with gr.Tab("Speech-to-text"):
            audio_file = gr.Audio(label="Audio", source="microphone", type="filepath")
            transcribe = gr.Button(value="Transcribe")
            audio_transcript = gr.Textbox(label="Transcription", interactive=False)
            transcribe.click(
                generate_transcription, inputs=[audio_file], outputs=[audio_transcript]
            )
        with gr.Tab("Get API Key"):
            email_box = gr.Textbox(label="Email Address", placeholder="Student Email")
            password_box = gr.Textbox(
                label="Password", type="password", placeholder="Student ID"
            )
            btn = gr.Button(value="Generate")
            api_host_box = gr.Textbox(label="OpenAI API Base", interactive=False)
            api_key_box = gr.Textbox(label="OpenAI API Key", interactive=False)
            btn.click(
                get_api_key,
                inputs=[email_box, password_box],
                outputs=[api_host_box, api_key_box],
            )
        # Return the app
        return app


app = FastAPI()

app.include_router(
    fastapi_users.get_auth_router(auth_backend), prefix="/auth/jwt", tags=["auth"]
)
app.include_router(
    fastapi_users.get_register_router(UserRead, UserCreate),
    prefix="/auth",
    tags=["auth"],
)
app.include_router(
    fastapi_users.get_users_router(UserRead, UserUpdate),
    prefix="/users",
    tags=["users"],
)


@app.get("/authenticated-route")
async def authenticated_route(user: User = Depends(current_active_user)):
    return {"message": f"Hello {user.email}!"}


@app.post("/v1/completions")
async def openai_api_completions_passthrough(
    request: Request,
    user: User = Depends(fastapi_users.current_user()),
):
    if not user:
        raise HTTPException(status_code=401, detail="Unauthorized")

    # Get the request data and headers
    request_data = await request.json()
    request_headers = request.headers
    openai_api_key = os.getenv("OPENAI_API_KEY")

    # Forward the request to the OpenAI API
    async with AsyncClient() as client:
        response = await client.post(
            "https://api.openai.com/v1/completions",
            json=request_data,
            headers={
                "Content-Type": request_headers.get("Content-Type"),
                "Authorization": f"Bearer {openai_api_key}",
            },
            timeout=120.0,
        )

    # Return the OpenAI API response
    return response.json()


@app.post("/v1/chat/completions")
async def openai_api_chat_completions_passthrough(
    request: Request,
    user: User = Depends(fastapi_users.current_user()),
):
    if not user:
        raise HTTPException(status_code=401, detail="Unauthorized")

    # Get the request data and headers
    request_data = await request.json()
    request_headers = request.headers
    openai_api_key = os.getenv("OPENAI_API_KEY")

    if "gpt-4" in request_data["model"]:
        request_data["model"] = "gpt-3.5-turbo"

    # Forward the request to the OpenAI API
    async with AsyncClient() as client:
        response = await client.post(
            "https://api.openai.com/v1/chat/completions",
            json=request_data,
            headers={
                "Content-Type": request_headers.get("Content-Type"),
                "Authorization": f"Bearer {openai_api_key}",
            },
            timeout=120.0,
        )

    # Return the OpenAI API response
    return response.json()


@app.on_event("startup")
async def on_startup():
    # Not needed if you setup a migration system like Alembic
    await create_db_and_tables()


gradio_gui = get_chatbot_app()
gradio_gui.auth = api_login
gradio_gui.auth_message = "Welcome, to the 4341 OpenAI Service"
app = gr.mount_gradio_app(app, gradio_gui, path="/")