Spaces:
Runtime error
Runtime error
Create app.py
Browse files
app.py
ADDED
@@ -0,0 +1,111 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
|
2 |
+
import gradio as gr
|
3 |
+
from langchain_community.vectorstores import Qdrant
|
4 |
+
from qdrant_client import QdrantClient
|
5 |
+
from qdrant_client.http import models
|
6 |
+
from google.colab import userdata
|
7 |
+
from qdrant_client import QdrantClient
|
8 |
+
from langchain_openai import OpenAIEmbeddings
|
9 |
+
from langchain.prompts import PromptTemplate
|
10 |
+
from langchain.chains import LLMChain
|
11 |
+
from langchain_openai import ChatOpenAI
|
12 |
+
from google.colab import userdata
|
13 |
+
from typing import Optional
|
14 |
+
|
15 |
+
def util_bot(question: str, openai_api_key: str) -> Optional[str]:
|
16 |
+
"""
|
17 |
+
Processes a given question using a combination of Qdrant vector search and an LLM (Large Language Model) response generation.
|
18 |
+
|
19 |
+
This function embeds the input question using OpenAI's embedding model, searches for relevant context using Qdrant,
|
20 |
+
and generates a response based on the context found and the input question using an LLM.
|
21 |
+
|
22 |
+
Args:
|
23 |
+
question (str): The user's question to be answered.
|
24 |
+
openai_api_key (str): API key for accessing OpenAI's services.
|
25 |
+
|
26 |
+
Returns:
|
27 |
+
Optional[str]: The generated answer, or None if no answer could be generated.
|
28 |
+
|
29 |
+
Raises:
|
30 |
+
Exception: If an error occurs during processing.
|
31 |
+
"""
|
32 |
+
|
33 |
+
# Configuration for Qdrant client
|
34 |
+
qdrant_end =os.environ['Qdrant_embeddings_url']
|
35 |
+
qdrant_api_key = os.environ['Qdrant_api_key']
|
36 |
+
|
37 |
+
# Initialize Qdrant client
|
38 |
+
qdrant_client = QdrantClient(url=qdrant_end, api_key=qdrant_api_key)
|
39 |
+
|
40 |
+
# Initialize embeddings using OpenAI
|
41 |
+
embeddings = OpenAIEmbeddings(model='text-embedding-3-small',openai_api_key=os.environ['openai_api_key'])
|
42 |
+
|
43 |
+
try:
|
44 |
+
# Embed the input question for vector search
|
45 |
+
query_result = embeddings.embed_query(question)
|
46 |
+
|
47 |
+
# Perform vector search in the "util-bot" collection
|
48 |
+
response = qdrant_client.search(
|
49 |
+
collection_name="util-bot",
|
50 |
+
query_vector=query_result,
|
51 |
+
limit=3 # Retrieve top 3 closest vectors
|
52 |
+
)
|
53 |
+
|
54 |
+
# Construct the prompt template for the LLM
|
55 |
+
prompt=PromptTemplate(
|
56 |
+
template=""""Use the following pieces of context to answer the questions at the end.If
|
57 |
+
you don't know the answer, just say don't know. do not try to make up the answer.
|
58 |
+
|
59 |
+
|
60 |
+
{context}
|
61 |
+
|
62 |
+
|
63 |
+
Question: {question}
|
64 |
+
Helpful Answer,formatted in markdown:""",
|
65 |
+
input_variables=["context","question"]
|
66 |
+
)
|
67 |
+
|
68 |
+
# Initialize LLM and the chain for generating the response
|
69 |
+
llm = ChatOpenAI(model='gpt-3.5-turbo-0125',openai_api_key=os.environ['openai_api_key'])
|
70 |
+
chain = LLMChain(llm=llm, prompt=prompt)
|
71 |
+
|
72 |
+
# Generate the response
|
73 |
+
result = chain({
|
74 |
+
"question": question,
|
75 |
+
"context": "\n".join([doc.payload['page_content'] for doc in response]) # Concatenate context from search results
|
76 |
+
})
|
77 |
+
|
78 |
+
return result['text']
|
79 |
+
except Exception as e:
|
80 |
+
# Log the exception or handle it as per the application's error handling policy
|
81 |
+
print(f"Error processing question: {e}")
|
82 |
+
return None
|
83 |
+
|
84 |
+
|
85 |
+
with gr.Blocks() as app:
|
86 |
+
# Customize the app's appearance
|
87 |
+
gr.Markdown("Utility Bill Helper")
|
88 |
+
gr.Markdown("### Ask any question related to Utility bills in the USA")
|
89 |
+
|
90 |
+
with gr.Row():
|
91 |
+
question = gr.Textbox(lines=3, label="Enter your question", placeholder="Type your question here...")
|
92 |
+
|
93 |
+
|
94 |
+
submit_button = gr.Button("Submit")
|
95 |
+
|
96 |
+
with gr.Column():
|
97 |
+
response = gr.Textbox(label="Response", placeholder="The response will appear here...", lines=10, interactive=False)
|
98 |
+
|
99 |
+
# Define the action to take on button click - Ensure util_bot function is awaited if it's async
|
100 |
+
submit_button.click(util_bot, inputs=[question, openai_api_key], outputs=response)
|
101 |
+
|
102 |
+
# Customizing the app's theme and adding CSS for fonts and colors
|
103 |
+
app.css = """
|
104 |
+
body { font-family: 'Arial', sans-serif; }
|
105 |
+
h2 { font-weight: bold; }
|
106 |
+
.gr-button { background-color: #4CAF50; color: white; font-size: 16px; }
|
107 |
+
.gr-textbox { border-color: #4CAF50; }
|
108 |
+
.gr-textbox:focus { border-color: #66BB6A; box-shadow: 0 0 0 0.2rem rgba(102, 187, 106, 0.25); }
|
109 |
+
"""
|
110 |
+
|
111 |
+
app.launch()
|