-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathstreamlit.py
193 lines (163 loc) · 6.85 KB
/
streamlit.py
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
191
192
193
import streamlit as st
import json
import _snowflake
from snowflake.snowpark.context import get_active_session
session = get_active_session()
API_ENDPOINT = "/api/v2/cortex/agent:run"
API_TIMEOUT = 50000 # in milliseconds
CORTEX_SEARCH_SERVICES = "sales_intelligence.data.sales_conversation_search"
SEMANTIC_MODELS = "@sales_intelligence.data.models/sales_metrics_model.yaml"
def run_snowflake_query(query):
try:
df = session.sql(query.replace(';',''))
return df
except Exception as e:
st.error(f"Error executing SQL: {str(e)}")
return None, None
def snowflake_api_call(query: str, limit: int = 10):
payload = {
"model": "llama3.1-70b",
"messages": [
{
"role": "user",
"content": [
{
"type": "text",
"text": query
}
]
}
],
"tools": [
{
"tool_spec": {
"type": "cortex_analyst_text_to_sql",
"name": "analyst1"
}
},
{
"tool_spec": {
"type": "cortex_search",
"name": "search1"
}
}
],
"tool_resources": {
"analyst1": {"semantic_model_file": SEMANTIC_MODELS},
"search1": {
"name": CORTEX_SEARCH_SERVICES,
"max_results": limit,
"id_column": "conversation_id"
}
}
}
try:
resp = _snowflake.send_snow_api_request(
"POST", # method
API_ENDPOINT, # path
{}, # headers
{}, # params
payload, # body
None, # request_guid
API_TIMEOUT, # timeout in milliseconds,
)
if resp["status"] != 200:
st.error(f"❌ HTTP Error: {resp['status']} - {resp.get('reason', 'Unknown reason')}")
st.error(f"Response details: {resp}")
return None
try:
response_content = json.loads(resp["content"])
except json.JSONDecodeError:
st.error("❌ Failed to parse API response. The server may have returned an invalid JSON format.")
st.error(f"Raw response: {resp['content'][:200]}...")
return None
return response_content
except Exception as e:
st.error(f"Error making request: {str(e)}")
return None
def process_sse_response(response):
"""Process SSE response"""
text = ""
sql = ""
citations = []
if not response:
return text, sql, citations
if isinstance(response, str):
return text, sql, citations
try:
for event in response:
if event.get('event') == "message.delta":
data = event.get('data', {})
delta = data.get('delta', {})
for content_item in delta.get('content', []):
content_type = content_item.get('type')
if content_type == "tool_results":
tool_results = content_item.get('tool_results', {})
if 'content' in tool_results:
for result in tool_results['content']:
if result.get('type') == 'json':
text += result.get('json', {}).get('text', '')
search_results = result.get('json', {}).get('searchResults', [])
for search_result in search_results:
citations.append({'source_id':search_result.get('source_id',''), 'doc_id':search_result.get('doc_id', '')})
sql = result.get('json', {}).get('sql', '')
if content_type == 'text':
text += content_item.get('text', '')
except json.JSONDecodeError as e:
st.error(f"Error processing events: {str(e)}")
except Exception as e:
st.error(f"Error processing events: {str(e)}")
return text, sql, citations
def main():
st.title("Intelligent Sales Assistant")
# Sidebar for new chat
with st.sidebar:
if st.button("New Conversation", key="new_chat"):
st.session_state.messages = []
st.rerun()
# Initialize session state
if 'messages' not in st.session_state:
st.session_state.messages = []
for message in st.session_state.messages:
with st.chat_message(message['role']):
st.markdown(message['content'].replace("•", "\n\n"))
if query := st.chat_input("Would you like to learn?"):
# Add user message to chat
with st.chat_message("user"):
st.markdown(query)
st.session_state.messages.append({"role": "user", "content": query})
# Get response from API
with st.spinner("Processing your request..."):
response = snowflake_api_call(query, 1)
text, sql, citations = process_sse_response(response)
# Add assistant response to chat
if text:
text = text.replace("【†", "[")
text = text.replace("†】", "]")
st.session_state.messages.append({"role": "assistant", "content": text})
with st.chat_message("assistant"):
st.markdown(text.replace("•", "\n\n"))
if citations:
st.write("Citations:")
for citation in citations:
doc_id = citation.get("doc_id", "")
if doc_id:
query = f"SELECT transcript_text FROM sales_conversations WHERE conversation_id = '{doc_id}'"
result = run_snowflake_query(query)
result_df = result.to_pandas()
if not result_df.empty:
transcript_text = result_df.iloc[0, 0]
else:
transcript_text = "No transcript available"
with st.expander(f"[{citation.get('source_id', '')}]"):
st.write(transcript_text)
# Display SQL if present
if sql:
st.markdown("### Generated SQL")
st.code(sql, language="sql")
sales_results = run_snowflake_query(sql)
if sales_results:
st.write("### Sales Metrics Report")
st.dataframe(sales_results)
if __name__ == "__main__":
main()