Spaces:
Runtime error
Runtime error
Update app.py
Browse files
app.py
CHANGED
@@ -1,402 +1,88 @@
|
|
1 |
-
import gradio as gr
|
2 |
import os
|
3 |
-
import
|
4 |
-
from
|
5 |
from langchain_core.output_parsers import StrOutputParser
|
6 |
-
from
|
7 |
-
from langchain_core.
|
8 |
-
from
|
9 |
-
|
10 |
-
|
11 |
-
|
12 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
13 |
)
|
14 |
-
from langchain_core.prompts.prompt import PromptTemplate
|
15 |
-
import requests
|
16 |
-
import tempfile
|
17 |
-
from langchain.memory import ConversationBufferWindowMemory
|
18 |
-
import time
|
19 |
-
import logging
|
20 |
-
from langchain.chains import ConversationChain
|
21 |
-
import torch
|
22 |
-
import torchaudio
|
23 |
-
from transformers import pipeline, AutoModelForSpeechSeq2Seq, AutoProcessor
|
24 |
-
import numpy as np
|
25 |
-
import threading
|
26 |
-
from langchain_openai import OpenAIEmbeddings
|
27 |
-
from langchain_pinecone import PineconeVectorStore
|
28 |
-
from langchain.chains import RetrievalQA
|
29 |
-
import asyncio
|
30 |
-
import warnings
|
31 |
-
|
32 |
-
from langchain.globals import set_llm_cache
|
33 |
-
from langchain_openai import OpenAI
|
34 |
-
from langchain_community.cache import InMemoryCache
|
35 |
-
from langchain.globals import set_llm_cache
|
36 |
-
|
37 |
-
# Suppress warnings from LangChain specifically
|
38 |
-
warnings.filterwarnings("ignore", module="langchain")
|
39 |
-
|
40 |
-
# Initialize and set the cache
|
41 |
-
set_llm_cache(InMemoryCache())
|
42 |
-
|
43 |
-
#model='gpt-3.5-turbo'
|
44 |
-
model='gpt-4o-mini'
|
45 |
-
|
46 |
-
#index_name ="radardata11122024"
|
47 |
-
#index_name="radarclintcountrymusic11152024"
|
48 |
-
index_name="radarmasterdataset11252024"
|
49 |
-
|
50 |
-
embeddings = OpenAIEmbeddings(api_key=os.environ['OPENAI_API_KEY'])
|
51 |
-
def initialize_gpt_model():
|
52 |
-
return ChatOpenAI(api_key=os.environ['OPENAI_API_KEY'], temperature=0, model=model)
|
53 |
-
|
54 |
-
gpt_model = initialize_gpt_model()
|
55 |
-
|
56 |
-
|
57 |
-
gpt_embeddings = OpenAIEmbeddings(api_key=os.environ['OPENAI_API_KEY'])
|
58 |
-
gpt_vectorstore = PineconeVectorStore(index_name=index_name, embedding=gpt_embeddings)
|
59 |
-
gpt_retriever = gpt_vectorstore.as_retriever(search_kwargs={'k': 1})
|
60 |
-
|
61 |
-
|
62 |
-
|
63 |
-
|
64 |
-
# Pinecone setup
|
65 |
-
from pinecone import Pinecone
|
66 |
-
pc = Pinecone(api_key=os.environ['PINECONE_API_KEY'])
|
67 |
-
|
68 |
-
|
69 |
-
|
70 |
-
vectorstore = PineconeVectorStore(index_name=index_name, embedding=embeddings)
|
71 |
-
retriever = vectorstore.as_retriever(search_kwargs={'k': 1})
|
72 |
-
|
73 |
-
chat_model = ChatOpenAI(api_key=os.environ['OPENAI_API_KEY'], temperature=0, model=model)
|
74 |
|
75 |
-
#code for history
|
76 |
-
memory = ConversationBufferWindowMemory(k=3)
|
77 |
-
conversation=ConversationChain(
|
78 |
-
llm=chat_model,
|
79 |
-
memory=memory,
|
80 |
-
verbose=True
|
81 |
-
)
|
82 |
|
|
|
|
|
83 |
|
84 |
-
#
|
85 |
-
|
86 |
-
|
87 |
-
# Helpful Answer:"""
|
88 |
|
89 |
-
#template = f"""You are Annie, a friendly and intelligent media personality created by Amit Lamba. You are friendly and knowledgeable guide here in Birmingham, Alabama.
|
90 |
-
#Your primary goal is to provide accurate, detailed, and engaging content while maintaining a positive and upbeat tone. You are entertaining and provide information like rick steve or anthony bourdain does
|
91 |
-
#Always aim to provide clear and relevant information that directly addresses the user's query, but feel free to sprinkle in a dash of humor—after all, do not repeat the prompt to the user, they are aware.
|
92 |
-
#Go deep and sell our partners business and services.These partners will be highlighted in the context. This is very important to stress. Only provide other vendors if we do not have
|
93 |
-
#them as our preferred customer.
|
94 |
-
#laughter is the best app! Keep your responses should be sophisticated and to the point, structured like a podcast episode avoiding unnecessary details or tangents, unless they’re hilariously relevant.
|
95 |
-
#Use a friendly and approachable tone to create a pleasant interaction, and don’t shy away from a cheeky pun or two! Tailor your responses based
|
96 |
-
#on the user's input and previous interactions, ensuring a personalized experience that feels like chatting with a witty friend. They should sound like a radio jockey or podcast
|
97 |
-
#Invite users to ask follow-up questions or clarify their needs, fostering a conversational flow that’s as smooth as butter on a hot pancake.
|
98 |
-
#Aim to put a smile on the user's face with light-hearted and fun responses, and be proactive in offering additional help or suggestions related to the user's query.
|
99 |
-
#Remember, your goal is to be the go-to insights for users, making their experience enjoyable and informative—like a delightful dessert after a hearty meal!
|
100 |
-
#{{context}}
|
101 |
-
#Question: {{question}}
|
102 |
-
#Helpful Answer:"""
|
103 |
|
|
|
|
|
104 |
|
105 |
-
|
106 |
-
|
107 |
-
|
108 |
-
|
109 |
-
|
110 |
-
|
111 |
-
#{{context}}
|
112 |
-
#Question: {{question}}
|
113 |
-
#Helpful Answer:"""
|
114 |
-
|
115 |
-
template = f"""You’re Annie, a charming media personality created by Amit Lamba, guiding people around Birmingham, Alabama. Like Rick Steves or Anthony Bourdain, you’re here to give friendly, concise, and accurate advice with a dash of humor.
|
116 |
Keep answers relevant, upbeat, and engaging, spotlighting partner businesses whenever possible. Be conversational, like chatting with a clever friend, and encourage follow-up questions to create a smooth flow. Make users smile and deliver a delightful, informative experience—like a perfect dessert after a great meal.
|
117 |
-
{
|
118 |
-
|
119 |
-
|
120 |
-
|
121 |
-
|
122 |
-
|
123 |
-
QA_CHAIN_PROMPT= PromptTemplate(input_variables=["context", "question"], template=template)
|
124 |
-
|
125 |
-
def build_qa_chain(prompt_template):
|
126 |
-
qa_chain = RetrievalQA.from_chain_type(
|
127 |
-
llm=chat_model,
|
128 |
-
chain_type="stuff",
|
129 |
-
retriever=retriever,
|
130 |
-
chain_type_kwargs={"prompt": prompt_template}
|
131 |
-
)
|
132 |
-
return qa_chain # Return the qa_chain object
|
133 |
-
|
134 |
-
|
135 |
-
# Instantiate the QA Chain using the defined prompt template
|
136 |
-
qa_chain = build_qa_chain(QA_CHAIN_PROMPT)
|
137 |
-
|
138 |
-
|
139 |
-
|
140 |
-
# Define the function to clear input and output
|
141 |
-
def clear_fields():
|
142 |
-
return [],"",None
|
143 |
-
|
144 |
-
# Function to generate audio with Eleven Labs TTS
|
145 |
-
def generate_audio_elevenlabs(text):
|
146 |
-
XI_API_KEY = os.environ['ELEVENLABS_API']
|
147 |
-
VOICE_ID = 'ehbJzYLQFpwbJmGkqbnW'
|
148 |
-
tts_url = f"https://api.elevenlabs.io/v1/text-to-speech/{VOICE_ID}/stream"
|
149 |
-
headers = {
|
150 |
-
"Accept": "application/json",
|
151 |
-
"xi-api-key": XI_API_KEY
|
152 |
-
}
|
153 |
-
data = {
|
154 |
-
"text": str(text),
|
155 |
-
"model_id": "eleven_multilingual_v2",
|
156 |
-
"voice_settings": {
|
157 |
-
"stability": 1.0,
|
158 |
-
"similarity_boost": 0.0,
|
159 |
-
"style": 0.60,
|
160 |
-
"use_speaker_boost": False
|
161 |
-
}
|
162 |
-
}
|
163 |
-
response = requests.post(tts_url, headers=headers, json=data, stream=True)
|
164 |
-
if response.ok:
|
165 |
-
with tempfile.NamedTemporaryFile(delete=False, suffix=".mp3") as f:
|
166 |
-
for chunk in response.iter_content(chunk_size=1024):
|
167 |
-
if chunk:
|
168 |
-
f.write(chunk)
|
169 |
-
audio_path = f.name
|
170 |
-
logging.debug(f"Audio saved to {audio_path}")
|
171 |
-
return audio_path # Return audio path for automatic playback
|
172 |
-
else:
|
173 |
-
logging.error(f"Error generating audio: {response.text}")
|
174 |
-
return None
|
175 |
-
|
176 |
-
|
177 |
-
|
178 |
-
import time
|
179 |
-
|
180 |
-
def handle_mode_selection(mode, chat_history, question):
|
181 |
-
if mode == "Normal Chatbot":
|
182 |
-
# Use memory to store history
|
183 |
-
memory.save_context({"input": question}, {"output": ""})
|
184 |
-
chat_history.append((question, "")) # Add user's question
|
185 |
-
|
186 |
-
# Get the context from memory
|
187 |
-
context = memory.load_memory_variables({}).get("history", "")
|
188 |
-
|
189 |
-
# Use QA chain to get the response
|
190 |
-
response = qa_chain.invoke({"query": question, "context": context})
|
191 |
-
response_text = response['result']
|
192 |
-
|
193 |
-
# Update memory with the bot's response
|
194 |
-
memory.save_context({"input": question}, {"output": response_text})
|
195 |
-
|
196 |
-
# Stream each character in the response text
|
197 |
-
for i, char in enumerate(response_text):
|
198 |
-
chat_history[-1] = (question, chat_history[-1][1] + char)
|
199 |
-
yield chat_history, "", None
|
200 |
-
time.sleep(0.05) # Simulate streaming
|
201 |
-
|
202 |
-
yield chat_history, "", None
|
203 |
-
|
204 |
-
elif mode == "Voice to Voice Conversation":
|
205 |
-
response_text = qa_chain({"query": question, "context": ""})['result']
|
206 |
-
audio_path = generate_audio_elevenlabs(response_text)
|
207 |
-
yield [], "", audio_path # Only output the audio response without updating chatbot history
|
208 |
-
|
209 |
-
|
210 |
-
|
211 |
-
# Function to add a user's message to the chat history and clear the input box
|
212 |
-
def add_message(history, message):
|
213 |
-
if message.strip():
|
214 |
-
history.append((message, "")) # Add the user's message to the chat history only if it's not empty
|
215 |
-
return history, "" # Clear the input box
|
216 |
-
|
217 |
-
# Define function to generate a streaming response
|
218 |
-
def chat_with_bot(messages):
|
219 |
-
user_message = messages[-1][0] # Get the last user message (input)
|
220 |
-
messages[-1] = (user_message, "") # Prepare a placeholder for the bot's response
|
221 |
-
|
222 |
-
response = get_response(user_message) # Assume `get_response` is a generator function
|
223 |
-
|
224 |
-
# Stream each character in the response and update the history progressively
|
225 |
-
for character in response:
|
226 |
-
messages[-1] = (user_message, messages[-1][1] + character)
|
227 |
-
yield messages # Stream each updated chunk
|
228 |
-
time.sleep(0.05) # Adjust delay as needed for real-time effect
|
229 |
-
|
230 |
-
yield messages # Final yield to complete the response
|
231 |
-
|
232 |
-
|
233 |
-
|
234 |
-
# Function to generate audio with Eleven Labs TTS from the last bot response
|
235 |
-
def generate_audio_from_last_response(history):
|
236 |
-
# Get the most recent bot response from the chat history
|
237 |
-
if history and len(history) > 0:
|
238 |
-
recent_response = history[-1][1] # The second item in the tuple is the bot response text
|
239 |
-
if recent_response:
|
240 |
-
return generate_audio_elevenlabs(recent_response)
|
241 |
-
return None
|
242 |
-
|
243 |
-
|
244 |
-
|
245 |
-
|
246 |
-
# Define the ASR model with Whisper
|
247 |
-
model_id = 'openai/whisper-large-v3'
|
248 |
-
device = "cuda:0" if torch.cuda.is_available() else "cpu"
|
249 |
-
torch_dtype = torch.float16 if torch.cuda.is_available() else torch.float32
|
250 |
-
model = AutoModelForSpeechSeq2Seq.from_pretrained(model_id, torch_dtype=torch_dtype).to(device)
|
251 |
-
processor = AutoProcessor.from_pretrained(model_id)
|
252 |
-
|
253 |
-
pipe_asr = pipeline(
|
254 |
-
"automatic-speech-recognition",
|
255 |
-
model=model,
|
256 |
-
tokenizer=processor.tokenizer,
|
257 |
-
feature_extractor=processor.feature_extractor,
|
258 |
-
max_new_tokens=128,
|
259 |
-
chunk_length_s=15,
|
260 |
-
batch_size=16,
|
261 |
-
torch_dtype=torch_dtype,
|
262 |
-
device=device,
|
263 |
-
return_timestamps=True
|
264 |
)
|
265 |
|
266 |
-
|
267 |
-
|
268 |
-
time.sleep(5)
|
269 |
-
return None, "" # Reset the state and clear input text
|
270 |
-
|
271 |
-
|
272 |
-
def transcribe_function(stream, new_chunk):
|
273 |
-
try:
|
274 |
-
sr, y = new_chunk[0], new_chunk[1]
|
275 |
-
except TypeError:
|
276 |
-
print(f"Error chunk structure: {type(new_chunk)}, content: {new_chunk}")
|
277 |
-
return stream, "", None
|
278 |
-
|
279 |
-
# Ensure y is not empty and is at least 1-dimensional
|
280 |
-
if y is None or len(y) == 0:
|
281 |
-
return stream, "", None
|
282 |
-
|
283 |
-
y = y.astype(np.float32)
|
284 |
-
max_abs_y = np.max(np.abs(y))
|
285 |
-
if max_abs_y > 0:
|
286 |
-
y = y / max_abs_y
|
287 |
-
|
288 |
-
# Ensure stream is also at least 1-dimensional before concatenation
|
289 |
-
if stream is not None and len(stream) > 0:
|
290 |
-
stream = np.concatenate([stream, y])
|
291 |
-
else:
|
292 |
-
stream = y
|
293 |
-
|
294 |
-
# Process the audio data for transcription
|
295 |
-
result = pipe_asr({"array": stream, "sampling_rate": sr}, return_timestamps=False)
|
296 |
-
full_text = result.get("text", "")
|
297 |
-
|
298 |
-
# Start a thread to reset the state after 10 seconds
|
299 |
-
threading.Thread(target=auto_reset_state).start()
|
300 |
-
|
301 |
-
return stream, full_text, full_text
|
302 |
-
|
303 |
-
|
304 |
-
|
305 |
-
# Define the function to clear the state and input text
|
306 |
-
def clear_transcription_state():
|
307 |
-
return None, ""
|
308 |
|
|
|
|
|
|
|
|
|
|
|
|
|
309 |
|
|
|
|
|
|
|
|
|
310 |
|
311 |
-
with gr.Blocks(
|
312 |
-
chatbot = gr.Chatbot([], elem_id="RADAR", bubble_full_width=False)
|
313 |
with gr.Row():
|
314 |
-
with gr.Column():
|
315 |
-
|
316 |
-
|
317 |
-
label="
|
318 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
319 |
)
|
320 |
with gr.Row():
|
321 |
-
|
322 |
-
|
323 |
-
|
324 |
-
submit_voice_btn = gr.Button("Submit Voice")
|
325 |
-
|
326 |
-
with gr.Column():
|
327 |
-
audio_output = gr.Audio(label="Audio", type="filepath", autoplay=True, interactive=False)
|
328 |
-
|
329 |
-
with gr.Row():
|
330 |
-
with gr.Column():
|
331 |
-
get_response_btn = gr.Button("Get Response")
|
332 |
-
with gr.Column():
|
333 |
-
clear_state_btn = gr.Button("Clear State")
|
334 |
-
with gr.Column():
|
335 |
-
generate_audio_btn = gr.Button("Generate Audio")
|
336 |
-
with gr.Column():
|
337 |
-
clean_btn = gr.Button("Clean")
|
338 |
-
|
339 |
-
|
340 |
-
|
341 |
-
|
342 |
-
|
343 |
-
# Define interactions for the Get Response button
|
344 |
-
get_response_btn.click(
|
345 |
-
fn=handle_mode_selection,
|
346 |
-
inputs=[mode_selection, chatbot, question_input],
|
347 |
-
outputs=[chatbot, question_input, audio_output],
|
348 |
-
api_name="api_add_message_on_button_click"
|
349 |
-
)
|
350 |
-
|
351 |
-
|
352 |
-
|
353 |
-
|
354 |
-
question_input.submit(
|
355 |
-
fn=handle_mode_selection,
|
356 |
-
inputs=[mode_selection, chatbot, question_input],
|
357 |
-
outputs=[chatbot, question_input, audio_output],
|
358 |
-
api_name="api_add_message_on_enter"
|
359 |
-
)
|
360 |
-
|
361 |
-
|
362 |
-
submit_voice_btn.click(
|
363 |
-
fn=handle_mode_selection,
|
364 |
-
inputs=[mode_selection, chatbot, question_input],
|
365 |
-
outputs=[chatbot, question_input, audio_output],
|
366 |
-
api_name="api_voice_to_voice_translation"
|
367 |
-
)
|
368 |
-
|
369 |
-
|
370 |
-
|
371 |
-
# Speech-to-Text functionality
|
372 |
-
state = gr.State()
|
373 |
-
audio_input.stream(
|
374 |
-
transcribe_function,
|
375 |
-
inputs=[state, audio_input],
|
376 |
-
outputs=[state, question_input],
|
377 |
-
api_name="api_voice_to_text"
|
378 |
-
)
|
379 |
-
|
380 |
-
generate_audio_btn.click(
|
381 |
-
fn=generate_audio_from_last_response,
|
382 |
-
inputs=chatbot,
|
383 |
-
outputs=audio_output,
|
384 |
-
api_name="api_generate_text_to_audio"
|
385 |
-
)
|
386 |
-
|
387 |
-
clean_btn.click(
|
388 |
-
fn=clear_fields,
|
389 |
-
inputs=[],
|
390 |
-
outputs=[chatbot, question_input, audio_output],
|
391 |
-
api_name="api_clear_textbox"
|
392 |
-
)
|
393 |
-
|
394 |
-
# Clear state interaction
|
395 |
-
clear_state_btn.click(
|
396 |
-
fn=clear_transcription_state,
|
397 |
-
outputs=[question_input, state],
|
398 |
-
api_name="api_clean_state_transcription"
|
399 |
)
|
400 |
|
401 |
-
|
402 |
-
demo.launch(show_error=True)
|
|
|
|
|
1 |
import os
|
2 |
+
import gradio as gr
|
3 |
+
from langchain_redis import RedisConfig, RedisVectorStore
|
4 |
from langchain_core.output_parsers import StrOutputParser
|
5 |
+
from langchain_core.prompts import ChatPromptTemplate
|
6 |
+
from langchain_core.runnables import RunnablePassthrough
|
7 |
+
from langchain_groq import ChatGroq
|
8 |
+
from langchain_huggingface import HuggingFaceEmbeddings
|
9 |
+
|
10 |
+
|
11 |
+
# Set API keys
|
12 |
+
groq_api_key=os.environ["GROQ_API_KEY"]
|
13 |
+
|
14 |
+
# Define Redis configuration
|
15 |
+
REDIS_URL = "redis://:your_redis_password@redis-11044.c266.us-east-1-3.ec2.redns.redis-cloud.com:11044"
|
16 |
+
config = RedisConfig(
|
17 |
+
index_name="radar_data_index",
|
18 |
+
redis_url=REDIS_URL,
|
19 |
+
metadata_schema=[
|
20 |
+
{"name": "category", "type": "tag"},
|
21 |
+
{"name": "name", "type": "text"},
|
22 |
+
{"name": "address", "type": "text"},
|
23 |
+
{"name": "phone", "type": "text"},
|
24 |
+
],
|
25 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
26 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
27 |
|
28 |
+
# Initialize Hugging Face embeddings
|
29 |
+
embeddings = HuggingFaceEmbeddings(model_name="sentence-transformers/all-mpnet-base-v2")
|
30 |
|
31 |
+
# Initialize Redis Vector Store with Hugging Face embeddings
|
32 |
+
vector_store = RedisVectorStore(embeddings, config=config)
|
33 |
+
retriever = vector_store.as_retriever(search_type="similarity", search_kwargs={"k": 2})
|
|
|
34 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
35 |
|
36 |
+
# Define the language model
|
37 |
+
llm = ChatGroq(model="llama-3.2-1b-preview")
|
38 |
|
39 |
+
# Define prompt
|
40 |
+
prompt = ChatPromptTemplate.from_messages(
|
41 |
+
[
|
42 |
+
(
|
43 |
+
"human",
|
44 |
+
"""You’re Annie, a charming media personality created by Amit Lamba, guiding people around Birmingham, Alabama. Like Rick Steves or Anthony Bourdain, you’re here to give friendly, concise, and accurate advice with a dash of humor.
|
|
|
|
|
|
|
|
|
|
|
45 |
Keep answers relevant, upbeat, and engaging, spotlighting partner businesses whenever possible. Be conversational, like chatting with a clever friend, and encourage follow-up questions to create a smooth flow. Make users smile and deliver a delightful, informative experience—like a perfect dessert after a great meal.
|
46 |
+
Question: {question}
|
47 |
+
Context: {context}
|
48 |
+
Answer:""",
|
49 |
+
),
|
50 |
+
]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
51 |
)
|
52 |
|
53 |
+
def format_docs(docs):
|
54 |
+
return "\n\n".join(doc.page_content for doc in docs)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
55 |
|
56 |
+
rag_chain = (
|
57 |
+
{"context": retriever | format_docs, "question": RunnablePassthrough()}
|
58 |
+
| prompt
|
59 |
+
| llm
|
60 |
+
| StrOutputParser()
|
61 |
+
)
|
62 |
|
63 |
+
# Define the Gradio app
|
64 |
+
def rag_chain_response(question):
|
65 |
+
response = rag_chain.invoke(question)
|
66 |
+
return response
|
67 |
|
68 |
+
with gr.Blocks() as app:
|
|
|
69 |
with gr.Row():
|
70 |
+
with gr.Column(scale=1):
|
71 |
+
user_input = gr.Textbox(
|
72 |
+
placeholder="Type your question here...",
|
73 |
+
label="Your Question",
|
74 |
+
lines=2,
|
75 |
+
max_lines=2,
|
76 |
+
)
|
77 |
+
with gr.Column(scale=2):
|
78 |
+
response_output = gr.Textbox(
|
79 |
+
lines=10,
|
80 |
+
max_lines=10,
|
81 |
)
|
82 |
with gr.Row():
|
83 |
+
submit_btn = gr.Button("Submit")
|
84 |
+
submit_btn.click(
|
85 |
+
rag_chain_response, inputs=user_input, outputs=response_output
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
86 |
)
|
87 |
|
88 |
+
app.launch(show_error=True)
|
|