unique_toolkit 0.6.6__py3-none-any.whl → 0.6.8__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.
@@ -102,7 +102,7 @@ class ChatEventPayload(BaseModel):
102
102
  metadata_filter: Optional[dict[str, Any]] = None
103
103
 
104
104
 
105
- @deprecated("""UUse `ChatEventPayload` instead.
105
+ @deprecated("""Use `ChatEventPayload` instead.
106
106
  This class will be removed in the next major version.""")
107
107
  class EventPayload(ChatEventPayload):
108
108
  user_message: EventUserMessage
@@ -1,10 +1,15 @@
1
+ import json
1
2
  import logging
3
+ import os
2
4
  from typing import Callable, TypeVar
3
5
 
4
6
  import unique_sdk
7
+ from pydantic import ValidationError
5
8
 
6
9
  from unique_toolkit.app.schemas import Event
7
10
 
11
+ logger = logging.getLogger(f"toolkit.{__name__}")
12
+
8
13
 
9
14
  class WebhookVerificationError(Exception):
10
15
  """Custom exception for webhook verification errors."""
@@ -19,7 +24,7 @@ def verify_signature_and_construct_event(
19
24
  headers: dict[str, str],
20
25
  payload: bytes,
21
26
  endpoint_secret: str,
22
- logger: logging.Logger = logging.getLogger(__name__),
27
+ logger: logging.Logger = logger,
23
28
  event_constructor: Callable[..., T] = Event,
24
29
  ) -> T:
25
30
  """
@@ -57,3 +62,51 @@ def verify_signature_and_construct_event(
57
62
  except unique_sdk.SignatureVerificationError as e:
58
63
  logger.error("⚠️ Webhook signature verification failed. " + str(e))
59
64
  raise WebhookVerificationError(f"Signature verification failed: {str(e)}")
65
+
66
+
67
+ def verify_request_and_construct_event(
68
+ assistant_name: str,
69
+ payload: bytes,
70
+ headers: dict[str, str],
71
+ event_constructor: Callable[..., Event] = Event,
72
+ ) -> tuple[str, int] | tuple[Event, int]:
73
+ """Check the payload, authenticate and genenrate the event if the payload is correct"""
74
+ logger.info(f"{assistant_name} - received request")
75
+
76
+ try:
77
+ payload_decoded = json.loads(payload)
78
+ except json.decoder.JSONDecodeError as e:
79
+ logger.error(f"Error decoding payload: {e}", exc_info=True)
80
+ return "Invalid payload", 400
81
+
82
+ endpoint_secret = os.environ.get("ENDPOINT_SECRET", None)
83
+ if endpoint_secret:
84
+ response = verify_signature_and_construct_event(
85
+ headers=headers, # type: ignore
86
+ payload=payload,
87
+ endpoint_secret=endpoint_secret,
88
+ logger=logger,
89
+ event_constructor=event_constructor,
90
+ )
91
+ if isinstance(response, tuple):
92
+ return response # Error response
93
+ event = response # This is an event since it is not a tuple
94
+ else:
95
+ try:
96
+ event = event_constructor(**payload_decoded)
97
+ except ValidationError as e:
98
+ # pydantic errors https://docs.pydantic.dev/2.10/errors/errors/
99
+ logger.error(f"Validation error with model: {e.json()}", exc_info=True)
100
+ raise ValidationError(e)
101
+ except ValueError as e:
102
+ logger.error(f"Error deserializing event: {e}", exc_info=True)
103
+ return "Invalid event", 400
104
+
105
+ if not event.payload.name == assistant_name:
106
+ logger.error(
107
+ f"{assistant_name}: Incorrect assistant: {event.payload.name}: Expected {assistant_name}"
108
+ )
109
+ return f"Not {assistant_name} event", 400
110
+
111
+ logger.info(f"{assistant_name} - received event")
112
+ return event, 200
@@ -3,6 +3,7 @@ from typing_extensions import Self
3
3
  from unique_toolkit.language_model import (
4
4
  LanguageModelAssistantMessage,
5
5
  LanguageModelMessage,
6
+ LanguageModelMessageRole,
6
7
  LanguageModelMessages,
7
8
  LanguageModelSystemMessage,
8
9
  LanguageModelToolMessage,
@@ -14,6 +15,11 @@ class MessagesBuilder:
14
15
  def __init__(self):
15
16
  self.messages: list[LanguageModelMessage] = []
16
17
 
18
+ def message_append(self, role: LanguageModelMessageRole, content: str):
19
+ message = LanguageModelMessage(role=role, content=content)
20
+ self.messages.append(message)
21
+ return self
22
+
17
23
  def system_message_append(self, content: str) -> Self:
18
24
  """Appends a system message to the messages list."""
19
25
  message = LanguageModelSystemMessage(content=content)
@@ -26,15 +32,18 @@ class MessagesBuilder:
26
32
  self.messages.append(message)
27
33
  return self # Return self to allow method chaining
28
34
 
29
- def image_message_append(self, content: str, images: list[str]) -> Self:
30
- message = LanguageModelUserMessage(
35
+ def image_message_append(
36
+ self, content: str, images: list[str], role=LanguageModelMessageRole.USER
37
+ ) -> Self:
38
+ message = LanguageModelMessage(
39
+ role=role,
31
40
  content=[
32
41
  {"type": "text", "text": content},
33
42
  *[
34
43
  {"type": "image_url", "imageUrl": {"url": image}}
35
44
  for image in images
36
45
  ],
37
- ]
46
+ ],
38
47
  )
39
48
  self.messages.append(message)
40
49
  return self
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: unique_toolkit
3
- Version: 0.6.6
3
+ Version: 0.6.8
4
4
  Summary:
5
5
  License: Proprietary
6
6
  Author: Martin Fadler
@@ -111,6 +111,12 @@ All notable changes to this project will be documented in this file.
111
111
  The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
112
112
  and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
113
113
 
114
+ ## [0.6.8] - 2025-03-11
115
+ - Add `verify_request_and_construct_event` to `verification.py`
116
+
117
+ ## [0.6.7] - 2025-03-10
118
+ - Extend language model message builder
119
+
114
120
  ## [0.6.6] - 2025-03-10
115
121
  - Add o1, o1-mini and o3-mini models
116
122
  - Remove deprecated gpt4 models
@@ -9,8 +9,8 @@ unique_toolkit/app/init_logging.py,sha256=Sh26SRxOj8i8dzobKhYha2lLrkrMTHfB1V4jR3
9
9
  unique_toolkit/app/init_sdk.py,sha256=Nv4Now4pMfM0AgRhbtatLpm_39rKxn0WmRLwmPhRl-8,1285
10
10
  unique_toolkit/app/performance/async_tasks.py,sha256=H0l3OAcosLwNHZ8d2pd-Di4wHIXfclEvagi5kfqLFPA,1941
11
11
  unique_toolkit/app/performance/async_wrapper.py,sha256=yVVcRDkcdyfjsxro-N29SBvi-7773wnfDplef6-y8xw,1077
12
- unique_toolkit/app/schemas.py,sha256=hPOh5xLNNWgWVIkdrj6ZHYaGz0cTV-5Kv7OQHOaUgV8,3201
13
- unique_toolkit/app/verification.py,sha256=mffa6wm0i4hJbwzofePrkaia46xumMzECwQ0T3eKAx0,1929
12
+ unique_toolkit/app/schemas.py,sha256=jnW3f_4ohyfM7sVfZlNuV8At19qUwPJGC8XHx4ktlEY,3200
13
+ unique_toolkit/app/verification.py,sha256=GxFFwcJMy25fCA_Xe89wKW7bgqOu8PAs5y8QpHF0GSc,3861
14
14
  unique_toolkit/chat/__init__.py,sha256=LRs2G-JTVuci4lbtHTkVUiNcZcSR6uqqfnAyo7af6nY,619
15
15
  unique_toolkit/chat/constants.py,sha256=05kq6zjqUVB2d6_P7s-90nbljpB3ryxwCI-CAz0r2O4,83
16
16
  unique_toolkit/chat/functions.py,sha256=J9Cmgkhj9bBxZja3ggkSp48af_LPU4Dfi9Sbc_WhhNY,27204
@@ -45,7 +45,7 @@ unique_toolkit/evaluators/hallucination/utils.py,sha256=4KTJH8low_fBzOcuVlcHB2FR
45
45
  unique_toolkit/evaluators/output_parser.py,sha256=eI72qkzK1dZyUvnfP2SOAQCGBj_-PwX5wy_aLPMsJMY,883
46
46
  unique_toolkit/evaluators/schemas.py,sha256=Jaue6Uhx75X1CyHKWj8sT3RE1JZXTqoLtfLt2xQNCX8,2507
47
47
  unique_toolkit/language_model/__init__.py,sha256=jWko_vQj48wjnpTtlkg8iNdef0SMI3FN2kGywXRTMzg,1880
48
- unique_toolkit/language_model/builder.py,sha256=qP1SlUnYJHLqT-fpXs4lgUixnekhx8IIfuoXnMHvRKE,2408
48
+ unique_toolkit/language_model/builder.py,sha256=_lUL2shMN1Je2LLYu2PiehOvfWtn5pg1yUuYyiw3f_c,2710
49
49
  unique_toolkit/language_model/constants.py,sha256=B-topqW0r83dkC_25DeQfnPk3n53qzIHUCBS7YJ0-1U,119
50
50
  unique_toolkit/language_model/functions.py,sha256=I5jHhHsKoq7GwEQyTrM8LXB2n_6dvMAk7UklenjuHSY,7945
51
51
  unique_toolkit/language_model/infos.py,sha256=DRkF0HzVemtSsSvdtrdsajNKaQ46Xla0ZXzFhi7xMtc,16338
@@ -58,7 +58,7 @@ unique_toolkit/short_term_memory/constants.py,sha256=698CL6-wjup2MvU19RxSmQk3gX7
58
58
  unique_toolkit/short_term_memory/functions.py,sha256=3WiK-xatY5nh4Dr5zlDUye1k3E6kr41RiscwtTplw5k,4484
59
59
  unique_toolkit/short_term_memory/schemas.py,sha256=OhfcXyF6ACdwIXW45sKzjtZX_gkcJs8FEZXcgQTNenw,1406
60
60
  unique_toolkit/short_term_memory/service.py,sha256=gdsVzoNqTXmLoBR_-p_lJlZDBo8L7Cr5EKchTNVJg1Q,5233
61
- unique_toolkit-0.6.6.dist-info/LICENSE,sha256=GlN8wHNdh53xwOPg44URnwag6TEolCjoq3YD_KrWgss,193
62
- unique_toolkit-0.6.6.dist-info/METADATA,sha256=MAiqgLQcnD82DSwx5CmFbRLoCaAJVgbrHLYpr0AGb2Q,20003
63
- unique_toolkit-0.6.6.dist-info/WHEEL,sha256=sP946D7jFCHeNz5Iq4fL4Lu-PrWrFsgfLXbbkciIZwg,88
64
- unique_toolkit-0.6.6.dist-info/RECORD,,
61
+ unique_toolkit-0.6.8.dist-info/LICENSE,sha256=GlN8wHNdh53xwOPg44URnwag6TEolCjoq3YD_KrWgss,193
62
+ unique_toolkit-0.6.8.dist-info/METADATA,sha256=ur8J07QmoFPjKB1oMwjXXsWhOo9XG1g_gabI3q5dpW0,20157
63
+ unique_toolkit-0.6.8.dist-info/WHEEL,sha256=sP946D7jFCHeNz5Iq4fL4Lu-PrWrFsgfLXbbkciIZwg,88
64
+ unique_toolkit-0.6.8.dist-info/RECORD,,