The provided Python code implements a web-based chat application using Gradio, allowing users to interact with an OpenAI language model via API calls. Below is a detailed explanation of the code, broken down into its main components:
1. Importing Required Libraries
import gradio as gr
import os
import sys
import json
import requests
import random
- gradio: A Python library for creating web interfaces easily.
- os: Provides a way to use operating system-dependent functionality, such as reading environment variables.
- sys: Access to some variables used or maintained by the interpreter.
- json: For encoding and decoding JSON data.
- requests: Simplifies making HTTP requests.
- random: Implements pseudo-random number generators.
2. Setting Up Initial Configuration
MODEL = "o1-preview"
API_URL = os.getenv("API_URL")
DISABLED = os.getenv("DISABLED") == 'True'
OPENAI_API_KEYS = os.getenv("OPENAI_API_KEYS").split(',')
NUM_THREADS = int(os.getenv("NUM_THREADS"))
print(API_URL)
print(OPENAI_API_KEYS)
print(NUM_THREADS)
- MODEL: Specifies the model name to use with the OpenAI API.
- API_URL: Retrieves the API endpoint URL from an environment variable.
- DISABLED: A flag to enable or disable the app based on an environment variable.
- OPENAI_API_KEYS: Retrieves and splits multiple OpenAI API keys from an environment variable for load balancing.
- NUM_THREADS: Sets the number of concurrent threads for handling requests, obtained from an environment variable.
3. Custom Exception Handling
def exception_handler(exception_type, exception, traceback):
print("%s: %s" % (exception_type.__name__, exception))
sys.excepthook = exception_handler
sys.tracebacklimit = 0
- exception_handler: Defines a custom function to handle exceptions and print them in a simplified format.
- sys.excepthook: Overrides the default exception hook with the custom handler.
- sys.tracebacklimit: Limits the traceback to zero to prevent detailed traceback information from being printed.
4. Parsing Code Blocks in Text
def parse_codeblock(text):
lines = text.split("\n")
for i, line in enumerate(lines):
if "```" in line:
if line != "```":
lines[i] = f'<pre><code class="{lines[i][3:]}">'
else:
lines[i] = '</code></pre>'
else:
if i > 0:
lines[i] = "<br/>" + line.replace("<", "<").replace(">", ">")
return "".join(lines)
- parse_codeblock: Converts markdown-style code blocks in text into HTML-formatted code blocks suitable for display in the chat interface.
- Purpose: Ensures that code snippets sent by the assistant are properly formatted and displayed to the user.
5. Defining the Main Prediction Function
def predict(inputs, top_p, temperature, chat_counter, chatbot, history, request: gr.Request):
# Function body...
This function handles user inputs, communicates with the OpenAI API, and streams responses back to the user.
5.1. Preparing the Payload for the API Request
-
Initial Payload: For a new conversation.
payload = {
"model": MODEL,
"messages": [{"role": "user", "content": f"{inputs}"}],
"temperature": 1.0,
"top_p": 1.0,
"n": 1,
"stream": True,
"presence_penalty": 0,
"frequency_penalty": 0,
}
-
Updating Payload with Conversation History: If it's not the first message.
if chat_counter != 0:
messages = []
for i, data in enumerate(history):
role = 'user' if i % 2 == 0 else 'assistant'
messages.append({"role": role, "content": data})
messages.append({"role": "user", "content": inputs})
payload["messages"] = messages
payload["temperature"] = temperature
payload["top_p"] = top_p
5.2. Setting Up the Request Headers
OPENAI_API_KEY = random.choice(OPENAI_API_KEYS)
headers_dict = {key.decode('utf-8'): value.decode('utf-8') for key, value in request.headers.raw}
headers = {
"Content-Type": "application/json",
"Authorization": f"Bearer {OPENAI_API_KEY}",
"Headers": f"{headers_dict}"
}
- Randomly selects an API key from the list.
- Prepares the headers, including the authorization token and request headers metadata.
5.3. Sending the API Request and Streaming the Response
response = requests.post(API_URL, headers=headers, json=payload, stream=True)
- Sends a POST request to the API endpoint with streaming enabled.
5.4. Processing the Streaming Response
for chunk in response.iter_lines():
# Process each chunk...
-
Iterating Over Chunks: Processes each line of the streamed response.
-
Extracting Content: Accumulates the assistant's reply.
if len(chunk) > 12 and "content" in json.loads(chunk[6:])['choices'][0]['delta']:
partial_words += json.loads(chunk[6:])['choices'][0]["delta"]["content"]
# Update history and yield the updated chat interface...
5.5. Handling Exceptions
except Exception as e:
print(f'error found: {e}')
- Catches any exceptions during the request and prints a simplified error message.
6. Resetting the Input Textbox
def reset_textbox():
return gr.update(value='', interactive=False), gr.update(interactive=False)
- Purpose: Clears the input textbox and sets it to non-interactive state until the assistant finishes responding.
7. Building the Gradio Interface
7.1. Setting Up the Layout
with gr.Blocks(css=..., theme=...) as demo:
gr.HTML(title)
gr.HTML("""<h3 align="center" style="color: red;">If this app doesn't respond, consider trying our O1-mini app...</h3>""")
# Main application and user consent blocks...
- Title and Description: Displays the app's title and provides alternative options if the app is unresponsive.
7.2. User Consent Section
with gr.Column(elem_id="user_consent_container") as user_consent_block:
accept_checkbox = gr.Checkbox(visible=False)
js = "(x) => confirm('By clicking \"OK\", I agree that my data may be published or shared.')"
with gr.Accordion("User Consent for Data Collection, Use, and Sharing", open=True):
gr.HTML("""<div>...<p>By continuing to use our app, you provide your explicit consent...</p></div>""")
accept_button = gr.Button("I Agree")
- Purpose: Informs users about data collection practices and obtains consent before they can use the app.
- accept_button: When clicked, triggers a JavaScript confirmation dialog and updates the interface to show the main application.
7.3. Main Chat Application
with gr.Column(elem_id="col_container", visible=False) as main_block:
chatbot = gr.Chatbot(elem_id='chatbot')
inputs = gr.Textbox(placeholder="Hi there!", label="Type an input and press Enter")
state = gr.State([])
# Parameters and controls...
- chatbot: Displays the conversation between the user and the assistant.
- inputs: Textbox for user input.
- state: Maintains the conversation history.
- Controls: Includes a button to send messages and sliders to adjust
top_p and temperature.
7.4. Event Handlers and Function Bindings
inputs.submit(reset_textbox, [], [inputs, b1], queue=False)
inputs.submit(predict, [inputs, top_p, temperature, chat_counter, chatbot, state], [chatbot, state, chat_counter, server_status_code, inputs, b1])
b1.click(reset_textbox, [], [inputs, b1], queue=False)
b1.click(predict, [inputs, top_p, temperature, chat_counter, chatbot, state], [chatbot, state, chat_counter, server_status_code, inputs, b1])
- inputs.submit: Triggers when the user presses Enter in the input textbox.
- b1.click: Triggers when the user clicks the send button.
- Function Bindings: Connects the interface elements to the
reset_textbox and predict functions.
8. Launching the Application
demo.queue(max_size=10, default_concurrency_limit=NUM_THREADS, api_open=False).launch(share=False)
- demo.queue: Configures the queuing system for handling multiple requests.
- max_size: Maximum number of concurrent jobs in the queue.
- default_concurrency_limit: Limits concurrent threads based on
NUM_THREADS.
- launch(): Starts the Gradio app without sharing publicly (
share=False).
Summary of the Application Flow
- User Consent: The user must agree to the data collection terms to use the app.
- User Interaction: The user types a message and submits it.
- Processing Input:
- The
predict function is called with the user's input and current parameters.
- Conversation history is updated and included in the API request.
- Communicating with OpenAI API:
- A streaming request is sent to the OpenAI API.
- The assistant's response is received incrementally.
- Updating the Interface:
- As chunks of the response arrive, the chat interface is updated in real-time.
- Code blocks in the response are formatted appropriately.
- Continuing the Conversation:
- The user can adjust parameters like
top_p and temperature to influence the assistant's responses.
- The conversation history allows for context-aware interactions.
Key Features and Considerations
- Environment Variables: The app uses environment variables for configuration, enhancing security and flexibility.
- Load Balancing: Randomly selects from multiple API keys to distribute the load and avoid rate limits.
- Exception Handling: Custom handling to prevent exposure of sensitive information.
- User Experience:
- Real-time streaming of responses provides a smooth interaction.
- Parameters allow users to customize the assistant's behavior.
- Data Privacy: Explicit user consent is obtained for data collection and sharing.
Conclusion
The code sets up a functional chat application that integrates with OpenAI's language models. It demonstrates handling user inputs, managing conversation state, and interfacing with an external API while providing a user-friendly web interface through Gradio. The application also takes into account important aspects like user consent, data handling, and operational configurations.