|
import openai
|
|
import gradio as gr
|
|
from full_chain import get_response
|
|
import os
|
|
import logging
|
|
|
|
|
|
logging.basicConfig(
|
|
level=logging.INFO,
|
|
format='%(asctime)s - %(levelname)s - %(message)s',
|
|
handlers=[
|
|
logging.FileHandler('app.log'),
|
|
logging.StreamHandler()
|
|
]
|
|
)
|
|
logger = logging.getLogger(__name__)
|
|
|
|
|
|
try:
|
|
api_key = os.getenv("OPENAI_API_KEY")
|
|
if not api_key:
|
|
raise ValueError("OPENAI_API_KEY environment variable not set")
|
|
client = openai.OpenAI(api_key=api_key)
|
|
logger.info("OpenAI client initialized successfully")
|
|
except Exception as e:
|
|
logger.error(f"Failed to initialize OpenAI client: {str(e)}")
|
|
raise
|
|
|
|
def create_hyperlink(url, title, domain):
|
|
"""Create HTML hyperlink with domain information."""
|
|
return f"<a href='{url}'>{title}</a> ({domain})"
|
|
|
|
def predict(message, history):
|
|
"""Process user message and return response with source links."""
|
|
try:
|
|
logger.info(f"Processing new query: {message}")
|
|
|
|
|
|
responder, links, titles, domains = get_response(message, rerank_type="crossencoder")
|
|
logger.info(f"Received response with {len(links)} sources")
|
|
|
|
|
|
formatted_links = [create_hyperlink(link, title, domain)
|
|
for link, title, domain in zip(links, titles, domains)]
|
|
|
|
|
|
out = responder + "\n" + "\n".join(formatted_links)
|
|
|
|
logger.info("Response generated successfully")
|
|
return out
|
|
|
|
except Exception as e:
|
|
error_msg = f"Error processing query: {str(e)}"
|
|
logger.error(error_msg)
|
|
return f"An error occurred while processing your request: {str(e)}"
|
|
|
|
|
|
EXAMPLE_QUERIES = [
|
|
"How many Americans Smoke?",
|
|
"What are some measures taken by the Indian Government to reduce the smoking population?",
|
|
"Does smoking negatively affect my health?"
|
|
]
|
|
|
|
|
|
def main():
|
|
try:
|
|
interface = gr.ChatInterface(
|
|
predict,
|
|
examples=EXAMPLE_QUERIES,
|
|
title="Tobacco Information Assistant",
|
|
description="Ask questions about tobacco-related topics and get answers with reliable sources."
|
|
)
|
|
logger.info("Starting Gradio interface")
|
|
interface.launch()
|
|
except Exception as e:
|
|
logger.error(f"Failed to launch Gradio interface: {str(e)}")
|
|
raise
|
|
|
|
if __name__ == "__main__":
|
|
main() |