ambrosfitz commited on
Commit
d440c70
1 Parent(s): c7d9064

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +88 -62
app.py CHANGED
@@ -1,63 +1,89 @@
 
 
 
1
  import gradio as gr
2
- from huggingface_hub import InferenceClient
3
-
4
- """
5
- For more information on `huggingface_hub` Inference API support, please check the docs: https://huggingface.co/docs/huggingface_hub/v0.22.2/en/guides/inference
6
- """
7
- client = InferenceClient("HuggingFaceH4/zephyr-7b-beta")
8
-
9
-
10
- def respond(
11
- message,
12
- history: list[tuple[str, str]],
13
- system_message,
14
- max_tokens,
15
- temperature,
16
- top_p,
17
- ):
18
- messages = [{"role": "system", "content": system_message}]
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
- For information on how to customize the ChatInterface, peruse the gradio docs: https://www.gradio.app/docs/chatinterface
44
- """
45
- demo = gr.ChatInterface(
46
- respond,
47
- additional_inputs=[
48
- gr.Textbox(value="You are a friendly Chatbot.", label="System message"),
49
- gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max new tokens"),
50
- gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperature"),
51
- gr.Slider(
52
- minimum=0.1,
53
- maximum=1.0,
54
- value=0.95,
55
- step=0.05,
56
- label="Top-p (nucleus sampling)",
57
- ),
58
- ],
59
- )
60
-
61
-
62
- if __name__ == "__main__":
63
- demo.launch()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ from openai import OpenAI
3
+ import requests
4
  import gradio as gr
5
+
6
+ # Initialize OpenAI client
7
+ client = OpenAI(api_key=os.environ.get("OPENAI_API_KEY"))
8
+
9
+ # Vector database search function
10
+ def search_document(query, k=5):
11
+ url = "http://154.12.226.68:8000/search"
12
+
13
+ payload = {
14
+ "text": query,
15
+ "k": k
16
+ }
17
+
18
+ headers = {
19
+ "Content-Type": "application/json"
20
+ }
21
+
22
+ try:
23
+ response = requests.post(url, json=payload, headers=headers)
24
+ response.raise_for_status()
25
+ return response.json()
26
+ except requests.exceptions.RequestException as e:
27
+ return f"An error occurred: {e}"
28
+
29
+ # Function to query OpenAI
30
+ def query_openai(prompt):
31
+ try:
32
+ response = client.chat.completions.create(
33
+ model="gpt-4o-mini",
34
+ messages=[
35
+ {"role": "system", "content": "You are a helpful assistant. Answer the question based on the provided context."},
36
+ {"role": "user", "content": prompt}
37
+ ]
38
+ )
39
+ return response.choices[0].message.content
40
+ except Exception as e:
41
+ return f"An error occurred while querying OpenAI: {e}"
42
+
43
+ # Function to perform vector search and format results
44
+ def vector_search(query):
45
+ results = search_document(query)
46
+ if isinstance(results, str): # Error occurred
47
+ return results
48
+ if not isinstance(results, dict) or 'results' not in results:
49
+ return "Unexpected format in vector database response."
50
+
51
+ formatted_results = ""
52
+ for i, result in enumerate(results['results'], 1):
53
+ content = result['metadata']['content']
54
+ source = f"Source {i}: {result['metadata'].get('source', 'Unknown source')}, page {result['metadata'].get('page', 'Unknown page')}"
55
+ metadata = ", ".join([f"{k}: {v}" for k, v in result['metadata'].items() if k != 'content'])
56
+ formatted_results += f"{source}\nMetadata: {metadata}\nContent: {content}\n\n"
57
+
58
+ return formatted_results
59
+
60
+ # Combined function for search and query
61
+ def search_and_query(question):
62
+ # First, perform the vector search
63
+ search_results = vector_search(question)
64
+
65
+ # Then, use these results to query OpenAI
66
+ prompt = f"""Given the following context and question, provide a comprehensive and accurate answer. Use ONLY the information provided in the context to answer. If the context doesn't contain relevant information to answer the question, state that clearly.
67
+
68
+ Context:
69
+ {search_results}
70
+
71
+ Question: {question}
72
+
73
+ Answer:"""
74
+
75
+ openai_response = query_openai(prompt)
76
+
77
+ # Return both the search results and the OpenAI response
78
+ return search_results, openai_response
79
+
80
+ # Gradio interface
81
+ with gr.Blocks() as demo:
82
+ question_input = gr.Textbox(label="Enter your question")
83
+ search_output = gr.Textbox(label="Vector Search Results")
84
+ answer_output = gr.Textbox(label="OpenAI Answer")
85
+ query_button = gr.Button("Get Answer")
86
+
87
+ query_button.click(search_and_query, inputs=question_input, outputs=[search_output, answer_output])
88
+
89
+ demo.launch()