Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -1,44 +1,123 @@
|
|
|
|
|
|
|
|
|
|
|
|
1 |
import streamlit as st
|
2 |
-
import streamlit as st
|
3 |
-
from openai import OpenAI
|
4 |
import json
|
|
|
|
|
|
|
|
|
5 |
import os
|
6 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
7 |
|
8 |
-
|
9 |
|
10 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
11 |
|
12 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
13 |
|
14 |
-
|
15 |
-
|
|
|
|
|
16 |
|
17 |
|
|
|
18 |
|
19 |
-
|
|
|
20 |
|
|
|
|
|
|
|
21 |
|
|
|
|
|
|
|
|
|
|
|
22 |
|
23 |
-
|
24 |
|
25 |
|
26 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
27 |
if user_input:
|
28 |
-
|
29 |
-
|
30 |
-
|
31 |
-
|
32 |
-
|
33 |
-
|
34 |
-
|
35 |
-
|
36 |
-
|
37 |
-
|
38 |
-
|
39 |
-
|
40 |
-
|
41 |
-
|
42 |
-
|
|
|
|
|
43 |
else:
|
44 |
-
st.
|
|
|
|
1 |
+
from llama_index.core.agent import ReActAgent
|
2 |
+
from llama_index.llms.openai import OpenAI
|
3 |
+
from llama_index.core.tools import FunctionTool
|
4 |
+
from opensearchpy import OpenSearch
|
5 |
+
from gradio_client import Client
|
6 |
import streamlit as st
|
|
|
|
|
7 |
import json
|
8 |
+
import openai
|
9 |
+
import warnings
|
10 |
+
warnings.filterwarnings('ignore')
|
11 |
+
from UI_Config import *
|
12 |
import os
|
13 |
|
14 |
+
openai_api_key = os.getenv("OPENAI_API_KEY")
|
15 |
+
job_id = os.getenv('JOB_ID')
|
16 |
+
user = os.getenv('USERNAME')
|
17 |
+
password = os.getenv('PASSWORD')
|
18 |
+
host = os.getenv('HOST')
|
19 |
+
port = int(os.getenv('PORT'))
|
20 |
+
|
21 |
+
auth = (user,password)
|
22 |
+
|
23 |
+
client = openai.OpenAI(api_key=openai_api_key)
|
24 |
+
|
25 |
+
os_client = OpenSearch(
|
26 |
+
hosts = [{'host': host, 'port': port}],
|
27 |
+
http_auth = auth,
|
28 |
+
use_ssl = True,
|
29 |
+
verify_certs = False
|
30 |
+
)
|
31 |
+
indices = os_client.cat.indices(format="json")
|
32 |
+
list_of_indeces = []
|
33 |
+
for index in indices:
|
34 |
+
list_of_indeces.append(index['index'])
|
35 |
+
|
36 |
+
def rag_app(user_input: str) -> str:
|
37 |
+
gr_client = Client("anasmkh/QdrantVectorStore_Llamaindex")
|
38 |
+
result = gr_client.predict(
|
39 |
+
user_input=user_input,
|
40 |
+
api_name="/chat_with_ai"
|
41 |
+
)
|
42 |
+
return result
|
43 |
|
44 |
+
rag_tool = FunctionTool.from_defaults(fn=rag_app)
|
45 |
|
46 |
+
def query_generator(user_input:str) -> str:
|
47 |
+
job = job_id
|
48 |
+
response = client.fine_tuning.jobs.retrieve(job)
|
49 |
+
completion = client.chat.completions.create(
|
50 |
+
model=response.fine_tuned_model,
|
51 |
+
messages=[
|
52 |
+
{"role": "system", "content": f"""You are a highly skilled assistant trained to translate natural language requests into accurate and efficient OpenSearch JSON queries. Follow a clear, step-by-step process to:
|
53 |
|
54 |
+
Understand the user's request by breaking it down into components such as filters, aggregations, sort criteria, and specific fields.
|
55 |
+
Pay special attention to fields with unique names, such as Date (instead of timestamp) and Stream (instead of type), and ensure they are used correctly in the query.
|
56 |
+
Recognize that the user operates within two main opcos: Zambia and Eswatini, each containing ptm_counters, ptm_events, and multiple streams like ers-daily.
|
57 |
+
Generate a valid JSON query strictly based on the provided indices, ensuring it aligns with the user's prompt. The available indices are: {list_of_indeces}.
|
58 |
+
When generating the query:
|
59 |
+
Be precise and include only necessary fields and components relevant to the request.
|
60 |
+
Assume any unspecified context or detail needs clarification and provide a clear explanation of your assumptions if needed.
|
61 |
+
Optimize the query for OpenSearch performance and readability.
|
62 |
+
Your goal is to provide a query that directly addresses the user's needs while being efficient and valid within the OpenSearch framework."""
|
63 |
|
64 |
+
},
|
65 |
+
{"role": "user", "content": user_input}
|
66 |
+
])
|
67 |
+
return completion.choices[0].message
|
68 |
|
69 |
|
70 |
+
query_tool = FunctionTool.from_defaults(fn=query_generator)
|
71 |
|
72 |
+
llm = OpenAI(model="gpt-3.5-turbo", temperature=0)
|
73 |
+
agent = ReActAgent.from_tools([query_tool,rag_tool], llm=llm, verbose=True)
|
74 |
|
75 |
+
def implement_query(generated_query):
|
76 |
+
try:
|
77 |
+
st.write("Raw Query:", generated_query)
|
78 |
|
79 |
+
if isinstance(generated_query, str):
|
80 |
+
generated_query = generated_query.replace("'", '"')
|
81 |
+
query = json.loads(generated_query)
|
82 |
+
else:
|
83 |
+
query = generated_query
|
84 |
|
85 |
+
st.write("Validated Query:", query)
|
86 |
|
87 |
|
88 |
+
response = os_client.search(body=query)
|
89 |
+
return response
|
90 |
+
except json.JSONDecodeError as e:
|
91 |
+
st.error("Error: The generated query is not valid JSON.")
|
92 |
+
st.write(f"JSONDecodeError Details: {e}")
|
93 |
+
except Exception as e:
|
94 |
+
st.error(f"Error executing OpenSearch query: {e}")
|
95 |
+
st.write(f"Exception Details: {e}")
|
96 |
+
|
97 |
+
|
98 |
+
st.subheader('OpenSearch Assistant')
|
99 |
+
user_input = st.text_input("Enter your query:", "")
|
100 |
+
|
101 |
+
|
102 |
+
if st.button("Submit"):
|
103 |
if user_input:
|
104 |
+
with st.spinner("Processing..."):
|
105 |
+
try:
|
106 |
+
response = agent.chat(user_input)
|
107 |
+
st.success("Query Processed Successfully!")
|
108 |
+
st.subheader("Agent Response:")
|
109 |
+
sources = response.sources
|
110 |
+
for source in sources:
|
111 |
+
st.write('Used Tool: ',source.tool_name)
|
112 |
+
if source.tool_name =='query_generator':
|
113 |
+
st.write(source.raw_output.content)
|
114 |
+
os_response = implement_query(source.raw_output.content)
|
115 |
+
st.subheader('OS Response')
|
116 |
+
st.write(os_response)
|
117 |
+
else:
|
118 |
+
st.write(source.raw_output[0][0][1])
|
119 |
+
except Exception as e:
|
120 |
+
st.error(f"Error: {e}")
|
121 |
else:
|
122 |
+
st.warning("Please enter a query to process.")
|
123 |
+
|