ambrosfitz commited on
Commit
566bd19
·
verified ·
1 Parent(s): d3016cd

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +112 -0
app.py ADDED
@@ -0,0 +1,112 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import gradio as gr
3
+ import requests
4
+ import json
5
+ import logging
6
+ from dotenv import load_dotenv
7
+
8
+ # Load environment variables
9
+ load_dotenv()
10
+
11
+ # Cohere API configuration
12
+ COHERE_API_KEY = os.getenv("COHERE_API_KEY")
13
+ if not COHERE_API_KEY:
14
+ raise ValueError("COHERE_API_KEY not found in environment variables")
15
+
16
+ COHERE_API_URL = "https://api.cohere.ai/v1/chat"
17
+ MODEL_NAME = "command-r-08-2024"
18
+
19
+ # Vector database configuration
20
+ API_URL = "https://sendthat.cc"
21
+ HISTORY_INDEX = "textbook"
22
+
23
+ def search_document(query, k):
24
+ try:
25
+ url = f"{API_URL}/search/{HISTORY_INDEX}"
26
+ payload = {"text": query, "k": k}
27
+ headers = {"Content-Type": "application/json"}
28
+ response = requests.post(url, json=payload, headers=headers)
29
+ response.raise_for_status()
30
+ return response.json(), "", k
31
+ except requests.exceptions.RequestException as e:
32
+ logging.error(f"Error in search: {e}")
33
+ return {"error": str(e)}, query, k
34
+
35
+ def generate_answer(question, context, citations):
36
+ prompt = f"Context: {context}\n\nQuestion: {question}\n\nAnswer the question based on the given context. At the end of your answer, provide citations for the sources you used, referencing them as [1], [2], etc.:"
37
+
38
+ headers = {
39
+ "Authorization": f"Bearer {COHERE_API_KEY}",
40
+ "Content-Type": "application/json"
41
+ }
42
+
43
+ payload = {
44
+ "message": prompt,
45
+ "model": MODEL_NAME,
46
+ "preamble": "You are an AI-assistant chatbot. You are trained to assist users by providing thorough and helpful responses to their queries based on the given context. Always include citations at the end of your answer.",
47
+ "chat_history": [] # You can add chat history here if needed
48
+ }
49
+
50
+ try:
51
+ response = requests.post(COHERE_API_URL, headers=headers, json=payload)
52
+ response.raise_for_status()
53
+ answer = response.json()['text']
54
+
55
+ # Append citations to the answer
56
+ answer += "\n\nSources:"
57
+ for i, citation in enumerate(citations, 1):
58
+ answer += f"\n[{i}] {citation}"
59
+
60
+ return answer
61
+ except requests.exceptions.RequestException as e:
62
+ logging.error(f"Error in generate_answer: {e}")
63
+ return f"An error occurred: {str(e)}"
64
+
65
+ def answer_question(question, k=3):
66
+ # Search the vector database
67
+ search_results, _, _ = search_document(question, k)
68
+
69
+ # Extract and combine the retrieved contexts
70
+ if "results" in search_results:
71
+ contexts = []
72
+ citations = []
73
+ for item in search_results['results']:
74
+ contexts.append(item['metadata']['content'])
75
+ citations.append(f"{item['metadata'].get('title', 'Unknown Source')} - {item['metadata'].get('source', 'No source provided')}")
76
+ combined_context = " ".join(contexts)
77
+ else:
78
+ logging.error(f"Error in database search or no results found: {search_results}")
79
+ combined_context = ""
80
+ citations = []
81
+
82
+ # Generate answer using the Cohere LLM
83
+ answer = generate_answer(question, combined_context, citations)
84
+ return answer
85
+
86
+ def chatbot(message, history):
87
+ response = answer_question(message)
88
+ return response
89
+
90
+ # Create Gradio interface
91
+ iface = gr.ChatInterface(
92
+ chatbot,
93
+ chatbot=gr.Chatbot(height=300),
94
+ textbox=gr.Textbox(placeholder="Ask a question about history...", container=False, scale=7),
95
+ title="History Chatbot",
96
+ description="Ask me anything about history, and I'll provide answers with citations!",
97
+ theme="soft",
98
+ examples=[
99
+ "Why was Anne Hutchinson banished from Massachusetts?",
100
+ "What were the major causes of World War I?",
101
+ "Who was the first President of the United States?",
102
+ "What was the significance of the Industrial Revolution?"
103
+ ],
104
+ cache_examples=False,
105
+ retry_btn=None,
106
+ undo_btn="Delete Previous",
107
+ clear_btn="Clear",
108
+ )
109
+
110
+ # Launch the app
111
+ if __name__ == "__main__":
112
+ iface.launch()