yalrashed commited on
Commit
07f9509
·
verified ·
1 Parent(s): e76bea7

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +51 -68
app.py CHANGED
@@ -2,15 +2,22 @@ import gradio as gr
2
  import os
3
  import json
4
  import requests
5
- import openai
6
 
7
- # Set OpenAI API key
8
- openai.api_key = os.getenv('OPENAI_API_KEY')
9
  ragie_api_key = os.getenv('RAGIE_API_KEY')
10
 
11
- def get_ragie_chunks(query):
12
- """Retrieve chunks using Ragie's documented method"""
13
  try:
 
 
 
 
 
 
 
 
 
14
  response = requests.post(
15
  "https://api.ragie.ai/retrievals",
16
  headers={
@@ -20,81 +27,57 @@ def get_ragie_chunks(query):
20
  json={
21
  "query": query,
22
  "filter": {
23
- "scope": "tutorial" # Adjust this to match your Ragie scope
24
  }
25
  }
26
  )
27
 
 
 
 
 
28
  if response.status_code != 200:
29
- print(f"Ragie API error: {response.status_code}")
30
- return []
 
 
 
 
 
 
 
 
31
 
 
32
  data = response.json()
33
- return [chunk["text"] for chunk in data.get("scored_chunks", [])]
34
- except Exception as e:
35
- print(f"Error getting chunks: {str(e)}")
36
- return []
37
-
38
- def create_system_prompt(chunks):
39
- """Create system prompt following Ragie's format"""
40
- return f"""These are very important to follow:
41
- You are "Ragie AI", a professional but friendly AI chatbot working as an assistant.
42
- Your current task is to help the user based on all of the information available to you.
43
- Answer informally, directly, and concisely without a heading or greeting but include details.
44
- Use richtext Markdown when appropriate including bold, italic, paragraphs, and lists.
45
- If using LaTeX, use double $$ as delimiter instead of single $. Use $$....$$ instead of $..$$.
46
- Organize information into multiple sections or points when appropriate.
47
- Don't include raw item IDs or other raw fields from the source.
48
- Don't use XML or other markup unless requested by the user.
49
-
50
- Here is all of the information available to answer the user:
51
- ===
52
- {chr(10).join(chunks)}
53
- ===
54
-
55
- If the user asked for a search and there are no results, make sure to let the user know
56
- and what they might be able to do to find the information they need."""
57
-
58
- def respond(message, history):
59
- """Main response function following Ragie's integration approach"""
60
- try:
61
- # Get chunks from Ragie using their method
62
- chunks = get_ragie_chunks(message)
63
 
64
- # Create messages array following their format
65
- messages = [{"role": "system", "content": create_system_prompt(chunks)}]
66
-
67
- # Add conversation history
68
- for human, assistant in history:
69
- messages.append({"role": "user", "content": human})
70
- messages.append({"role": "assistant", "content": assistant})
 
 
 
 
71
 
72
- # Add current message
73
- messages.append({"role": "user", "content": message})
74
 
75
- # Get streaming response from OpenAI
76
- response = ""
77
- for chunk in openai.ChatCompletion.create(
78
- model="gpt-3.5-turbo",
79
- messages=messages,
80
- temperature=0.7,
81
- stream=True
82
- ):
83
- if hasattr(chunk.choices[0].delta, 'content'):
84
- content = chunk.choices[0].delta.content
85
- if content is not None:
86
- response += content
87
- yield response
88
-
89
  except Exception as e:
90
- print(f"Error in respond: {str(e)}")
91
- yield f"I apologize, but I encountered an error: {str(e)}"
 
92
 
93
- # Create the Gradio interface
94
- demo = gr.ChatInterface(
95
- respond,
96
- title="Ragie-Powered Chatbot",
97
- description="A chatbot that combines Ragie's retrieval system with OpenAI's language capabilities."
 
 
98
  )
99
 
100
  if __name__ == "__main__":
 
2
  import os
3
  import json
4
  import requests
 
5
 
6
+ # Get Ragie API key
 
7
  ragie_api_key = os.getenv('RAGIE_API_KEY')
8
 
9
+ def get_chunks(query):
10
+ """Retrieve chunks with detailed API response checking"""
11
  try:
12
+ # Print API key status (safely)
13
+ if ragie_api_key:
14
+ print("API key found")
15
+ else:
16
+ return "Error: No Ragie API key found in environment variables"
17
+
18
+ print(f"\nSending query: {query}")
19
+
20
+ # Make the API call
21
  response = requests.post(
22
  "https://api.ragie.ai/retrievals",
23
  headers={
 
27
  json={
28
  "query": query,
29
  "filter": {
30
+ "scope": "tutorial" # Adjust this to match your scope
31
  }
32
  }
33
  )
34
 
35
+ # Print full response details
36
+ print(f"\nAPI Response Status: {response.status_code}")
37
+ print(f"Response Headers: {dict(response.headers)}")
38
+
39
  if response.status_code != 200:
40
+ error_detail = ""
41
+ try:
42
+ error_detail = response.json()
43
+ print(f"Error Response Body: {error_detail}")
44
+ except:
45
+ error_detail = response.text
46
+ print(f"Error Response Text: {error_detail}")
47
+ return f"""API Call Failed:
48
+ Status Code: {response.status_code}
49
+ Error Details: {error_detail}"""
50
 
51
+ # Parse the successful response
52
  data = response.json()
53
+ print(f"\nFound {len(data.get('scored_chunks', []))} chunks")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
54
 
55
+ # Format the chunks with API response info
56
+ result = f"""API Call Successful:
57
+ Status Code: {response.status_code}
58
+ Number of Chunks: {len(data.get('scored_chunks', []))}
59
+
60
+ Retrieved Chunks:
61
+ """
62
+ for i, chunk in enumerate(data.get("scored_chunks", []), 1):
63
+ result += f"\nChunk {i} (Score: {chunk['score']}):\n"
64
+ result += f"{chunk['text']}\n"
65
+ result += "-" * 50
66
 
67
+ return result if data.get("scored_chunks") else "API call successful but no chunks were found for this query."
 
68
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
69
  except Exception as e:
70
+ error_msg = f"Error during API call: {str(e)}"
71
+ print(error_msg)
72
+ return error_msg
73
 
74
+ # Create a simple interface
75
+ demo = gr.Interface(
76
+ fn=get_chunks,
77
+ inputs=gr.Textbox(label="Enter your query"),
78
+ outputs=gr.Textbox(label="API Response and Retrieved Chunks", lines=20),
79
+ title="Ragie Chunk Retriever with API Debugging",
80
+ description="Enter a query to see full API response details and retrieved chunks."
81
  )
82
 
83
  if __name__ == "__main__":