forked from Shubhamsaboo/awesome-llm-apps
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrag_app.py
More file actions
190 lines (160 loc) · 7.65 KB
/
rag_app.py
File metadata and controls
190 lines (160 loc) · 7.65 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
import streamlit as st
import requests
from anthropic import Anthropic
import time
from typing import List, Dict, Optional
from urllib.parse import urlparse
class RAGPipeline:
def __init__(self, ragie_api_key: str, anthropic_api_key: str):
"""
Initialize the RAG pipeline with API keys.
"""
self.ragie_api_key = ragie_api_key
self.anthropic_api_key = anthropic_api_key
self.anthropic_client = Anthropic(api_key=anthropic_api_key)
# API endpoints
self.RAGIE_UPLOAD_URL = "https://api.ragie.ai/documents/url"
self.RAGIE_RETRIEVAL_URL = "https://api.ragie.ai/retrievals"
def upload_document(self, url: str, name: Optional[str] = None, mode: str = "fast") -> Dict:
"""
Upload a document to Ragie from a URL.
"""
if not name:
name = urlparse(url).path.split('/')[-1] or "document"
payload = {
"mode": mode,
"name": name,
"url": url
}
headers = {
"accept": "application/json",
"content-type": "application/json",
"authorization": f"Bearer {self.ragie_api_key}"
}
response = requests.post(self.RAGIE_UPLOAD_URL, json=payload, headers=headers)
if not response.ok:
raise Exception(f"Document upload failed: {response.status_code} {response.reason}")
return response.json()
def retrieve_chunks(self, query: str, scope: str = "tutorial") -> List[str]:
"""
Retrieve relevant chunks from Ragie for a given query.
"""
headers = {
"Content-Type": "application/json",
"Authorization": f"Bearer {self.ragie_api_key}"
}
payload = {
"query": query,
"filters": {
"scope": scope
}
}
response = requests.post(
self.RAGIE_RETRIEVAL_URL,
headers=headers,
json=payload
)
if not response.ok:
raise Exception(f"Retrieval failed: {response.status_code} {response.reason}")
data = response.json()
return [chunk["text"] for chunk in data["scored_chunks"]]
def create_system_prompt(self, chunk_texts: List[str]) -> str:
"""
Create the system prompt with the retrieved chunks.
"""
return f"""These are very important to follow: You are "Ragie AI", a professional but friendly AI chatbot working as an assistant to the user. Your current task is to help the user based on all of the information available to you shown below. Answer informally, directly, and concisely without a heading or greeting but include everything relevant. Use richtext Markdown when appropriate including bold, italic, paragraphs, and lists when helpful. If using LaTeX, use double $$ as delimiter instead of single $. Use $$...$$ instead of parentheses. Organize information into multiple sections or points when appropriate. Don't include raw item IDs or other raw fields from the source. Don't use XML or other markup unless requested by the user. Here is all of the information available to answer the user: === {chunk_texts} === If the user asked for a search and there are no results, make sure to let the user know that you couldn't find anything, and what they might be able to do to find the information they need. END SYSTEM INSTRUCTIONS"""
def generate_response(self, system_prompt: str, query: str) -> str:
"""
Generate response using Claude 3.5 Sonnet.
"""
message = self.anthropic_client.messages.create(
model="claude-3-sonnet-20240229",
max_tokens=1024,
system=system_prompt,
messages=[
{
"role": "user",
"content": query
}
]
)
return message.content[0].text
def process_query(self, query: str, scope: str = "tutorial") -> str:
"""
Process a query through the complete RAG pipeline.
"""
chunks = self.retrieve_chunks(query, scope)
if not chunks:
return "No relevant information found for your query."
system_prompt = self.create_system_prompt(chunks)
return self.generate_response(system_prompt, query)
def initialize_session_state():
"""Initialize session state variables."""
if 'pipeline' not in st.session_state:
st.session_state.pipeline = None
if 'document_uploaded' not in st.session_state:
st.session_state.document_uploaded = False
if 'api_keys_submitted' not in st.session_state:
st.session_state.api_keys_submitted = False
def main():
st.set_page_config(page_title="RAG-as-a-Service", layout="wide")
initialize_session_state()
st.title(":linked_paperclips: RAG-as-a-Service")
# API Keys Section
with st.expander("🔑 API Keys Configuration", expanded=not st.session_state.api_keys_submitted):
col1, col2 = st.columns(2)
with col1:
ragie_key = st.text_input("Ragie API Key", type="password", key="ragie_key")
with col2:
anthropic_key = st.text_input("Anthropic API Key", type="password", key="anthropic_key")
if st.button("Submit API Keys"):
if ragie_key and anthropic_key:
try:
st.session_state.pipeline = RAGPipeline(ragie_key, anthropic_key)
st.session_state.api_keys_submitted = True
st.success("API keys configured successfully!")
except Exception as e:
st.error(f"Error configuring API keys: {str(e)}")
else:
st.error("Please provide both API keys.")
# Document Upload Section
if st.session_state.api_keys_submitted:
st.markdown("### 📄 Document Upload")
doc_url = st.text_input("Enter document URL")
doc_name = st.text_input("Document name (optional)")
col1, col2 = st.columns([1, 3])
with col1:
upload_mode = st.selectbox("Upload mode", ["fast", "accurate"])
if st.button("Upload Document"):
if doc_url:
try:
with st.spinner("Uploading document..."):
st.session_state.pipeline.upload_document(
url=doc_url,
name=doc_name if doc_name else None,
mode=upload_mode
)
time.sleep(5) # Wait for indexing
st.session_state.document_uploaded = True
st.success("Document uploaded and indexed successfully!")
except Exception as e:
st.error(f"Error uploading document: {str(e)}")
else:
st.error("Please provide a document URL.")
# Query Section
if st.session_state.document_uploaded:
st.markdown("### 🔍 Query Document")
query = st.text_input("Enter your query")
if st.button("Generate Response"):
if query:
try:
with st.spinner("Generating response..."):
response = st.session_state.pipeline.process_query(query)
st.markdown("### Response:")
st.markdown(response)
except Exception as e:
st.error(f"Error generating response: {str(e)}")
else:
st.error("Please enter a query.")
if __name__ == "__main__":
main()