maitai-python 1.2.31b3__tar.gz → 1.2.32__tar.gz
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.
- {maitai_python-1.2.31b3 → maitai_python-1.2.32}/PKG-INFO +6 -1
- maitai_python-1.2.32/maitai/__init__.py +34 -0
- maitai_python-1.2.32/maitai/_files.py +145 -0
- maitai_python-1.2.32/maitai/_logger.py +300 -0
- {maitai_python-1.2.31b3 → maitai_python-1.2.32}/maitai/_maitai.py +23 -0
- {maitai_python-1.2.31b3 → maitai_python-1.2.32}/maitai/_maitai_async.py +39 -2
- {maitai_python-1.2.31b3 → maitai_python-1.2.32}/maitai/_utils.py +89 -0
- {maitai_python-1.2.31b3 → maitai_python-1.2.32}/maitai/agent/_completions.py +2 -53
- {maitai_python-1.2.31b3 → maitai_python-1.2.32}/maitai/agent/_completions_async.py +2 -53
- maitai_python-1.2.32/maitai/agent/_handle.py +219 -0
- maitai_python-1.2.32/maitai/agent/_request_wire.py +102 -0
- {maitai_python-1.2.31b3 → maitai_python-1.2.32}/maitai/chat/_completions.py +4 -0
- {maitai_python-1.2.31b3 → maitai_python-1.2.32}/maitai/chat/_completions_async.py +4 -0
- maitai_python-1.2.32/maitai/integrations/__init__.py +14 -0
- maitai_python-1.2.32/maitai/integrations/_observe.py +245 -0
- maitai_python-1.2.32/maitai/integrations/_session.py +86 -0
- {maitai_python-1.2.31b3 → maitai_python-1.2.32}/maitai/models/agent/extended.py +81 -3
- {maitai_python-1.2.31b3 → maitai_python-1.2.32}/maitai/models/chat.py +57 -0
- {maitai_python-1.2.31b3 → maitai_python-1.2.32}/maitai/models/sentinel.py +12 -3
- maitai_python-1.2.32/maitai/models/workflow_chunk.py +43 -0
- {maitai_python-1.2.31b3 → maitai_python-1.2.32}/maitai/workflow/_completions.py +3 -0
- {maitai_python-1.2.31b3 → maitai_python-1.2.32}/maitai/workflow/_completions_async.py +12 -4
- {maitai_python-1.2.31b3 → maitai_python-1.2.32}/maitai/workflow/_local.py +128 -8
- {maitai_python-1.2.31b3 → maitai_python-1.2.32}/maitai_common/version.py +1 -1
- maitai_python-1.2.32/maitai_models/adapter.py +18 -0
- maitai_python-1.2.32/maitai_models/agent/__init__.py +76 -0
- maitai_python-1.2.32/maitai_models/agent/base.py +218 -0
- maitai_python-1.2.32/maitai_models/agent/enum.py +69 -0
- maitai_python-1.2.32/maitai_models/agent/extended.py +636 -0
- maitai_python-1.2.32/maitai_models/agent/import_manifest.py +152 -0
- maitai_python-1.2.32/maitai_models/agent_action.py +144 -0
- maitai_python-1.2.32/maitai_models/agent_evaluation.py +70 -0
- maitai_python-1.2.32/maitai_models/agent_form.py +127 -0
- maitai_python-1.2.32/maitai_models/agent_routing.py +170 -0
- maitai_python-1.2.32/maitai_models/application.py +60 -0
- maitai_python-1.2.32/maitai_models/assistant_model.py +28 -0
- maitai_python-1.2.32/maitai_models/backtest.py +29 -0
- maitai_python-1.2.32/maitai_models/billing.py +280 -0
- maitai_python-1.2.32/maitai_models/chat.py +559 -0
- maitai_python-1.2.32/maitai_models/chat_metadata.py +25 -0
- maitai_python-1.2.32/maitai_models/company.py +42 -0
- maitai_python-1.2.32/maitai_models/config.py +128 -0
- maitai_python-1.2.32/maitai_models/connection.py +14 -0
- maitai_python-1.2.32/maitai_models/continuous_learning.py +307 -0
- maitai_python-1.2.32/maitai_models/conversation_builder.py +664 -0
- maitai_python-1.2.32/maitai_models/dataset.py +77 -0
- maitai_python-1.2.32/maitai_models/dataset_import.py +84 -0
- maitai_python-1.2.32/maitai_models/deploy.py +50 -0
- maitai_python-1.2.32/maitai_models/embedding.py +19 -0
- maitai_python-1.2.32/maitai_models/evaluation.py +163 -0
- maitai_python-1.2.32/maitai_models/evaluation_enums.py +696 -0
- maitai_python-1.2.32/maitai_models/event.py +13 -0
- maitai_python-1.2.32/maitai_models/event_subscription.py +11 -0
- maitai_python-1.2.32/maitai_models/file.py +36 -0
- maitai_python-1.2.32/maitai_models/finetuning.py +444 -0
- maitai_python-1.2.32/maitai_models/inference.py +21 -0
- maitai_python-1.2.32/maitai_models/infra.py +44 -0
- maitai_python-1.2.32/maitai_models/intent.py +17 -0
- maitai_python-1.2.32/maitai_models/intent_config_version.py +66 -0
- maitai_python-1.2.32/maitai_models/key.py +45 -0
- maitai_python-1.2.32/maitai_models/metadata.py +72 -0
- maitai_python-1.2.32/maitai_models/metric.py +18 -0
- maitai_python-1.2.32/maitai_models/model.py +55 -0
- maitai_python-1.2.32/maitai_models/model_drift.py +55 -0
- maitai_python-1.2.32/maitai_models/model_profile.py +88 -0
- maitai_python-1.2.32/maitai_models/monitor.py +331 -0
- maitai_python-1.2.32/maitai_models/notification.py +46 -0
- maitai_python-1.2.32/maitai_models/rates.py +38 -0
- maitai_python-1.2.32/maitai_models/sandbox.py +36 -0
- maitai_python-1.2.32/maitai_models/scheduled_job.py +17 -0
- maitai_python-1.2.32/maitai_models/sentinel.py +122 -0
- maitai_python-1.2.32/maitai_models/session.py +35 -0
- maitai_python-1.2.32/maitai_models/shared_resource.py +19 -0
- maitai_python-1.2.32/maitai_models/slack_integration.py +17 -0
- maitai_python-1.2.32/maitai_models/tagging.py +102 -0
- maitai_python-1.2.32/maitai_models/webhook.py +32 -0
- maitai_python-1.2.32/maitai_models/webhook_event.py +12 -0
- maitai_python-1.2.32/maitai_models/workflow.py +160 -0
- maitai_python-1.2.32/maitai_models/workflow_chunk.py +45 -0
- {maitai_python-1.2.31b3 → maitai_python-1.2.32}/maitai_python.egg-info/PKG-INFO +6 -1
- maitai_python-1.2.32/maitai_python.egg-info/SOURCES.txt +117 -0
- maitai_python-1.2.32/maitai_python.egg-info/requires.txt +13 -0
- {maitai_python-1.2.31b3 → maitai_python-1.2.32}/maitai_python.egg-info/top_level.txt +1 -0
- {maitai_python-1.2.31b3 → maitai_python-1.2.32}/setup.py +15 -4
- maitai_python-1.2.31b3/maitai/__init__.py +0 -7
- maitai_python-1.2.31b3/maitai/models/workflow_chunk.py +0 -24
- maitai_python-1.2.31b3/maitai_python.egg-info/SOURCES.txt +0 -55
- maitai_python-1.2.31b3/maitai_python.egg-info/requires.txt +0 -8
- {maitai_python-1.2.31b3 → maitai_python-1.2.32}/README.md +0 -0
- {maitai_python-1.2.31b3 → maitai_python-1.2.32}/maitai/_config.py +0 -0
- {maitai_python-1.2.31b3 → maitai_python-1.2.32}/maitai/_config_listener.py +0 -0
- {maitai_python-1.2.31b3 → maitai_python-1.2.32}/maitai/_context.py +0 -0
- {maitai_python-1.2.31b3 → maitai_python-1.2.32}/maitai/_evaluator.py +0 -0
- {maitai_python-1.2.31b3 → maitai_python-1.2.32}/maitai/_inference.py +0 -0
- {maitai_python-1.2.31b3 → maitai_python-1.2.32}/maitai/_maitai_client.py +0 -0
- {maitai_python-1.2.31b3 → maitai_python-1.2.32}/maitai/_pydantic.py +0 -0
- {maitai_python-1.2.31b3 → maitai_python-1.2.32}/maitai/_types.py +0 -0
- {maitai_python-1.2.31b3 → maitai_python-1.2.32}/maitai/agent/__init__.py +0 -0
- {maitai_python-1.2.31b3 → maitai_python-1.2.32}/maitai/chat/__init__.py +0 -0
- {maitai_python-1.2.31b3 → maitai_python-1.2.32}/maitai/exceptions.py +0 -0
- {maitai_python-1.2.31b3 → maitai_python-1.2.32}/maitai/models/__init__.py +0 -0
- {maitai_python-1.2.31b3 → maitai_python-1.2.32}/maitai/models/agent/__init__.py +0 -0
- {maitai_python-1.2.31b3 → maitai_python-1.2.32}/maitai/models/agent/base.py +0 -0
- {maitai_python-1.2.31b3 → maitai_python-1.2.32}/maitai/models/agent/enum.py +0 -0
- {maitai_python-1.2.31b3 → maitai_python-1.2.32}/maitai/models/agent_action.py +0 -0
- {maitai_python-1.2.31b3 → maitai_python-1.2.32}/maitai/models/agent_routing.py +0 -0
- {maitai_python-1.2.31b3 → maitai_python-1.2.32}/maitai/models/application.py +0 -0
- {maitai_python-1.2.31b3 → maitai_python-1.2.32}/maitai/models/config.py +0 -0
- {maitai_python-1.2.31b3 → maitai_python-1.2.32}/maitai/models/event.py +0 -0
- {maitai_python-1.2.31b3 → maitai_python-1.2.32}/maitai/models/inference.py +0 -0
- {maitai_python-1.2.31b3 → maitai_python-1.2.32}/maitai/models/key.py +0 -0
- {maitai_python-1.2.31b3 → maitai_python-1.2.32}/maitai/models/metric.py +0 -0
- {maitai_python-1.2.31b3 → maitai_python-1.2.32}/maitai/tools/__init__.py +0 -0
- {maitai_python-1.2.31b3 → maitai_python-1.2.32}/maitai/transcriptions/__init__.py +0 -0
- {maitai_python-1.2.31b3 → maitai_python-1.2.32}/maitai/transcriptions/_transcriptions.py +0 -0
- {maitai_python-1.2.31b3 → maitai_python-1.2.32}/maitai/transcriptions/_transcriptions_async.py +0 -0
- {maitai_python-1.2.31b3 → maitai_python-1.2.32}/maitai/workflow/__init__.py +0 -0
- {maitai_python-1.2.31b3 → maitai_python-1.2.32}/maitai/workflow/_stream_http.py +0 -0
- {maitai_python-1.2.31b3 → maitai_python-1.2.32}/maitai_common/__init__.py +0 -0
- {maitai_python-1.2.31b3 → maitai_python-1.2.32}/maitai_common/config/__init__.py +0 -0
- {maitai_python-1.2.31b3 → maitai_python-1.2.32}/maitai_common/config/config_service.py +0 -0
- {maitai_python-1.2.31b3 → maitai_python-1.2.32}/maitai_python.egg-info/dependency_links.txt +0 -0
- {maitai_python-1.2.31b3 → maitai_python-1.2.32}/setup.cfg +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: maitai-python
|
|
3
|
-
Version: 1.2.
|
|
3
|
+
Version: 1.2.32
|
|
4
4
|
Summary: Maitai SDK for Python
|
|
5
5
|
Home-page: https://docs.trymaitai.ai
|
|
6
6
|
Author: Maitai
|
|
@@ -17,6 +17,10 @@ Requires-Dist: pydantic>=2.0.0
|
|
|
17
17
|
Requires-Dist: groq
|
|
18
18
|
Requires-Dist: boto3
|
|
19
19
|
Requires-Dist: redis
|
|
20
|
+
Provides-Extra: observe
|
|
21
|
+
Requires-Dist: opentelemetry-sdk; extra == "observe"
|
|
22
|
+
Requires-Dist: opentelemetry-exporter-otlp-proto-http; extra == "observe"
|
|
23
|
+
Requires-Dist: openinference-instrumentation; extra == "observe"
|
|
20
24
|
Dynamic: author
|
|
21
25
|
Dynamic: author-email
|
|
22
26
|
Dynamic: classifier
|
|
@@ -24,6 +28,7 @@ Dynamic: description
|
|
|
24
28
|
Dynamic: description-content-type
|
|
25
29
|
Dynamic: home-page
|
|
26
30
|
Dynamic: license
|
|
31
|
+
Dynamic: provides-extra
|
|
27
32
|
Dynamic: requires-dist
|
|
28
33
|
Dynamic: summary
|
|
29
34
|
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
from maitai._files import file_content_part, file_content_part_from_path
|
|
2
|
+
from maitai._maitai import Maitai
|
|
3
|
+
from maitai._maitai_async import MaitaiAsync
|
|
4
|
+
|
|
5
|
+
AsyncOpenAI = MaitaiAsync
|
|
6
|
+
OpenAI = Maitai
|
|
7
|
+
|
|
8
|
+
AsyncMaitai = MaitaiAsync
|
|
9
|
+
|
|
10
|
+
__all__ = [
|
|
11
|
+
"Maitai",
|
|
12
|
+
"MaitaiAsync",
|
|
13
|
+
"AsyncMaitai",
|
|
14
|
+
"OpenAI",
|
|
15
|
+
"AsyncOpenAI",
|
|
16
|
+
"file_content_part",
|
|
17
|
+
"file_content_part_from_path",
|
|
18
|
+
"observe",
|
|
19
|
+
"set_session",
|
|
20
|
+
"session",
|
|
21
|
+
"get_session",
|
|
22
|
+
]
|
|
23
|
+
|
|
24
|
+
# Lazy attrs served from maitai.integrations, so base `import maitai` never
|
|
25
|
+
# pulls in the optional observability extra (OTel / OpenInference).
|
|
26
|
+
_LAZY_INTEGRATIONS = {"observe", "set_session", "session", "get_session"}
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def __getattr__(name: str):
|
|
30
|
+
if name in _LAZY_INTEGRATIONS:
|
|
31
|
+
import maitai.integrations as _integrations
|
|
32
|
+
|
|
33
|
+
return getattr(_integrations, name)
|
|
34
|
+
raise AttributeError(f"module 'maitai' has no attribute '{name}'")
|
|
@@ -0,0 +1,145 @@
|
|
|
1
|
+
import base64
|
|
2
|
+
import mimetypes
|
|
3
|
+
import os
|
|
4
|
+
from typing import Optional, Union
|
|
5
|
+
|
|
6
|
+
from maitai._config import Config
|
|
7
|
+
from maitai._maitai_client import MaitaiClient
|
|
8
|
+
from maitai._utils import __version__ as version
|
|
9
|
+
from maitai.exceptions import BadRequestError, MaitaiConnectionError
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def file_content_part(file_id: str) -> dict:
|
|
13
|
+
"""Build a chat message content part that references an already-stored file.
|
|
14
|
+
|
|
15
|
+
Usage::
|
|
16
|
+
|
|
17
|
+
messages=[{
|
|
18
|
+
"role": "user",
|
|
19
|
+
"content": [
|
|
20
|
+
{"type": "text", "text": "Summarize this video"},
|
|
21
|
+
file_content_part("file_abc123"),
|
|
22
|
+
],
|
|
23
|
+
}]
|
|
24
|
+
"""
|
|
25
|
+
return {"type": "file", "file": {"file_id": file_id}}
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def file_content_part_from_path(path: str, mime_type: Optional[str] = None) -> dict:
|
|
29
|
+
"""Build an inline (base64) file content part from a local file path.
|
|
30
|
+
|
|
31
|
+
Reads the file, base64-encodes its bytes, and embeds them as a ``data:`` URL.
|
|
32
|
+
The MIME type is inferred from the file extension when not provided.
|
|
33
|
+
|
|
34
|
+
Usage::
|
|
35
|
+
|
|
36
|
+
messages=[{
|
|
37
|
+
"role": "user",
|
|
38
|
+
"content": [
|
|
39
|
+
{"type": "text", "text": "Describe this clip"},
|
|
40
|
+
file_content_part_from_path("clip.mp4"),
|
|
41
|
+
],
|
|
42
|
+
}]
|
|
43
|
+
"""
|
|
44
|
+
if mime_type is None:
|
|
45
|
+
mime_type, _ = mimetypes.guess_type(path)
|
|
46
|
+
if mime_type is None:
|
|
47
|
+
mime_type = "application/octet-stream"
|
|
48
|
+
with open(path, "rb") as f:
|
|
49
|
+
data = f.read()
|
|
50
|
+
b64 = base64.b64encode(data).decode("ascii")
|
|
51
|
+
return {
|
|
52
|
+
"type": "file",
|
|
53
|
+
"file": {
|
|
54
|
+
"file_data": f"data:{mime_type};base64,{b64}",
|
|
55
|
+
"filename": os.path.basename(path),
|
|
56
|
+
},
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
class Files(MaitaiClient):
|
|
61
|
+
"""Upload files once and reference them by ``file_id`` across requests.
|
|
62
|
+
|
|
63
|
+
Two ways to send a file to ``chat.completions``:
|
|
64
|
+
|
|
65
|
+
1. **Inline** — attach it directly with ``file_content_part_from_path`` and
|
|
66
|
+
Maitai stores it as part of the request (nothing to pre-upload).
|
|
67
|
+
2. **Pre-upload** — call ``upload`` once to get a ``file_id``, then reference
|
|
68
|
+
it with ``file_content_part(file_id)`` on any number of later requests,
|
|
69
|
+
avoiding re-sending the bytes each time.
|
|
70
|
+
"""
|
|
71
|
+
|
|
72
|
+
def __init__(self, config: Config):
|
|
73
|
+
super().__init__()
|
|
74
|
+
self.config = config
|
|
75
|
+
|
|
76
|
+
def upload(
|
|
77
|
+
self,
|
|
78
|
+
path: str,
|
|
79
|
+
mime_type: Optional[str] = None,
|
|
80
|
+
) -> str:
|
|
81
|
+
"""Upload a file and return its Maitai ``file_id``.
|
|
82
|
+
|
|
83
|
+
Args:
|
|
84
|
+
path: Local path to the file to upload.
|
|
85
|
+
mime_type: Optional MIME type. Inferred from the file extension when
|
|
86
|
+
not provided.
|
|
87
|
+
|
|
88
|
+
Returns:
|
|
89
|
+
The ``file_id`` to pass to ``file_content_part(file_id)``.
|
|
90
|
+
|
|
91
|
+
Usage::
|
|
92
|
+
|
|
93
|
+
file_id = client.files.upload("clip.mp4")
|
|
94
|
+
messages = [{
|
|
95
|
+
"role": "user",
|
|
96
|
+
"content": [
|
|
97
|
+
{"type": "text", "text": "Summarize this video"},
|
|
98
|
+
maitai.file_content_part(file_id),
|
|
99
|
+
],
|
|
100
|
+
}]
|
|
101
|
+
"""
|
|
102
|
+
with open(path, "rb") as f:
|
|
103
|
+
data = f.read()
|
|
104
|
+
return self.upload_bytes(data, os.path.basename(path), mime_type)
|
|
105
|
+
|
|
106
|
+
def upload_bytes(
|
|
107
|
+
self,
|
|
108
|
+
data: Union[bytes, bytearray],
|
|
109
|
+
filename: str,
|
|
110
|
+
mime_type: Optional[str] = None,
|
|
111
|
+
) -> str:
|
|
112
|
+
"""Upload raw bytes and return the Maitai ``file_id``.
|
|
113
|
+
|
|
114
|
+
Args:
|
|
115
|
+
data: The file bytes.
|
|
116
|
+
filename: A filename (used for metadata and MIME inference).
|
|
117
|
+
mime_type: Optional MIME type. Inferred from ``filename`` when not
|
|
118
|
+
provided.
|
|
119
|
+
"""
|
|
120
|
+
if mime_type is None:
|
|
121
|
+
mime_type, _ = mimetypes.guess_type(filename)
|
|
122
|
+
if mime_type is None:
|
|
123
|
+
mime_type = "application/octet-stream"
|
|
124
|
+
|
|
125
|
+
url = f"{self.config.maitai_host}/files"
|
|
126
|
+
headers = {
|
|
127
|
+
"x-api-key": self.config.api_key,
|
|
128
|
+
"User-Agent": version,
|
|
129
|
+
}
|
|
130
|
+
client = self.get_client()
|
|
131
|
+
try:
|
|
132
|
+
response = client.post(
|
|
133
|
+
url,
|
|
134
|
+
headers=headers,
|
|
135
|
+
files={"file": (filename, bytes(data), mime_type)},
|
|
136
|
+
timeout=120,
|
|
137
|
+
)
|
|
138
|
+
except Exception as e:
|
|
139
|
+
self.log_error(self.config.api_key, str(e), url)
|
|
140
|
+
raise MaitaiConnectionError(f"Failed to upload file. Error: {e}") from None
|
|
141
|
+
if response.status_code != 200:
|
|
142
|
+
raise BadRequestError(
|
|
143
|
+
f"Failed to upload file ({response.status_code}): {response.text}"
|
|
144
|
+
)
|
|
145
|
+
return response.json()["file_id"]
|
|
@@ -0,0 +1,300 @@
|
|
|
1
|
+
"""Fire-and-forget logging of bring-your-own-inference request/response pairs.
|
|
2
|
+
|
|
3
|
+
``maitai.log()`` lets a caller run inference with their own provider SDK
|
|
4
|
+
(OpenAI, Anthropic, Gemini, ...) and ship the raw request/response pair to
|
|
5
|
+
Maitai for logging and monitoring. Maitai does NOT perform the inference on this
|
|
6
|
+
path. The pair is normalized server-side (by ``provider``) into Maitai's
|
|
7
|
+
OpenAI-compatible schema and flows through the same pipeline as proxied
|
|
8
|
+
requests, so monitors run against it.
|
|
9
|
+
|
|
10
|
+
Design goals:
|
|
11
|
+
* Non-blocking: sends happen on a background thread (sync) or task (async).
|
|
12
|
+
* Never raises into the caller's path: all errors are swallowed + reported to
|
|
13
|
+
Maitai's error metric, so logging can never break the host application.
|
|
14
|
+
* Cheap to disable/sample: a kill-switch and client-side sample rate let
|
|
15
|
+
callers dial volume without touching call sites.
|
|
16
|
+
"""
|
|
17
|
+
|
|
18
|
+
import asyncio
|
|
19
|
+
import atexit
|
|
20
|
+
import logging
|
|
21
|
+
import os
|
|
22
|
+
import random
|
|
23
|
+
import traceback
|
|
24
|
+
import weakref
|
|
25
|
+
from typing import Any, Dict, Optional, Union
|
|
26
|
+
|
|
27
|
+
from maitai._config import Config
|
|
28
|
+
from maitai._maitai_client import MaitaiClient
|
|
29
|
+
from maitai._utils import __version__ as version
|
|
30
|
+
from maitai.models.chat import LogCompletionRequest
|
|
31
|
+
from maitai.models.metric import RequestTimingMetric
|
|
32
|
+
|
|
33
|
+
logger = logging.getLogger("maitai")
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def _env_flag(name: str, default: bool) -> bool:
|
|
37
|
+
raw = os.environ.get(name)
|
|
38
|
+
if raw is None:
|
|
39
|
+
return default
|
|
40
|
+
return raw.strip().lower() not in ("0", "false", "no", "off", "")
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def _env_float(name: str) -> Optional[float]:
|
|
44
|
+
raw = os.environ.get(name)
|
|
45
|
+
if raw is None:
|
|
46
|
+
return None
|
|
47
|
+
try:
|
|
48
|
+
return float(raw)
|
|
49
|
+
except ValueError:
|
|
50
|
+
return None
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def _to_dict(obj: Any) -> Dict[str, Any]:
|
|
54
|
+
"""Best-effort serialize a provider request/response into a plain dict.
|
|
55
|
+
|
|
56
|
+
Handles pydantic models (OpenAI v1, Anthropic, google-genai responses),
|
|
57
|
+
objects exposing ``to_dict()``/``model_dump()``, and plain dicts. Anything
|
|
58
|
+
else falls back to ``vars()`` or an empty dict — logging must never raise.
|
|
59
|
+
"""
|
|
60
|
+
if obj is None:
|
|
61
|
+
return {}
|
|
62
|
+
if isinstance(obj, dict):
|
|
63
|
+
return obj
|
|
64
|
+
for attr in ("model_dump", "to_dict", "dict"):
|
|
65
|
+
fn = getattr(obj, attr, None)
|
|
66
|
+
if callable(fn):
|
|
67
|
+
try:
|
|
68
|
+
result = fn()
|
|
69
|
+
if isinstance(result, dict):
|
|
70
|
+
return result
|
|
71
|
+
except Exception:
|
|
72
|
+
continue
|
|
73
|
+
try:
|
|
74
|
+
return dict(vars(obj))
|
|
75
|
+
except Exception:
|
|
76
|
+
return {}
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
class Logger(MaitaiClient):
|
|
80
|
+
"""Backs ``maitai.log()`` / ``maitai.log_async()``."""
|
|
81
|
+
|
|
82
|
+
def __init__(self, config: Config):
|
|
83
|
+
super().__init__()
|
|
84
|
+
self.config = config
|
|
85
|
+
# Hold strong refs to in-flight async send tasks; asyncio only keeps a
|
|
86
|
+
# weak reference, so without this a task can be GC'd before it runs.
|
|
87
|
+
self._pending_tasks: set = set()
|
|
88
|
+
# Kill-switch: env var overrides the default-on behavior.
|
|
89
|
+
self.enabled = _env_flag("MAITAI_LOGGING_ENABLED", True)
|
|
90
|
+
# Client-side sampling: fraction of events to actually send (0.0-1.0).
|
|
91
|
+
env_rate = _env_float("MAITAI_LOG_SAMPLE_RATE")
|
|
92
|
+
self.default_sample_rate = env_rate if env_rate is not None else 1.0
|
|
93
|
+
# Drain queued sends on interpreter exit so short-lived processes
|
|
94
|
+
# (scripts, lambdas) don't drop in-flight logs. weakref avoids keeping
|
|
95
|
+
# the Logger alive solely for the atexit registration.
|
|
96
|
+
_self_ref = weakref.ref(self)
|
|
97
|
+
|
|
98
|
+
def _atexit_flush():
|
|
99
|
+
inst = _self_ref()
|
|
100
|
+
if inst is not None:
|
|
101
|
+
inst.shutdown()
|
|
102
|
+
|
|
103
|
+
atexit.register(_atexit_flush)
|
|
104
|
+
|
|
105
|
+
# -- public API --------------------------------------------------------
|
|
106
|
+
|
|
107
|
+
def log(
|
|
108
|
+
self,
|
|
109
|
+
*,
|
|
110
|
+
intent: str,
|
|
111
|
+
application: str,
|
|
112
|
+
provider: str,
|
|
113
|
+
request: Any,
|
|
114
|
+
response: Any,
|
|
115
|
+
timing: Optional[RequestTimingMetric] = None,
|
|
116
|
+
session_id: Optional[str] = None,
|
|
117
|
+
reference_id: Union[str, int, None] = None,
|
|
118
|
+
user_id: Optional[str] = None,
|
|
119
|
+
metadata: Optional[dict] = None,
|
|
120
|
+
sample_rate: Optional[float] = None,
|
|
121
|
+
) -> None:
|
|
122
|
+
"""Queue a request/response pair for logging (returns immediately).
|
|
123
|
+
|
|
124
|
+
``request``/``response`` are the provider's native payloads (dicts or
|
|
125
|
+
SDK objects). ``provider`` is one of ``openai`` (any OpenAI-compatible
|
|
126
|
+
API), ``anthropic``, or ``gemini``.
|
|
127
|
+
"""
|
|
128
|
+
log_request = self._build_request(
|
|
129
|
+
intent=intent,
|
|
130
|
+
application=application,
|
|
131
|
+
provider=provider,
|
|
132
|
+
request=request,
|
|
133
|
+
response=response,
|
|
134
|
+
timing=timing,
|
|
135
|
+
session_id=session_id,
|
|
136
|
+
reference_id=reference_id,
|
|
137
|
+
user_id=user_id,
|
|
138
|
+
metadata=metadata,
|
|
139
|
+
sample_rate=sample_rate,
|
|
140
|
+
)
|
|
141
|
+
if log_request is None:
|
|
142
|
+
return
|
|
143
|
+
try:
|
|
144
|
+
self.executor.submit(self._send_log, log_request)
|
|
145
|
+
except RuntimeError:
|
|
146
|
+
# Executor already shut down (e.g. after flush()/atexit). Drop the
|
|
147
|
+
# event rather than raise into the caller's path.
|
|
148
|
+
pass
|
|
149
|
+
|
|
150
|
+
async def log_async(
|
|
151
|
+
self,
|
|
152
|
+
*,
|
|
153
|
+
intent: str,
|
|
154
|
+
application: str,
|
|
155
|
+
provider: str,
|
|
156
|
+
request: Any,
|
|
157
|
+
response: Any,
|
|
158
|
+
timing: Optional[RequestTimingMetric] = None,
|
|
159
|
+
session_id: Optional[str] = None,
|
|
160
|
+
reference_id: Union[str, int, None] = None,
|
|
161
|
+
user_id: Optional[str] = None,
|
|
162
|
+
metadata: Optional[dict] = None,
|
|
163
|
+
sample_rate: Optional[float] = None,
|
|
164
|
+
) -> None:
|
|
165
|
+
"""Async fire-and-forget variant of :meth:`log`."""
|
|
166
|
+
log_request = self._build_request(
|
|
167
|
+
intent=intent,
|
|
168
|
+
application=application,
|
|
169
|
+
provider=provider,
|
|
170
|
+
request=request,
|
|
171
|
+
response=response,
|
|
172
|
+
timing=timing,
|
|
173
|
+
session_id=session_id,
|
|
174
|
+
reference_id=reference_id,
|
|
175
|
+
user_id=user_id,
|
|
176
|
+
metadata=metadata,
|
|
177
|
+
sample_rate=sample_rate,
|
|
178
|
+
)
|
|
179
|
+
if log_request is None:
|
|
180
|
+
return
|
|
181
|
+
try:
|
|
182
|
+
task = asyncio.create_task(self._send_log_async(log_request))
|
|
183
|
+
except RuntimeError:
|
|
184
|
+
# No running loop (e.g. interpreter teardown). Drop, don't raise.
|
|
185
|
+
return
|
|
186
|
+
self._pending_tasks.add(task)
|
|
187
|
+
task.add_done_callback(self._pending_tasks.discard)
|
|
188
|
+
|
|
189
|
+
def flush(self) -> None:
|
|
190
|
+
"""Block until queued sync logs have been sent.
|
|
191
|
+
|
|
192
|
+
Useful for short-lived processes (scripts, lambdas) that would
|
|
193
|
+
otherwise exit before background sends complete.
|
|
194
|
+
"""
|
|
195
|
+
# ThreadPoolExecutor has no public join; shutdown(wait=True) drains the
|
|
196
|
+
# queue, then we recreate the executor so the logger stays usable.
|
|
197
|
+
import concurrent.futures
|
|
198
|
+
|
|
199
|
+
self.executor.shutdown(wait=True)
|
|
200
|
+
self.executor = concurrent.futures.ThreadPoolExecutor()
|
|
201
|
+
|
|
202
|
+
def shutdown(self) -> None:
|
|
203
|
+
"""Drain and tear down background workers. Safe to call multiple times."""
|
|
204
|
+
try:
|
|
205
|
+
self.executor.shutdown(wait=True)
|
|
206
|
+
except Exception:
|
|
207
|
+
pass
|
|
208
|
+
|
|
209
|
+
# -- internals ---------------------------------------------------------
|
|
210
|
+
|
|
211
|
+
def _safe_api_key(self) -> str:
|
|
212
|
+
"""Read the API key without raising. ``config.api_key`` is a property
|
|
213
|
+
that raises ValueError when unset; the error/headers paths must never
|
|
214
|
+
propagate that into the caller."""
|
|
215
|
+
try:
|
|
216
|
+
return self.config.api_key
|
|
217
|
+
except Exception:
|
|
218
|
+
return getattr(self.config, "_api_key", None) or ""
|
|
219
|
+
|
|
220
|
+
def _should_sample(self, sample_rate: Optional[float]) -> bool:
|
|
221
|
+
rate = sample_rate if sample_rate is not None else self.default_sample_rate
|
|
222
|
+
if rate >= 1.0:
|
|
223
|
+
return True
|
|
224
|
+
if rate <= 0.0:
|
|
225
|
+
return False
|
|
226
|
+
return random.random() < rate
|
|
227
|
+
|
|
228
|
+
def _build_request(
|
|
229
|
+
self,
|
|
230
|
+
*,
|
|
231
|
+
intent: str,
|
|
232
|
+
application: str,
|
|
233
|
+
provider: str,
|
|
234
|
+
request: Any,
|
|
235
|
+
response: Any,
|
|
236
|
+
timing: Optional[RequestTimingMetric],
|
|
237
|
+
session_id: Optional[str],
|
|
238
|
+
reference_id: Union[str, int, None],
|
|
239
|
+
user_id: Optional[str],
|
|
240
|
+
metadata: Optional[dict],
|
|
241
|
+
sample_rate: Optional[float],
|
|
242
|
+
) -> Optional[LogCompletionRequest]:
|
|
243
|
+
"""Validate, gate (kill-switch + sampling), and serialize. Returns None
|
|
244
|
+
when the event should be dropped or building fails — never raises."""
|
|
245
|
+
if not self.enabled:
|
|
246
|
+
return None
|
|
247
|
+
if not self._should_sample(sample_rate):
|
|
248
|
+
return None
|
|
249
|
+
try:
|
|
250
|
+
effective_rate = (
|
|
251
|
+
sample_rate if sample_rate is not None else self.default_sample_rate
|
|
252
|
+
)
|
|
253
|
+
return LogCompletionRequest(
|
|
254
|
+
provider=str(provider),
|
|
255
|
+
action_type=intent,
|
|
256
|
+
application_ref_name=application,
|
|
257
|
+
request=_to_dict(request),
|
|
258
|
+
response=_to_dict(response),
|
|
259
|
+
timing_metrics=timing,
|
|
260
|
+
session_id=session_id,
|
|
261
|
+
reference_id=reference_id,
|
|
262
|
+
user_id=user_id,
|
|
263
|
+
metadata=metadata or None,
|
|
264
|
+
sample_rate=effective_rate,
|
|
265
|
+
)
|
|
266
|
+
except Exception:
|
|
267
|
+
# Bad inputs must not break the caller; report and drop.
|
|
268
|
+
self.log_error(self._safe_api_key(), traceback.format_exc(), "log")
|
|
269
|
+
return None
|
|
270
|
+
|
|
271
|
+
def _log_url(self) -> str:
|
|
272
|
+
host = self.config.maitai_inference_host
|
|
273
|
+
return f"{host}/chat/completions/log"
|
|
274
|
+
|
|
275
|
+
def _headers(self) -> Dict[str, str]:
|
|
276
|
+
return {
|
|
277
|
+
"Content-Type": "application/json",
|
|
278
|
+
"x-api-key": self._safe_api_key(),
|
|
279
|
+
"User-Agent": version,
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
def _send_log(self, log_request: LogCompletionRequest) -> None:
|
|
283
|
+
url = self._log_url()
|
|
284
|
+
try:
|
|
285
|
+
client = self.get_client()
|
|
286
|
+
client.put(url, headers=self._headers(), json=log_request.model_dump())
|
|
287
|
+
except Exception:
|
|
288
|
+
self.log_error(self._safe_api_key(), traceback.format_exc(), url)
|
|
289
|
+
|
|
290
|
+
async def _send_log_async(self, log_request: LogCompletionRequest) -> None:
|
|
291
|
+
url = self._log_url()
|
|
292
|
+
try:
|
|
293
|
+
client = self.get_async_client()
|
|
294
|
+
await client.put(
|
|
295
|
+
url, headers=self._headers(), json=log_request.model_dump()
|
|
296
|
+
)
|
|
297
|
+
except Exception:
|
|
298
|
+
await self.log_error_async(
|
|
299
|
+
self._safe_api_key(), traceback.format_exc(), url
|
|
300
|
+
)
|
|
@@ -8,6 +8,8 @@ import openai
|
|
|
8
8
|
|
|
9
9
|
from maitai._config import Config
|
|
10
10
|
from maitai._context import ContextManager
|
|
11
|
+
from maitai._files import Files
|
|
12
|
+
from maitai._logger import Logger
|
|
11
13
|
from maitai.agent._completions import Completions as AgentCompletions
|
|
12
14
|
from maitai.chat._completions import Completions
|
|
13
15
|
from maitai.models.chat import AzureParams, ClientParams
|
|
@@ -176,9 +178,12 @@ class Maitai:
|
|
|
176
178
|
self.config, self._openai_client, self._groq_client, client_params
|
|
177
179
|
)
|
|
178
180
|
self.audio = Audio(self.config)
|
|
181
|
+
self.files = Files(self.config)
|
|
179
182
|
self.agent = Agent(self.config)
|
|
180
183
|
self.workflow = Workflow(self.config)
|
|
181
184
|
self.context = ContextManager(self.config)
|
|
185
|
+
self._logger = Logger(self.config)
|
|
186
|
+
self.log = self._logger.log
|
|
182
187
|
|
|
183
188
|
|
|
184
189
|
class Chat:
|
|
@@ -207,7 +212,25 @@ class Agent:
|
|
|
207
212
|
self,
|
|
208
213
|
config: Config,
|
|
209
214
|
):
|
|
215
|
+
from maitai.agent._handle import AgentResolver
|
|
216
|
+
|
|
210
217
|
self.completions = AgentCompletions(config)
|
|
218
|
+
self._resolver = AgentResolver(config)
|
|
219
|
+
|
|
220
|
+
def get(
|
|
221
|
+
self,
|
|
222
|
+
agent: str,
|
|
223
|
+
*,
|
|
224
|
+
version: Optional[str] = None,
|
|
225
|
+
release: Optional[str] = None,
|
|
226
|
+
session_id: Optional[str] = None,
|
|
227
|
+
):
|
|
228
|
+
return self._resolver.get(
|
|
229
|
+
agent,
|
|
230
|
+
version=version,
|
|
231
|
+
release=release,
|
|
232
|
+
session_id=session_id,
|
|
233
|
+
)
|
|
211
234
|
|
|
212
235
|
|
|
213
236
|
class Workflow:
|
|
@@ -1,18 +1,21 @@
|
|
|
1
1
|
import logging
|
|
2
2
|
import os
|
|
3
|
-
from typing import Mapping, Optional, Union
|
|
3
|
+
from typing import Any, Dict, Mapping, Optional, Union
|
|
4
4
|
|
|
5
5
|
import groq
|
|
6
6
|
import httpx
|
|
7
7
|
import openai
|
|
8
8
|
|
|
9
9
|
from maitai._config import Config
|
|
10
|
+
from maitai._logger import Logger
|
|
10
11
|
from maitai.agent._completions_async import AsyncCompletions as AsyncAgentCompletions
|
|
11
12
|
from maitai.chat._completions_async import AsyncCompletions
|
|
12
13
|
from maitai.models.chat import AzureParams, ClientParams
|
|
13
14
|
from maitai.models.key import Key
|
|
14
15
|
from maitai.transcriptions._transcriptions_async import AsyncTranscriptions
|
|
15
|
-
from maitai.workflow._completions_async import
|
|
16
|
+
from maitai.workflow._completions_async import (
|
|
17
|
+
AsyncCompletions as AsyncWorkflowCompletions,
|
|
18
|
+
)
|
|
16
19
|
|
|
17
20
|
logger = logging.getLogger("maitai")
|
|
18
21
|
|
|
@@ -176,6 +179,8 @@ class MaitaiAsync:
|
|
|
176
179
|
self.audio = AsyncAudio(self.config)
|
|
177
180
|
self.agent = AsyncAgent(self.config)
|
|
178
181
|
self.workflow = AsyncWorkflow(self.config)
|
|
182
|
+
self._logger = Logger(self.config)
|
|
183
|
+
self.log = self._logger.log_async
|
|
179
184
|
|
|
180
185
|
|
|
181
186
|
class AsyncChat:
|
|
@@ -204,7 +209,39 @@ class AsyncAgent:
|
|
|
204
209
|
self,
|
|
205
210
|
config: Config,
|
|
206
211
|
):
|
|
212
|
+
from maitai.agent._handle import AgentResolver
|
|
213
|
+
|
|
207
214
|
self.completions = AsyncAgentCompletions(config)
|
|
215
|
+
self._resolver = AgentResolver(config)
|
|
216
|
+
|
|
217
|
+
async def get(
|
|
218
|
+
self,
|
|
219
|
+
agent: str,
|
|
220
|
+
*,
|
|
221
|
+
version: Optional[str] = None,
|
|
222
|
+
release: Optional[str] = None,
|
|
223
|
+
session_id: Optional[str] = None,
|
|
224
|
+
):
|
|
225
|
+
import httpx
|
|
226
|
+
|
|
227
|
+
from maitai.agent._handle import AgentHandle, _normalize_agent_target
|
|
228
|
+
|
|
229
|
+
base = self._resolver.config.maitai_orchestration_host.rstrip("/")
|
|
230
|
+
params: Dict[str, Any] = {
|
|
231
|
+
"agent": _normalize_agent_target(agent, version=version, release=release)
|
|
232
|
+
}
|
|
233
|
+
if session_id:
|
|
234
|
+
params["session_id"] = session_id
|
|
235
|
+
|
|
236
|
+
async with httpx.AsyncClient() as client:
|
|
237
|
+
response = await client.get(
|
|
238
|
+
f"{base}/orchestration/resolve",
|
|
239
|
+
params=params,
|
|
240
|
+
headers={"x-api-key": self._resolver.config.api_key},
|
|
241
|
+
timeout=30.0,
|
|
242
|
+
)
|
|
243
|
+
response.raise_for_status()
|
|
244
|
+
return AgentHandle(response.json(), self._resolver.config)
|
|
208
245
|
|
|
209
246
|
|
|
210
247
|
class AsyncWorkflow:
|