forked from GoogleCloudPlatform/dfcx-scrapi
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathconversation_history.py
156 lines (123 loc) · 5.49 KB
/
conversation_history.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
"""Conversation History class for Generative Agents."""
# Copyright 2024 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import json
import logging
import os
from typing import Dict, List, Any
from tqdm.contrib.concurrent import thread_map
from google.cloud.dialogflowcx_v3beta1 import services
from google.cloud.dialogflowcx_v3beta1 import types
from dfcx_scrapi.core import scrapi_base
# logging config
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s %(levelname)-8s %(message)s",
datefmt="%Y-%m-%d %H:%M:%S",
)
class ConversationHistory(scrapi_base.ScrapiBase):
"""Used to get Conversation History Data."""
def __init__(self,
creds_path: str = None,
creds_dict: Dict[str,str] = None,
creds = None,
scope = False,
agent_id: str = None):
super().__init__(creds_path, creds_dict, creds, scope)
self.agent_id = agent_id
@staticmethod
def get_user_input(query_input: types.QueryInput):
"""Extract the input from the user."""
if "text" in query_input:
return query_input.text.text
else:
return None
@staticmethod
def get_query_result(query_result: types.QueryResult):
"""Extract the query result from the agent."""
messages = []
if "response_messages" in query_result:
for rm in query_result.response_messages:
if "text" in rm:
messages.append(rm.text.text[0])
return " ".join(messages)
def list_conversations(self, agent_id: str):
request = types.conversation_history.ListConversationsRequest(
parent=agent_id)
client_options = self._set_region(agent_id)
client = services.conversation_history.ConversationHistoryClient(
credentials=self.creds, client_options=client_options)
return list(client.list_conversations(request))
def get_conversation(self, conversation_id: str):
request = types.conversation_history.GetConversationRequest(
name=conversation_id)
client_options = self._set_region(conversation_id)
client = services.conversation_history.ConversationHistoryClient(
credentials=self.creds, client_options=client_options)
return client.get_conversation(request)
def delete_conversation(self, conversation_id: str) -> None:
request = types.conversation_history.DeleteConversationRequest(
name=conversation_id
)
client_options = self._set_region(conversation_id)
client = services.conversation_history.ConversationHistoryClient(
credentials=self.creds, client_options=client_options
)
client.delete_conversation(request)
def process_single_conversation(self, current_convo: types.Conversation):
"""Extract details from single conversation for embed and cluster."""
conversation = {}
conversation["session_id"] = current_convo.name
conversation["create_time"] = current_convo.start_time.rfc3339()
conversation["turns"] = []
for action in reversed(current_convo.interactions):
turn = {}
turn["user"] = self.get_user_input(action.request.query_input)
turn["agent"] = self.get_query_result(action.response.query_result)
conversation["turns"].append(turn)
return conversation
def write_conversations_to_file(
self, convos: List[Dict[str, Any]], filename: str
):
"""Write conversations to file."""
# Check if the file exists
if not os.path.exists(filename):
# If not, create an empty file
with open(filename, "w", encoding="utf-8") as new_file:
new_file.close()
with open(filename, "w", encoding="utf-8") as json_file:
for data_dict in convos:
json.dump(data_dict, json_file)
json_file.write("\n")
def read_conversations_from_file(self, filename: str):
"""Loads a JSON Lines file and returns a list of dictionaries."""
data = []
with open(filename, "r", encoding="utf-8") as f:
for line in f:
data.append(json.loads(line))
return data
def conversation_history_to_file(self, agent_id: str, filename: str):
"""Process existing conversation history, with progress bar."""
convo_ids = [convo.name for convo in self.list_conversations(agent_id)]
def process_conversation(conversation_id: str):
"""Helper method to process single convo."""
current_convo = self.get_conversation(conversation_id)
return self.process_single_conversation(current_convo)
# Use thread_map for progress visualization during parallel processing
results = thread_map(
process_conversation,
convo_ids,
desc="Processing Conversations"
)
self.write_conversations_to_file(list(results), filename)