Update app.py
Browse filesAdd code for Agent
app.py
CHANGED
|
@@ -1,64 +1,160 @@
|
|
| 1 |
import gradio as gr
|
| 2 |
-
|
| 3 |
-
|
| 4 |
-
|
| 5 |
-
|
| 6 |
-
|
| 7 |
-
|
| 8 |
-
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
for val in history:
|
| 21 |
-
if val[0]:
|
| 22 |
-
messages.append({"role": "user", "content": val[0]})
|
| 23 |
-
if val[1]:
|
| 24 |
-
messages.append({"role": "assistant", "content": val[1]})
|
| 25 |
-
|
| 26 |
-
messages.append({"role": "user", "content": message})
|
| 27 |
-
|
| 28 |
-
response = ""
|
| 29 |
-
|
| 30 |
-
for message in client.chat_completion(
|
| 31 |
-
messages,
|
| 32 |
-
max_tokens=max_tokens,
|
| 33 |
-
stream=True,
|
| 34 |
-
temperature=temperature,
|
| 35 |
-
top_p=top_p,
|
| 36 |
-
):
|
| 37 |
-
token = message.choices[0].delta.content
|
| 38 |
-
|
| 39 |
-
response += token
|
| 40 |
-
yield response
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
"""
|
| 44 |
-
For information on how to customize the ChatInterface, peruse the gradio docs: https://www.gradio.app/docs/chatinterface
|
| 45 |
-
"""
|
| 46 |
-
demo = gr.ChatInterface(
|
| 47 |
-
respond,
|
| 48 |
-
additional_inputs=[
|
| 49 |
-
gr.Textbox(value="You are a friendly Chatbot.", label="System message"),
|
| 50 |
-
gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max new tokens"),
|
| 51 |
-
gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperature"),
|
| 52 |
-
gr.Slider(
|
| 53 |
-
minimum=0.1,
|
| 54 |
-
maximum=1.0,
|
| 55 |
-
value=0.95,
|
| 56 |
-
step=0.05,
|
| 57 |
-
label="Top-p (nucleus sampling)",
|
| 58 |
-
),
|
| 59 |
-
],
|
| 60 |
)
|
| 61 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 62 |
|
| 63 |
-
|
| 64 |
-
|
|
|
|
| 1 |
import gradio as gr
|
| 2 |
+
import PyPDF2
|
| 3 |
+
import os
|
| 4 |
+
from openai import OpenAI
|
| 5 |
+
import sys # Import sys to write to stderr
|
| 6 |
+
|
| 7 |
+
# --- Configuration & Client Initialization ---
|
| 8 |
+
# It's good practice to check for the API key at startup.
|
| 9 |
+
# This provides a clear error if the secret isn't set in Hugging Face Spaces.
|
| 10 |
+
NEBIUS_API_KEY = os.getenv("NEBIUS_API_KEY")
|
| 11 |
+
if not NEBIUS_API_KEY:
|
| 12 |
+
# Use a more descriptive error message.
|
| 13 |
+
raise ValueError("API Key not found. Please set the NEBIUS_API_KEY secret in your Hugging Face Space settings.")
|
| 14 |
+
|
| 15 |
+
# Initialize the OpenAI client with your custom endpoint.
|
| 16 |
+
# Ensure this base_url is correct and publicly accessible.
|
| 17 |
+
client = OpenAI(
|
| 18 |
+
base_url="https://api.studio.nebius.com/v1/",
|
| 19 |
+
api_key=NEBIUS_API_KEY
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 20 |
)
|
| 21 |
|
| 22 |
+
# --- Core Functions ---
|
| 23 |
+
|
| 24 |
+
def extract_text_from_pdf(pdf_file):
|
| 25 |
+
"""Extracts text from an uploaded PDF file object."""
|
| 26 |
+
# pdf_file is a temporary file object from Gradio.
|
| 27 |
+
if not pdf_file:
|
| 28 |
+
return ""
|
| 29 |
+
try:
|
| 30 |
+
reader = PyPDF2.PdfReader(pdf_file.name)
|
| 31 |
+
text = ""
|
| 32 |
+
# Extract text from all pages except the first one.
|
| 33 |
+
for i, page in enumerate(reader.pages):
|
| 34 |
+
if i == 0:
|
| 35 |
+
continue
|
| 36 |
+
page_text = page.extract_text()
|
| 37 |
+
if page_text:
|
| 38 |
+
text += page_text + "\n"
|
| 39 |
+
return text
|
| 40 |
+
except Exception as e:
|
| 41 |
+
print(f"Error reading PDF: {e}", file=sys.stderr)
|
| 42 |
+
return ""
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
def get_llm_answer(pdf_text, question, history):
|
| 46 |
+
"""
|
| 47 |
+
Sends the context, history, and question to the LLM and returns the answer.
|
| 48 |
+
"""
|
| 49 |
+
# Truncate the PDF text to avoid exceeding the model's context limit.
|
| 50 |
+
context = pdf_text[:16000]
|
| 51 |
+
|
| 52 |
+
# The system prompt guides the model's behavior.
|
| 53 |
+
system_prompt = '''You are a helpful assistant who specializes in body composition, diet, and exercise.
|
| 54 |
+
Answer questions based on the provided document. Encourage the user to seek a professional
|
| 55 |
+
if they have serious concerns whenever appropriate.'''
|
| 56 |
+
|
| 57 |
+
# Construct the message payload for the API.
|
| 58 |
+
messages = [{"role": "system", "content": system_prompt},
|
| 59 |
+
{"role": "user", "content": f"Use the following document to answer my question:\n\n{context}"},
|
| 60 |
+
{"role":"user", "content": f"Question: {question}"}
|
| 61 |
+
]
|
| 62 |
+
|
| 63 |
+
# Add the conversation history.
|
| 64 |
+
if history:
|
| 65 |
+
for msg in history:
|
| 66 |
+
if msg["role"] in ["user", "assistant"]:
|
| 67 |
+
messages.append(msg)
|
| 68 |
+
# Add the new user question
|
| 69 |
+
messages.append({"role": "user", "content": question})
|
| 70 |
+
|
| 71 |
+
try:
|
| 72 |
+
response = client.chat.completions.create(
|
| 73 |
+
model="meta-llama/Meta-Llama-3.1-70B-Instruct",
|
| 74 |
+
temperature=0.6,
|
| 75 |
+
top_p=0.95,
|
| 76 |
+
messages=messages
|
| 77 |
+
)
|
| 78 |
+
return response.choices[0].message.content
|
| 79 |
+
except Exception as e:
|
| 80 |
+
print(f"Error calling OpenAI API: {e}", file=sys.stderr)
|
| 81 |
+
# Return a user-friendly error message.
|
| 82 |
+
return "Sorry, I encountered an error while trying to generate a response. Please check the logs."
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
# --- Gradio Interface Logic ---
|
| 86 |
+
|
| 87 |
+
# Use a class to manage state (the extracted PDF text).
|
| 88 |
+
class PDFChatbot:
|
| 89 |
+
def __init__(self):
|
| 90 |
+
self.pdf_text = None
|
| 91 |
+
self.pdf_filename = None
|
| 92 |
+
|
| 93 |
+
def upload_pdf(self, pdf_file):
|
| 94 |
+
if pdf_file is None:
|
| 95 |
+
return "Status: No PDF uploaded."
|
| 96 |
+
|
| 97 |
+
self.pdf_text = extract_text_from_pdf(pdf_file)
|
| 98 |
+
self.pdf_filename = os.path.basename(pdf_file.name)
|
| 99 |
+
|
| 100 |
+
if not self.pdf_text:
|
| 101 |
+
return f"Status: Could not extract text from {self.pdf_filename}. It might be empty, scanned, or protected."
|
| 102 |
+
|
| 103 |
+
return f"Status: Successfully processed {self.pdf_filename}. You can now ask questions."
|
| 104 |
+
|
| 105 |
+
def chat(self, user_message, history):
|
| 106 |
+
if self.pdf_text is None:
|
| 107 |
+
# Add an instruction to the chatbot window if no PDF is uploaded.
|
| 108 |
+
#history.append([user_message, "Please upload a PDF document first."])
|
| 109 |
+
return "Please upload a PDF document first.", history
|
| 110 |
+
|
| 111 |
+
if history is None:
|
| 112 |
+
history = []
|
| 113 |
+
context_history = [msg for msg in history if msg["role"] in ["user", "assistant"]]
|
| 114 |
+
# Get the answer from the LLM.
|
| 115 |
+
answer = get_llm_answer(self.pdf_text, user_message, context_history)
|
| 116 |
+
|
| 117 |
+
# Append the user message and the assistant's answer to the history.
|
| 118 |
+
history = history + [
|
| 119 |
+
{"role": "user", "content": user_message },
|
| 120 |
+
{"role": "assistant", "content": answer }
|
| 121 |
+
]
|
| 122 |
+
|
| 123 |
+
# Return an empty string to clear the input textbox and the updated history.
|
| 124 |
+
return "", history
|
| 125 |
+
|
| 126 |
+
# Instantiate the bot.
|
| 127 |
+
pdf_bot = PDFChatbot()
|
| 128 |
+
|
| 129 |
+
# Build the Gradio UI.
|
| 130 |
+
with gr.Blocks(theme=gr.themes.Soft()) as demo:
|
| 131 |
+
gr.Markdown("# Body Composition Agent\nUpload a document about your body composition and ask questions about its content.")
|
| 132 |
+
|
| 133 |
+
with gr.Row():
|
| 134 |
+
with gr.Column(scale=1):
|
| 135 |
+
pdf_file = gr.File(label="Upload PDF", file_types=[".pdf"])
|
| 136 |
+
upload_btn = gr.Button("Process PDF", variant="primary")
|
| 137 |
+
upload_status = gr.Textbox(label="Status", interactive=False, value="Status: Waiting for PDF...")
|
| 138 |
+
|
| 139 |
+
with gr.Column(scale=2):
|
| 140 |
+
chatbot = gr.Chatbot(type="messages", label="Chat History", height=500)
|
| 141 |
+
msg_textbox = gr.Textbox(label="Your Question:", interactive=True, placeholder="Type your question here...")
|
| 142 |
+
# Clear button is useful for starting a new conversation.
|
| 143 |
+
clear_btn = gr.ClearButton([msg_textbox, chatbot], value="Clear Chat")
|
| 144 |
+
|
| 145 |
+
# Wire up the event listeners.
|
| 146 |
+
upload_btn.click(
|
| 147 |
+
fn=pdf_bot.upload_pdf,
|
| 148 |
+
inputs=[pdf_file],
|
| 149 |
+
outputs=[upload_status]
|
| 150 |
+
)
|
| 151 |
+
|
| 152 |
+
# Allow submitting questions with Enter key or the button.
|
| 153 |
+
msg_textbox.submit(
|
| 154 |
+
fn=pdf_bot.chat,
|
| 155 |
+
inputs=[msg_textbox, chatbot],
|
| 156 |
+
outputs=[msg_textbox, chatbot]
|
| 157 |
+
)
|
| 158 |
|
| 159 |
+
# Launch the app.
|
| 160 |
+
demo.launch(debug=True) # Use debug=True to see errors in the console.
|