cwyodmodules 0.3.32__py3-none-any.whl → 0.3.33__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (46) hide show
  1. cwyodmodules/api/chat_history.py +14 -7
  2. cwyodmodules/batch/utilities/chat_history/auth_utils.py +7 -3
  3. cwyodmodules/batch/utilities/chat_history/cosmosdb.py +17 -1
  4. cwyodmodules/batch/utilities/chat_history/postgresdbservice.py +239 -254
  5. cwyodmodules/batch/utilities/common/source_document.py +60 -61
  6. cwyodmodules/batch/utilities/document_chunking/fixed_size_overlap.py +8 -3
  7. cwyodmodules/batch/utilities/document_chunking/layout.py +8 -3
  8. cwyodmodules/batch/utilities/document_chunking/page.py +8 -3
  9. cwyodmodules/batch/utilities/document_loading/read.py +30 -34
  10. cwyodmodules/batch/utilities/helpers/azure_computer_vision_client.py +10 -3
  11. cwyodmodules/batch/utilities/helpers/azure_form_recognizer_helper.py +6 -2
  12. cwyodmodules/batch/utilities/helpers/azure_postgres_helper.py +14 -2
  13. cwyodmodules/batch/utilities/helpers/azure_postgres_helper_light_rag.py +14 -2
  14. cwyodmodules/batch/utilities/helpers/azure_search_helper.py +15 -6
  15. cwyodmodules/batch/utilities/helpers/config/config_helper.py +24 -2
  16. cwyodmodules/batch/utilities/helpers/env_helper.py +9 -9
  17. cwyodmodules/batch/utilities/helpers/lightrag_helper.py +9 -2
  18. cwyodmodules/batch/utilities/helpers/llm_helper.py +13 -2
  19. cwyodmodules/batch/utilities/helpers/secret_helper.py +9 -9
  20. cwyodmodules/batch/utilities/integrated_vectorization/azure_search_index.py +8 -2
  21. cwyodmodules/batch/utilities/integrated_vectorization/azure_search_indexer.py +9 -2
  22. cwyodmodules/batch/utilities/integrated_vectorization/azure_search_skillset.py +6 -2
  23. cwyodmodules/batch/utilities/orchestrator/lang_chain_agent.py +8 -2
  24. cwyodmodules/batch/utilities/orchestrator/open_ai_functions.py +6 -2
  25. cwyodmodules/batch/utilities/orchestrator/orchestrator_base.py +9 -3
  26. cwyodmodules/batch/utilities/orchestrator/prompt_flow.py +8 -2
  27. cwyodmodules/batch/utilities/orchestrator/semantic_kernel_orchestrator.py +135 -138
  28. cwyodmodules/batch/utilities/parser/output_parser_tool.py +64 -64
  29. cwyodmodules/batch/utilities/plugins/outlook_calendar_plugin.py +91 -93
  30. cwyodmodules/batch/utilities/search/azure_search_handler.py +16 -3
  31. cwyodmodules/batch/utilities/search/azure_search_handler_light_rag.py +14 -2
  32. cwyodmodules/batch/utilities/search/integrated_vectorization_search_handler.py +36 -24
  33. cwyodmodules/batch/utilities/search/lightrag_search_handler.py +14 -2
  34. cwyodmodules/batch/utilities/search/postgres_search_handler.py +100 -97
  35. cwyodmodules/batch/utilities/search/postgres_search_handler_light_rag.py +103 -104
  36. cwyodmodules/batch/utilities/search/search.py +21 -24
  37. cwyodmodules/batch/utilities/tools/content_safety_checker.py +66 -78
  38. cwyodmodules/batch/utilities/tools/post_prompt_tool.py +48 -60
  39. cwyodmodules/batch/utilities/tools/question_answer_tool.py +196 -206
  40. cwyodmodules/batch/utilities/tools/text_processing_tool.py +36 -39
  41. cwyodmodules/logging_config.py +15 -0
  42. {cwyodmodules-0.3.32.dist-info → cwyodmodules-0.3.33.dist-info}/METADATA +2 -1
  43. {cwyodmodules-0.3.32.dist-info → cwyodmodules-0.3.33.dist-info}/RECORD +46 -45
  44. {cwyodmodules-0.3.32.dist-info → cwyodmodules-0.3.33.dist-info}/WHEEL +0 -0
  45. {cwyodmodules-0.3.32.dist-info → cwyodmodules-0.3.33.dist-info}/licenses/LICENSE +0 -0
  46. {cwyodmodules-0.3.32.dist-info → cwyodmodules-0.3.33.dist-info}/top_level.txt +0 -0
@@ -3,14 +3,11 @@ from datetime import datetime, timezone
3
3
  from ..helpers.azure_identity_helper import AzureIdentityHelper
4
4
  from .database_client_base import DatabaseClientBase
5
5
 
6
- from logging import getLogger
7
- from opentelemetry import trace, baggage
8
- from opentelemetry.propagate import extract
9
-
10
- # logger = getLogger("__main__" + ".base_package")
11
- logger = getLogger("__main__")
12
- # tracer = trace.get_tracer("__main__" + ".base_package")
13
- tracer = trace.get_tracer("__main__")
6
+ from ...utilities.helpers.env_helper import EnvHelper
7
+ from logging_config import logger
8
+ env_helper: EnvHelper = EnvHelper()
9
+ log_args = env_helper.LOG_ARGS
10
+ log_result = env_helper.LOG_RESULT
14
11
 
15
12
 
16
13
  class PostgresConversationClient(DatabaseClientBase):
@@ -25,282 +22,270 @@ class PostgresConversationClient(DatabaseClientBase):
25
22
  self.enable_message_feedback = enable_message_feedback
26
23
  self.conn = None
27
24
 
25
+ @logger.trace_function(log_args=log_args, log_result=log_result)
28
26
  async def connect(self):
29
- with tracer.start_as_current_span("PostgresConversationClient.connect"):
30
- try:
31
- access_information = self.azure_identity_helper.get_token(scopes="https://ossrdbms-aad.database.windows.net/.default")
32
- token = access_information.token
33
- self.conn = await asyncpg.connect(
34
- user=self.user,
35
- host=self.host,
36
- database=self.database,
37
- password=token,
38
- port=5432,
39
- ssl="require",
40
- )
41
- logger.info("Successfully connected to PostgreSQL")
42
- except Exception as e:
43
- logger.error("Failed to connect to PostgreSQL: %s", e, exc_info=True)
44
- raise
27
+ try:
28
+ access_information = self.azure_identity_helper.get_token(scopes="https://ossrdbms-aad.database.windows.net/.default")
29
+ token = access_information.token
30
+ self.conn = await asyncpg.connect(
31
+ user=self.user,
32
+ host=self.host,
33
+ database=self.database,
34
+ password=token,
35
+ port=5432,
36
+ ssl="require",
37
+ )
38
+ logger.info("Successfully connected to PostgreSQL")
39
+ except Exception as e:
40
+ logger.error("Failed to connect to PostgreSQL: %s", e, exc_info=True)
41
+ raise
45
42
 
43
+ @logger.trace_function(log_args=log_args, log_result=log_result)
46
44
  async def close(self):
47
- with tracer.start_as_current_span("PostgresConversationClient.close"):
48
- if self.conn:
49
- await self.conn.close()
50
- logger.info("PostgreSQL connection closed")
45
+ if self.conn:
46
+ await self.conn.close()
47
+ logger.info("PostgreSQL connection closed")
51
48
 
49
+ @logger.trace_function(log_args=log_args, log_result=log_result)
52
50
  async def ensure(self):
53
- with tracer.start_as_current_span("PostgresConversationClient.ensure"):
54
- if not self.conn:
55
- logger.warning("PostgreSQL client not initialized correctly")
56
- return False, "PostgreSQL client not initialized correctly"
57
- logger.info("PostgreSQL client initialized successfully")
58
- return True, "PostgreSQL client initialized successfully"
51
+ if not self.conn:
52
+ logger.warning("PostgreSQL client not initialized correctly")
53
+ return False, "PostgreSQL client not initialized correctly"
54
+ logger.info("PostgreSQL client initialized successfully")
55
+ return True, "PostgreSQL client initialized successfully"
59
56
 
57
+ @logger.trace_function(log_args=log_args, log_result=log_result)
60
58
  async def create_conversation(self, conversation_id, user_id, title=""):
61
- with tracer.start_as_current_span(
62
- "PostgresConversationClient.create_conversation"
63
- ):
64
- utc_now = datetime.now(timezone.utc)
65
- createdAt = utc_now.strftime("%Y-%m-%dT%H:%M:%S.%f")[:-3] + "Z"
66
- query = """
67
- INSERT INTO conversations (id, conversation_id, type, "createdAt", "updatedAt", user_id, title)
68
- VALUES ($1, $2, 'conversation', $3, $3, $4, $5)
69
- RETURNING *
70
- """
71
- try:
72
- conversation = await self.conn.fetchrow(
73
- query, conversation_id, conversation_id, createdAt, user_id, title
74
- )
75
- if conversation:
76
- logger.info(f"Conversation created with id: {conversation_id}")
77
- return dict(conversation)
78
- else:
79
- logger.warning(
80
- f"Failed to create conversation with id: {conversation_id}"
81
- )
82
- return False
83
- except Exception as e:
84
- logger.error(
85
- f"Error creating conversation with id: {conversation_id}: {e}",
86
- exc_info=True,
59
+ utc_now = datetime.now(timezone.utc)
60
+ createdAt = utc_now.strftime("%Y-%m-%dT%H:%M:%S.%f")[:-3] + "Z"
61
+ query = """
62
+ INSERT INTO conversations (id, conversation_id, type, "createdAt", "updatedAt", user_id, title)
63
+ VALUES ($1, $2, 'conversation', $3, $3, $4, $5)
64
+ RETURNING *
65
+ """
66
+ try:
67
+ conversation = await self.conn.fetchrow(
68
+ query, conversation_id, conversation_id, createdAt, user_id, title
69
+ )
70
+ if conversation:
71
+ logger.info(f"Conversation created with id: {conversation_id}")
72
+ return dict(conversation)
73
+ else:
74
+ logger.warning(
75
+ f"Failed to create conversation with id: {conversation_id}"
87
76
  )
88
- raise
77
+ return False
78
+ except Exception as e:
79
+ logger.error(
80
+ f"Error creating conversation with id: {conversation_id}: {e}",
81
+ exc_info=True,
82
+ )
83
+ raise
89
84
 
85
+ @logger.trace_function(log_args=log_args, log_result=log_result)
90
86
  async def upsert_conversation(self, conversation):
91
- with tracer.start_as_current_span(
92
- "PostgresConversationClient.upsert_conversation"
93
- ):
94
- query = """
95
- INSERT INTO conversations (id, conversation_id, type, "createdAt", "updatedAt", user_id, title)
96
- VALUES ($1, $2, $3, $4, $5, $6, $7)
97
- ON CONFLICT (id) DO UPDATE SET
98
- "updatedAt" = EXCLUDED."updatedAt",
99
- title = EXCLUDED.title
100
- RETURNING *
101
- """
102
- try:
103
- updated_conversation = await self.conn.fetchrow(
104
- query,
105
- conversation["id"],
106
- conversation["conversation_id"],
107
- conversation["type"],
108
- conversation["createdAt"],
109
- conversation["updatedAt"],
110
- conversation["user_id"],
111
- conversation["title"],
112
- )
113
- if updated_conversation:
114
- logger.info(f"Conversation upserted with id: {conversation['id']}")
115
- return dict(updated_conversation)
116
- else:
117
- logger.warning(
118
- f"Failed to upsert conversation with id: {conversation['id']}"
119
- )
120
- return False
121
- except Exception as e:
122
- logger.error(
123
- f"Error upserting conversation with id: {conversation['id']}: {e}",
124
- exc_info=True,
87
+ query = """
88
+ INSERT INTO conversations (id, conversation_id, type, "createdAt", "updatedAt", user_id, title)
89
+ VALUES ($1, $2, $3, $4, $5, $6, $7)
90
+ ON CONFLICT (id) DO UPDATE SET
91
+ "updatedAt" = EXCLUDED."updatedAt",
92
+ title = EXCLUDED.title
93
+ RETURNING *
94
+ """
95
+ try:
96
+ updated_conversation = await self.conn.fetchrow(
97
+ query,
98
+ conversation["id"],
99
+ conversation["conversation_id"],
100
+ conversation["type"],
101
+ conversation["createdAt"],
102
+ conversation["updatedAt"],
103
+ conversation["user_id"],
104
+ conversation["title"],
105
+ )
106
+ if updated_conversation:
107
+ logger.info(f"Conversation upserted with id: {conversation['id']}")
108
+ return dict(updated_conversation)
109
+ else:
110
+ logger.warning(
111
+ f"Failed to upsert conversation with id: {conversation['id']}"
125
112
  )
126
- raise
113
+ return False
114
+ except Exception as e:
115
+ logger.error(
116
+ f"Error upserting conversation with id: {conversation['id']}: {e}",
117
+ exc_info=True,
118
+ )
119
+ raise
127
120
 
121
+ @logger.trace_function(log_args=log_args, log_result=log_result)
128
122
  async def delete_conversation(self, user_id, conversation_id):
129
- with tracer.start_as_current_span(
130
- "PostgresConversationClient.delete_conversation"
131
- ):
132
- query = (
133
- "DELETE FROM conversations WHERE conversation_id = $1 AND user_id = $2"
123
+ query = (
124
+ "DELETE FROM conversations WHERE conversation_id = $1 AND user_id = $2"
125
+ )
126
+ try:
127
+ await self.conn.execute(query, conversation_id, user_id)
128
+ logger.info(
129
+ f"Conversation deleted with conversation_id: {conversation_id} and user_id: {user_id}"
134
130
  )
135
- try:
136
- await self.conn.execute(query, conversation_id, user_id)
137
- logger.info(
138
- f"Conversation deleted with conversation_id: {conversation_id} and user_id: {user_id}"
139
- )
140
- return True
141
- except Exception as e:
142
- logger.error(
143
- f"Error deleting conversation with conversation_id: {conversation_id} and user_id: {user_id}: {e}",
144
- exc_info=True,
145
- )
146
- raise
131
+ return True
132
+ except Exception as e:
133
+ logger.error(
134
+ f"Error deleting conversation with conversation_id: {conversation_id} and user_id: {user_id}: {e}",
135
+ exc_info=True,
136
+ )
137
+ raise
147
138
 
139
+ @logger.trace_function(log_args=log_args, log_result=log_result)
148
140
  async def delete_messages(self, conversation_id, user_id):
149
- with tracer.start_as_current_span("PostgresConversationClient.delete_messages"):
150
- query = "DELETE FROM messages WHERE conversation_id = $1 AND user_id = $2 RETURNING *"
151
- try:
152
- messages = await self.conn.fetch(query, conversation_id, user_id)
153
- logger.info(
154
- f"Messages deleted for conversation_id: {conversation_id} and user_id: {user_id}"
155
- )
156
- return [dict(message) for message in messages]
157
- except Exception as e:
158
- logger.error(
159
- f"Error deleting messages for conversation_id: {conversation_id} and user_id: {user_id}: {e}",
160
- exc_info=True,
161
- )
162
- raise
141
+ query = "DELETE FROM messages WHERE conversation_id = $1 AND user_id = $2 RETURNING *"
142
+ try:
143
+ messages = await self.conn.fetch(query, conversation_id, user_id)
144
+ logger.info(
145
+ f"Messages deleted for conversation_id: {conversation_id} and user_id: {user_id}"
146
+ )
147
+ return [dict(message) for message in messages]
148
+ except Exception as e:
149
+ logger.error(
150
+ f"Error deleting messages for conversation_id: {conversation_id} and user_id: {user_id}: {e}",
151
+ exc_info=True,
152
+ )
153
+ raise
163
154
 
155
+ @logger.trace_function(log_args=log_args, log_result=log_result)
164
156
  async def get_conversations(self, user_id, limit=None, sort_order="DESC", offset=0):
165
- with tracer.start_as_current_span(
166
- "PostgresConversationClient.get_conversations"
167
- ):
157
+ try:
158
+ offset = int(offset) # Ensure offset is an integer
159
+ except ValueError:
160
+ logger.error("Offset must be an integer.", exc_info=True)
161
+ raise ValueError("Offset must be an integer.")
162
+ # Base query without LIMIT and OFFSET
163
+ query = f"""
164
+ SELECT * FROM conversations
165
+ WHERE user_id = $1 AND type = 'conversation'
166
+ ORDER BY "updatedAt" {sort_order}
167
+ """
168
+ # Append LIMIT and OFFSET to the query if limit is specified
169
+ if limit is not None:
168
170
  try:
169
- offset = int(offset) # Ensure offset is an integer
170
- except ValueError:
171
- logger.error("Offset must be an integer.", exc_info=True)
172
- raise ValueError("Offset must be an integer.")
173
- # Base query without LIMIT and OFFSET
174
- query = f"""
175
- SELECT * FROM conversations
176
- WHERE user_id = $1 AND type = 'conversation'
177
- ORDER BY "updatedAt" {sort_order}
178
- """
179
- # Append LIMIT and OFFSET to the query if limit is specified
180
- if limit is not None:
181
- try:
182
- limit = int(limit) # Ensure limit is an integer
183
- query += " LIMIT $2 OFFSET $3"
184
- # Fetch records with LIMIT and OFFSET
185
- conversations = await self.conn.fetch(query, user_id, limit, offset)
186
- logger.info(
187
- f"Retrieved conversations for user_id: {user_id} with limit: {limit} and offset: {offset}"
188
- )
189
- except ValueError:
190
- logger.error("Limit must be an integer.", exc_info=True)
191
- raise ValueError("Limit must be an integer.")
192
- else:
193
- # Fetch records without LIMIT and OFFSET
194
- conversations = await self.conn.fetch(query, user_id)
171
+ limit = int(limit) # Ensure limit is an integer
172
+ query += " LIMIT $2 OFFSET $3"
173
+ # Fetch records with LIMIT and OFFSET
174
+ conversations = await self.conn.fetch(query, user_id, limit, offset)
195
175
  logger.info(
196
- f"Retrieved conversations for user_id: {user_id} without limit and offset"
176
+ f"Retrieved conversations for user_id: {user_id} with limit: {limit} and offset: {offset}"
197
177
  )
198
- return [dict(conversation) for conversation in conversations]
178
+ except ValueError:
179
+ logger.error("Limit must be an integer.", exc_info=True)
180
+ raise ValueError("Limit must be an integer.")
181
+ else:
182
+ # Fetch records without LIMIT and OFFSET
183
+ conversations = await self.conn.fetch(query, user_id)
184
+ logger.info(
185
+ f"Retrieved conversations for user_id: {user_id} without limit and offset"
186
+ )
187
+ return [dict(conversation) for conversation in conversations]
199
188
 
189
+ @logger.trace_function(log_args=log_args, log_result=log_result)
200
190
  async def get_conversation(self, user_id, conversation_id):
201
- with tracer.start_as_current_span(
202
- "PostgresConversationClient.get_conversation"
203
- ):
204
- query = "SELECT * FROM conversations WHERE id = $1 AND user_id = $2 AND type = 'conversation'"
205
- try:
206
- conversation = await self.conn.fetchrow(query, conversation_id, user_id)
207
- if conversation:
208
- logger.info(
209
- f"Retrieved conversation with id: {conversation_id} and user_id: {user_id}"
210
- )
211
- return dict(conversation)
212
- else:
213
- logger.warning(
214
- f"No conversation found with id: {conversation_id} and user_id: {user_id}"
215
- )
216
- return None
217
- except Exception as e:
218
- logger.error(
219
- f"Error retrieving conversation with id: {conversation_id} and user_id: {user_id}: {e}",
220
- exc_info=True,
191
+ query = "SELECT * FROM conversations WHERE id = $1 AND user_id = $2 AND type = 'conversation'"
192
+ try:
193
+ conversation = await self.conn.fetchrow(query, conversation_id, user_id)
194
+ if conversation:
195
+ logger.info(
196
+ f"Retrieved conversation with id: {conversation_id} and user_id: {user_id}"
221
197
  )
222
- raise
198
+ return dict(conversation)
199
+ else:
200
+ logger.warning(
201
+ f"No conversation found with id: {conversation_id} and user_id: {user_id}"
202
+ )
203
+ return None
204
+ except Exception as e:
205
+ logger.error(
206
+ f"Error retrieving conversation with id: {conversation_id} and user_id: {user_id}: {e}",
207
+ exc_info=True,
208
+ )
209
+ raise
223
210
 
211
+ @logger.trace_function(log_args=log_args, log_result=log_result)
224
212
  async def create_message(self, uuid, conversation_id, user_id, input_message: dict):
225
- with tracer.start_as_current_span("PostgresConversationClient.create_message"):
226
- message_id = uuid
227
- utc_now = datetime.now(timezone.utc)
228
- createdAt = utc_now.strftime("%Y-%m-%dT%H:%M:%S.%f")[:-3] + "Z"
229
- query = """
230
- INSERT INTO messages (id, type, "createdAt", "updatedAt", user_id, conversation_id, role, content, feedback)
231
- VALUES ($1, 'message', $2, $2, $3, $4, $5, $6, $7)
232
- RETURNING *
233
- """
234
- feedback = "" if self.enable_message_feedback else None
235
- try:
236
- message = await self.conn.fetchrow(
237
- query,
238
- message_id,
239
- createdAt,
240
- user_id,
241
- conversation_id,
242
- input_message["role"],
243
- input_message["content"],
244
- feedback,
245
- )
213
+ message_id = uuid
214
+ utc_now = datetime.now(timezone.utc)
215
+ createdAt = utc_now.strftime("%Y-%m-%dT%H:%M:%S.%f")[:-3] + "Z"
216
+ query = """
217
+ INSERT INTO messages (id, type, "createdAt", "updatedAt", user_id, conversation_id, role, content, feedback)
218
+ VALUES ($1, 'message', $2, $2, $3, $4, $5, $6, $7)
219
+ RETURNING *
220
+ """
221
+ feedback = "" if self.enable_message_feedback else None
222
+ try:
223
+ message = await self.conn.fetchrow(
224
+ query,
225
+ message_id,
226
+ createdAt,
227
+ user_id,
228
+ conversation_id,
229
+ input_message["role"],
230
+ input_message["content"],
231
+ feedback,
232
+ )
246
233
 
247
- if message:
248
- update_query = 'UPDATE conversations SET "updatedAt" = $1 WHERE id = $2 AND user_id = $3 RETURNING *'
249
- await self.conn.execute(
250
- update_query, createdAt, conversation_id, user_id
251
- )
252
- logger.info(
253
- f"Message created with id: {message_id} in conversation: {conversation_id}"
254
- )
255
- return dict(message)
256
- else:
257
- logger.warning(
258
- f"Failed to create message with id: {message_id} in conversation: {conversation_id}"
259
- )
260
- return False
261
- except Exception as e:
262
- logger.error(
263
- f"Error creating message with id: {message_id} in conversation: {conversation_id}: {e}",
264
- exc_info=True,
234
+ if message:
235
+ update_query = 'UPDATE conversations SET "updatedAt" = $1 WHERE id = $2 AND user_id = $3 RETURNING *'
236
+ await self.conn.execute(
237
+ update_query, createdAt, conversation_id, user_id
265
238
  )
266
- raise
267
-
268
- async def update_message_feedback(self, user_id, message_id, feedback):
269
- with tracer.start_as_current_span(
270
- "PostgresConversationClient.update_message_feedback"
271
- ):
272
- query = "UPDATE messages SET feedback = $1 WHERE id = $2 AND user_id = $3 RETURNING *"
273
- try:
274
- message = await self.conn.fetchrow(query, feedback, message_id, user_id)
275
- if message:
276
- logger.info(
277
- f"Message feedback updated for message_id: {message_id} and user_id: {user_id}"
278
- )
279
- return dict(message)
280
- else:
281
- logger.warning(
282
- f"Failed to update message feedback for message_id: {message_id} and user_id: {user_id}"
283
- )
284
- return False
285
- except Exception as e:
286
- logger.error(
287
- f"Error updating message feedback for message_id: {message_id} and user_id: {user_id}: {e}",
288
- exc_info=True,
239
+ logger.info(
240
+ f"Message created with id: {message_id} in conversation: {conversation_id}"
241
+ )
242
+ return dict(message)
243
+ else:
244
+ logger.warning(
245
+ f"Failed to create message with id: {message_id} in conversation: {conversation_id}"
289
246
  )
290
- raise
247
+ return False
248
+ except Exception as e:
249
+ logger.error(
250
+ f"Error creating message with id: {message_id} in conversation: {conversation_id}: {e}",
251
+ exc_info=True,
252
+ )
253
+ raise
291
254
 
292
- async def get_messages(self, user_id, conversation_id):
293
- with tracer.start_as_current_span("PostgresConversationClient.get_messages"):
294
- query = 'SELECT * FROM messages WHERE conversation_id = $1 AND user_id = $2 ORDER BY "createdAt" ASC'
295
- try:
296
- messages = await self.conn.fetch(query, conversation_id, user_id)
255
+ @logger.trace_function(log_args=log_args, log_result=log_result)
256
+ async def update_message_feedback(self, user_id, message_id, feedback):
257
+ query = "UPDATE messages SET feedback = $1 WHERE id = $2 AND user_id = $3 RETURNING *"
258
+ try:
259
+ message = await self.conn.fetchrow(query, feedback, message_id, user_id)
260
+ if message:
297
261
  logger.info(
298
- f"Retrieved messages for conversation_id: {conversation_id} and user_id: {user_id}"
262
+ f"Message feedback updated for message_id: {message_id} and user_id: {user_id}"
299
263
  )
300
- return [dict(message) for message in messages]
301
- except Exception as e:
302
- logger.error(
303
- f"Error retrieving messages for conversation_id: {conversation_id} and user_id: {user_id}: {e}",
304
- exc_info=True,
264
+ return dict(message)
265
+ else:
266
+ logger.warning(
267
+ f"Failed to update message feedback for message_id: {message_id} and user_id: {user_id}"
305
268
  )
306
- raise
269
+ return False
270
+ except Exception as e:
271
+ logger.error(
272
+ f"Error updating message feedback for message_id: {message_id} and user_id: {user_id}: {e}",
273
+ exc_info=True,
274
+ )
275
+ raise
276
+
277
+ @logger.trace_function(log_args=log_args, log_result=log_result)
278
+ async def get_messages(self, user_id, conversation_id):
279
+ query = 'SELECT * FROM messages WHERE conversation_id = $1 AND user_id = $2 ORDER BY "createdAt" ASC'
280
+ try:
281
+ messages = await self.conn.fetch(query, conversation_id, user_id)
282
+ logger.info(
283
+ f"Retrieved messages for conversation_id: {conversation_id} and user_id: {user_id}"
284
+ )
285
+ return [dict(message) for message in messages]
286
+ except Exception as e:
287
+ logger.error(
288
+ f"Error retrieving messages for conversation_id: {conversation_id} and user_id: {user_id}: {e}",
289
+ exc_info=True,
290
+ )
291
+ raise