-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcortex_chat.py
180 lines (159 loc) · 6.42 KB
/
cortex_chat.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
import requests
import json
DEBUG = False
class CortexChat:
def __init__(self,
agent_url: str,
search_service: str,
semantic_model: str,
model: str,
jwt: str
):
self.agent_url = agent_url
self.model = model
self.search_service = search_service
self.semantic_model = semantic_model
self.jwt = jwt
def _retrieve_response(self, query: str, limit=1) -> dict[str, any]:
url = self.agent_url
headers = {
'X-Snowflake-Authorization-Token-Type': 'KEYPAIR_JWT',
'Content-Type': 'application/json',
'Accept': 'application/json',
'Authorization': f"Bearer {self.jwt}"
}
data = {
"model": self.model,
"messages": [
{
"role": "user",
"content": [
{
"type": "text",
"text": query
}
]
}
],
"tools": [
{
"tool_spec": {
"type": "cortex_search",
"name": "vehicles_info_search"
}
},
{
"tool_spec": {
"type": "cortex_analyst_text_to_sql",
"name": "supply_chain"
}
}
],
"tool_resources": {
"vehicles_info_search": {
"name": self.search_service,
"max_results": limit,
"title_column": "title",
"id_column": "relative_path",
},
"supply_chain": {
"semantic_model_file": self.semantic_model
}
},
}
response = requests.post(url, headers=headers, json=data)
if DEBUG:
print(response.text)
if response.status_code == 200:
return self._parse_response(response)
else:
print(f"Error: Received status code {response.status_code}")
return {"text": response.text}
def _parse_delta_content(self,content: list) -> dict[str, any]:
"""Parse different types of content from the delta."""
result = {
'text': '',
'tool_use': [],
'tool_results': []
}
for entry in content:
entry_type = entry.get('type')
if entry_type == 'text':
result['text'] += entry.get('text', '')
elif entry_type == 'tool_use':
result['tool_use'].append(entry.get('tool_use', {}))
elif entry_type == 'tool_results':
result['tool_results'].append(entry.get('tool_results', {}))
return result
def _process_sse_line(self,line: str) -> dict[str, any]:
"""Process a single SSE line and return parsed content."""
if not line.startswith('data: '):
return {}
try:
json_str = line[6:].strip() # Remove 'data: ' prefix
if json_str == '[DONE]':
return {'type': 'done'}
data = json.loads(json_str)
if data.get('object') == 'message.delta':
delta = data.get('delta', {})
if 'content' in delta:
return {
'type': 'message',
'content': self._parse_delta_content(delta['content'])
}
return {'type': 'other', 'data': data}
except json.JSONDecodeError:
return {'type': 'error', 'message': f'Failed to parse: {line}'}
def _parse_response(self,response: requests.Response) -> dict[str, any]:
"""Parse and print the SSE chat response with improved organization."""
accumulated = {
'text': '',
'tool_use': [],
'tool_results': [],
'other': []
}
for line in response.iter_lines():
if line:
result = self._process_sse_line(line.decode('utf-8'))
if result.get('type') == 'message':
content = result['content']
accumulated['text'] += content['text']
accumulated['tool_use'].extend(content['tool_use'])
accumulated['tool_results'].extend(content['tool_results'])
elif result.get('type') == 'other':
accumulated['other'].append(result['data'])
text = ''
sql = ''
citations = ''
if accumulated['text']:
text = accumulated['text']
if DEBUG:
print("\n=== Complete Response ===")
print("\n--- Generated Text ---")
print(text)
if accumulated['tool_use']:
print("\n--- Tool Usage ---")
print(json.dumps(accumulated['tool_use'], indent=2))
if accumulated['other']:
print("\n--- Other Messages ---")
print(json.dumps(accumulated['other'], indent=2))
if accumulated['tool_results']:
print("\n--- Tool Results ---")
print(json.dumps(accumulated['tool_results'], indent=2))
if accumulated['tool_results']:
for result in accumulated['tool_results']:
for k,v in result.items():
if k == 'content':
for content in v:
if 'sql' in content['json']:
sql = content['json']['sql']
elif 'searchResults' in content['json']:
search_results = content['json']['searchResults']
for search_result in search_results:
citations += f"{search_result['text']}"
text = text.replace("【†1†】","").replace("【†2†】","").replace("【†3†】","").replace(" .",".") + "*"
citations = f"{search_result['doc_title']} \n {citations} \n\n[Source: {search_result['doc_id']}]"
return {"text": text, "sql": sql, "citations": citations}
def chat(self, query: str) -> any:
response = self._retrieve_response(query)
return response