cogent-sdk 0.1.2__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.
@@ -0,0 +1,191 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship made available under
36
+ the License, as indicated by a copyright notice that is included in
37
+ or attached to the work (an example is provided in the Appendix below).
38
+
39
+ "Derivative Works" shall mean any work, whether in Source or Object
40
+ form, that is based on (or derived from) the Work and for which the
41
+ editorial revisions, annotations, elaborations, or other modifications
42
+ represent, as a whole, an original work of authorship. For the purposes
43
+ of this License, Derivative Works shall not include works that remain
44
+ separable from, or merely link (or bind by name) to the interfaces of,
45
+ the Work and Derivative Works thereof.
46
+
47
+ "Contribution" shall mean, as submitted to the Licensor for inclusion
48
+ in the Work by the copyright owner or by an individual or Legal Entity
49
+ authorized to submit on behalf of the copyright owner. For the purposes
50
+ of this definition, "submit" means any form of electronic, verbal, or
51
+ written communication sent to the Licensor or its representatives,
52
+ including but not limited to communication on electronic mailing lists,
53
+ source code control systems, and issue tracking systems that are managed
54
+ by, or on behalf of, the Licensor for the purpose of developing and
55
+ improving the Work, but excluding communication that is conspicuously
56
+ marked or designated in writing by the copyright owner as "Not a
57
+ Contribution."
58
+
59
+ "Contributor" shall mean Licensor and any Legal Entity on behalf of
60
+ whom a Contribution has been received by the Licensor and included
61
+ within the Work.
62
+
63
+ 2. Grant of Copyright License. Subject to the terms and conditions of
64
+ this License, each Contributor hereby grants to You a perpetual,
65
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
66
+ copyright license to reproduce, prepare Derivative Works of,
67
+ publicly display, publicly perform, sublicense, and distribute the
68
+ Work and such Derivative Works in Source or Object form.
69
+
70
+ 3. Grant of Patent License. Subject to the terms and conditions of
71
+ this License, each Contributor hereby grants to You a perpetual,
72
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
73
+ (except as stated in this section) patent license to make, have made,
74
+ use, offer to sell, sell, import, and otherwise transfer the Work,
75
+ where such license applies only to those patent claims licensable
76
+ by such Contributor that are necessarily infringed by their
77
+ Contribution(s) alone or by the combination of their Contribution(s)
78
+ with the Work to which such Contribution(s) was submitted. If You
79
+ institute patent litigation against any entity (including a cross-claim
80
+ or counterclaim in a lawsuit) alleging that the Work or any
81
+ Contributor's patent claims are necessarily infringed by one or more
82
+ features of the Work, you may terminate your license from the
83
+ Contributor as of the date such litigation is filed.
84
+
85
+ 4. Redistribution. You may reproduce and distribute copies of the
86
+ Work or Derivative Works thereof in any medium, with or without
87
+ modifications, and in Source or Object form, provided that You
88
+ meet the following conditions:
89
+
90
+ (a) You must give any other recipients of the Work or Derivative Works
91
+ a copy of this License; and
92
+
93
+ (b) You must cause any modified files to carry prominent notices
94
+ stating that You changed the files; and
95
+
96
+ (c) You must retain, in the Source form of any Derivative Works that
97
+ You distribute, all copyright, patent, trademark, and attribution
98
+ notices from the Source form of the Work, excluding those notices
99
+ that do not pertain to any part of the Derivative Works; and
100
+
101
+ (d) If the Work includes a "NOTICE" text file as part of its
102
+ distribution, You must include a readable copy of the attribution
103
+ notices contained within such NOTICE file, in at least one of the
104
+ following places: within a NOTICE text file distributed as part of
105
+ the Derivative Works; within the Source form or documentation, if
106
+ provided along with the Derivative Works; or, within a display
107
+ generated by the Derivative Works, if and wherever such third-party
108
+ notices normally appear. The contents of the NOTICE file are for
109
+ informational purposes only and do not modify the License. You may
110
+ add Your own attribution notices within Derivative Works that You
111
+ distribute, alongside or as an addendum to the NOTICE text from the
112
+ Work, provided that such additional attribution notices cannot be
113
+ construed as modifying the License.
114
+
115
+ You may add Your own license statement for Your modifications and
116
+ may provide additional grant of rights to use, copy, modify, merge,
117
+ publish, distribute, sublicense, and/or sell copies of the
118
+ Derivative Works, and to permit persons to whom the Derivative Works
119
+ is furnished to do so, subject to the following conditions described
120
+ in this License.
121
+
122
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
123
+ any Contribution intentionally submitted for inclusion in the Work
124
+ by You to the Licensor shall be under the terms and conditions of
125
+ this License, without any additional terms or conditions.
126
+ Notwithstanding the above, nothing herein shall supersede or modify
127
+ the terms of any separate license agreement you may have executed
128
+ with Licensor regarding such Contributions.
129
+
130
+ 6. Trademarks. This License does not grant permission to use the trade
131
+ names, trademarks, service marks, or product names of the Licensor,
132
+ except as required for reasonable and customary use in describing the
133
+ origin of the Work and reproducing the content of the NOTICE file.
134
+
135
+ 7. Disclaimer of Warranty. Unless required by applicable law or agreed
136
+ to in writing, Licensor provides the Work (and each Contributor
137
+ provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES
138
+ OR CONDITIONS OF ANY KIND, either express or implied, including,
139
+ without limitation, any warranties or conditions of TITLE,
140
+ NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR
141
+ PURPOSE. You are solely responsible for determining the
142
+ appropriateness of using or reproducing the Work and assume any
143
+ risks associated with Your exercise of permissions under this License.
144
+
145
+ 8. Limitation of Liability. In no event and under no legal theory,
146
+ whether in tort (including negligence), contract, or otherwise,
147
+ unless required by applicable law (such as deliberate and grossly
148
+ negligent acts) or agreed to in writing, shall any Contributor be
149
+ liable to You for damages, including any direct, indirect, special,
150
+ incidental, or exemplary damages of any character arising as a result
151
+ of this License or out of the use or inability to use the Work
152
+ (including but not limited to damages for loss of goodwill, work
153
+ stoppage, computer failure or malfunction, or all other commercial
154
+ damages or losses), even if such Contributor has been advised of the
155
+ possibility of such damages.
156
+
157
+ 9. Accepting Warranty or Additional Liability. While redistributing
158
+ the Work or Derivative Works thereof, You may offer, and charge a fee
159
+ for, acceptance of support, warranty, indemnity, or other liability
160
+ obligations and/or rights consistent with this License. However, in
161
+ accepting such obligations, You may offer such obligations only on Your
162
+ own behalf and on a full indemnity basis, not on behalf of any other
163
+ Contributor, and only if You agree to indemnify, defend, and hold each
164
+ Contributor harmless for any liability incurred by, or claims asserted
165
+ against, such Contributor by reason of your accepting any such
166
+ warranty or additional liability.
167
+
168
+ END OF TERMS AND CONDITIONS
169
+
170
+ APPENDIX: How to apply the Apache License to your work.
171
+
172
+ To apply the Apache License to your work, attach the following
173
+ boilerplate notice, with the fields enclosed by brackets "[]"
174
+ replaced with your own identifying information. (Don't include
175
+ the brackets!) The text should be enclosed in the appropriate
176
+ comment syntax for the format in question. Please also include a
177
+ copy of the License with the work.
178
+
179
+ Copyright 2025 Cogent Contributors
180
+
181
+ Licensed under the Apache License, Version 2.0 (the "License");
182
+ you may not use this file except in compliance with the License.
183
+ You may obtain a copy of the License at
184
+
185
+ http://www.apache.org/licenses/LICENSE-2.0
186
+
187
+ Unless required by applicable law or agreed to in writing, software
188
+ distributed under the License is distributed on an "AS IS" BASIS,
189
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
190
+ See the License for the specific language governing permissions and
191
+ limitations under the License.
@@ -0,0 +1,14 @@
1
+ Metadata-Version: 2.4
2
+ Name: cogent-sdk
3
+ Version: 0.1.2
4
+ Summary: Stream-first observability for distributed LLM agents
5
+ Requires-Python: >=3.11
6
+ License-File: LICENSE
7
+ Provides-Extra: sdk
8
+ Requires-Dist: kafka-python>=2.0; extra == "sdk"
9
+ Requires-Dist: pydantic>=2.0; extra == "sdk"
10
+ Requires-Dist: minio>=7.0; extra == "sdk"
11
+ Provides-Extra: dev
12
+ Requires-Dist: pytest>=7.0; extra == "dev"
13
+ Requires-Dist: pytest-asyncio>=0.23; extra == "dev"
14
+ Dynamic: license-file
@@ -0,0 +1,180 @@
1
+ # Cogent
2
+
3
+ **Self-hosted observability for LLM agents.** Every call, every tool use, every handoff — streamed, stored, searchable. Apache 2.0.
4
+
5
+ ---
6
+
7
+ ## Why Cogent
8
+
9
+ You built an agent. Now it's in production and something is wrong — a loop that ran 400 times, a prompt that cost $12, a tool that silently returned garbage. You have no idea what happened.
10
+
11
+ Cogent gives you the trace. Three lines of instrumentation code. Zero coupling to your agent logic. If the observability stack goes down, your agents keep running — they emit fire-and-forget events and move on.
12
+
13
+ Built for the numbers that break SaaS tools: gigabyte traces, megabyte prompts, agents that call agents that call tools at 3 AM.
14
+
15
+ ---
16
+
17
+ ## Quickstart
18
+
19
+ ```bash
20
+ git clone https://github.com/cogent/cogent && cd cogent
21
+ cp .env.example .env
22
+ make up
23
+ ```
24
+
25
+ > **macOS + Colima:** run `colima ssh -- sudo sysctl -w vm.max_map_count=2000000` once after `colima start` — Doris needs it.
26
+
27
+ Then send some traces:
28
+
29
+ ```bash
30
+ pip install cogent-sdk
31
+ python examples/single_agent.py
32
+ python examples/multi_agent.py
33
+ ```
34
+
35
+ Open **http://localhost:8090** — traces appear within seconds.
36
+
37
+ ---
38
+
39
+ ## What you get
40
+
41
+ ```
42
+ Trace list Trace waterfall
43
+ ───────────────────────────── ───────────────────────────────────────
44
+ Trace ID Agent Cost orchestrator 420ms $0.006
45
+ a1b2c3.. risk-scorer $0.002 └─ data-fetcher 12ms tool
46
+ d4e5f6.. support-bot $0.001 └─ sentiment-analy 88ms $0.001
47
+ g7h8i9.. planner $0.008 └─ risk-scorer 310ms $0.002
48
+ ✓ score: 0.91
49
+ ```
50
+
51
+ **Trace view** — every span in the run, indented by depth, with duration, cost, and eval badge.
52
+
53
+ **Span detail** — prompt/completion preview inline; click to load the full payload from S3.
54
+
55
+ **Full-text search** — `GET /api/search?q=acct_8821` finds every span that mentioned it.
56
+
57
+ **Human annotation** — score any span with a label, justification, and 0–1 score. Stored alongside LLM eval scores.
58
+
59
+ **Grafana dashboards** — token spend, cost per agent, latency percentiles, eval score trends. Available at `http://localhost:3000`.
60
+
61
+ ---
62
+
63
+ ## Instrument your agent in three lines
64
+
65
+ ```python
66
+ from cogent.sdk import AgentTelemetry, PayloadOffloader
67
+
68
+ tel = AgentTelemetry(
69
+ bootstrap_servers="localhost:19092",
70
+ offloader=PayloadOffloader(endpoint="localhost:9000", bucket="cogent-payloads"),
71
+ )
72
+
73
+ with tel.span("llm_call", agent_name="my-agent") as span:
74
+ response = llm.complete(prompt)
75
+ span.log(
76
+ prompt=prompt,
77
+ completion=response.text,
78
+ model="claude-sonnet-4-6",
79
+ input_tokens=response.usage.input,
80
+ output_tokens=response.usage.output,
81
+ cost_usd=0.003,
82
+ )
83
+ ```
84
+
85
+ Child spans inherit `trace_id` automatically — no manual ID threading.
86
+
87
+ See [`docs/user-guide.adoc`](docs/user-guide.adoc) for the full SDK reference.
88
+
89
+ ---
90
+
91
+ ## How it works
92
+
93
+ ```
94
+ Agent process
95
+ │ span.log() ← returns immediately, never blocks the agent
96
+
97
+ Redpanda (Kafka-compatible)
98
+
99
+ ├──► consumer-greptime ──► GreptimeDB time-series metadata, previews, costs
100
+ ├──► consumer-doris ──► Doris full text, inverted-index search
101
+ ├──► consumer-judge ──► auto-scores every llm_call with an LLM judge
102
+ └──► consumer-alerting ──► webhook on runaway loop / cost spike / oversized payload
103
+
104
+ └──► MinIO / S3 ◄── SDK always offloads full payloads (prompts, completions, tool I/O)
105
+ DB rows stay narrow. UI lazy-loads on click.
106
+
107
+ └──► server :8090 ── trace list, waterfall, span detail, annotation, search
108
+ ```
109
+
110
+ **Why two databases?**
111
+ GreptimeDB answers time-series queries fast (dashboard, trace list). Doris answers full-text search over full prompt/completion content with a native inverted index. Every event goes to both simultaneously via independent Kafka consumer groups.
112
+
113
+ **Why Kafka?**
114
+ Decouples your agent from the observability backend completely. Agent emits and moves on. Consumer backlogs during restarts, catches up, no data loss. You can add new consumers (alerting, eval, audit) without touching agent code.
115
+
116
+ ---
117
+
118
+ ## Stack
119
+
120
+ | Component | Purpose | Local default | Production swap |
121
+ |---|---|---|---|
122
+ | Redpanda | Kafka-compatible event bus | `localhost:19092` | AutoMQ (S3-native, same protocol) |
123
+ | MinIO | Payload object store | `localhost:9000` | AWS S3, GCS |
124
+ | GreptimeDB | Hot tier — time-series queries | `localhost:4002` | GreptimeDB cluster |
125
+ | Apache Doris | Warm tier — full-text search | `localhost:9030` | Doris cluster |
126
+ | Grafana | Dashboards | `localhost:3000` | — |
127
+
128
+ ---
129
+
130
+ ## The judge
131
+
132
+ `consumer-judge` scores every `llm_call` event automatically using any OpenAI-compatible endpoint:
133
+
134
+ ```bash
135
+ ./bin/consumer-judge \
136
+ --judge-model gpt-4o-mini \
137
+ --judge-base-url https://api.openai.com/v1 \
138
+ --judge-api-key sk-... \
139
+ --judge-prompt-file /path/to/your_rubric.txt
140
+ ```
141
+
142
+ The default rubric scores relevance, faithfulness, and safety. Replace it with a domain-specific rubric — see [`deploy/prompts/judge_default.txt`](deploy/prompts/judge_default.txt) and the [user guide](docs/user-guide.adoc#the-judge).
143
+
144
+ ---
145
+
146
+ ## Building and testing
147
+
148
+ ```bash
149
+ make build-go # six Go binaries → ./bin/
150
+ make build-python # pip install -e .[sdk]
151
+ make test-go # go test ./... in services/
152
+ make test-python # pytest tests/python/
153
+ ```
154
+
155
+ ---
156
+
157
+ ## Directories
158
+
159
+ | Path | What it is |
160
+ |---|---|
161
+ | `cogent/sdk/` | Python instrumentation library — `AgentTelemetry`, `PayloadOffloader`, `@observe` |
162
+ | `examples/` | Runnable demos — single agent and multi-agent pipeline |
163
+ | `services/` | Six Go binaries — four consumers, API server, batch eval CLI |
164
+ | `deploy/` | Docker Compose, DDL, Grafana dashboards, judge prompt |
165
+ | `docs/` | Full user guide (AsciiDoc) |
166
+ | `arch/` | Architecture design docs — overview, SDK, infra, judge, server, services |
167
+
168
+ ---
169
+
170
+ ## Documentation
171
+
172
+ - **[User Guide](docs/user-guide.adoc)** — installation, SDK reference, deployment, judge, alerting, UI, batch eval
173
+ - **[Architecture](arch/overview.md)** — design principles, technology choices, storage model
174
+ - **[deploy/README.md](deploy/README.md)** — Docker Compose reference, startup order, service ports
175
+
176
+ ---
177
+
178
+ ## License
179
+
180
+ Apache 2.0 — see [LICENSE](LICENSE).
File without changes
@@ -0,0 +1,5 @@
1
+ from .telemetry import AgentTelemetry
2
+ from .offload import PayloadOffloader
3
+ from .decorators import observe, set_telemetry
4
+
5
+ __all__ = ["AgentTelemetry", "PayloadOffloader", "observe", "set_telemetry"]
@@ -0,0 +1,69 @@
1
+ from __future__ import annotations
2
+ import functools
3
+ import inspect
4
+ from typing import Optional, TYPE_CHECKING
5
+
6
+ if TYPE_CHECKING:
7
+ from .telemetry import AgentTelemetry
8
+
9
+ _telemetry_instance: Optional["AgentTelemetry"] = None
10
+
11
+
12
+ def set_telemetry(tel: "AgentTelemetry") -> None:
13
+ """Register the global AgentTelemetry instance used by @observe."""
14
+ global _telemetry_instance
15
+ _telemetry_instance = tel
16
+
17
+
18
+ def _get_telemetry() -> "AgentTelemetry":
19
+ if _telemetry_instance is None:
20
+ raise RuntimeError(
21
+ "No AgentTelemetry registered. Call cogent.set_telemetry(tel) first."
22
+ )
23
+ return _telemetry_instance
24
+
25
+
26
+ def observe(
27
+ operation: Optional[str] = None,
28
+ agent_name: str = "unknown",
29
+ **span_meta,
30
+ ):
31
+ """
32
+ Decorator that wraps sync and async functions in a Cogent span.
33
+ If the return value is str, it is passed as the completion field.
34
+ Exceptions are captured as tool_error and re-raised.
35
+ """
36
+
37
+ def decorator(fn):
38
+ op = operation or fn.__name__
39
+
40
+ if inspect.iscoroutinefunction(fn):
41
+
42
+ @functools.wraps(fn)
43
+ async def async_wrapper(*args, **kwargs):
44
+ tel = _get_telemetry()
45
+ async with tel.span(op, agent_name=agent_name, **span_meta) as span:
46
+ result = await fn(*args, **kwargs)
47
+ log_fields: dict = {}
48
+ if isinstance(result, str):
49
+ log_fields["completion"] = result
50
+ span.log(**log_fields)
51
+ return result
52
+
53
+ return async_wrapper
54
+ else:
55
+
56
+ @functools.wraps(fn)
57
+ def sync_wrapper(*args, **kwargs):
58
+ tel = _get_telemetry()
59
+ with tel.span(op, agent_name=agent_name, **span_meta) as span:
60
+ result = fn(*args, **kwargs)
61
+ log_fields: dict = {}
62
+ if isinstance(result, str):
63
+ log_fields["completion"] = result
64
+ span.log(**log_fields)
65
+ return result
66
+
67
+ return sync_wrapper
68
+
69
+ return decorator
@@ -0,0 +1,89 @@
1
+ from __future__ import annotations
2
+ import io
3
+ import logging
4
+ import threading
5
+ from typing import Optional
6
+
7
+ try:
8
+ from minio import Minio
9
+ except ImportError:
10
+ Minio = None # type: ignore[assignment,misc]
11
+
12
+ logger = logging.getLogger(__name__)
13
+
14
+ _PREVIEW_LEN = 500
15
+
16
+
17
+ class PayloadOffloader:
18
+ """
19
+ Splits every content field into a 500-char preview plus an S3 upload.
20
+ No threshold. No conditional logic. All content always goes to S3.
21
+ Pass endpoint=None for no-op mode (local dev without MinIO).
22
+ """
23
+
24
+ def __init__(
25
+ self,
26
+ endpoint: Optional[str],
27
+ bucket: str,
28
+ access_key: str,
29
+ secret_key: str,
30
+ secure: bool = False,
31
+ ) -> None:
32
+ self._bucket = bucket
33
+ self._client = None
34
+ if endpoint:
35
+ self._client = Minio(
36
+ endpoint,
37
+ access_key=access_key,
38
+ secret_key=secret_key,
39
+ secure=secure,
40
+ )
41
+
42
+ def prepare(
43
+ self,
44
+ field_name: str,
45
+ content: str,
46
+ trace_id: str,
47
+ span_id: str,
48
+ ) -> tuple[str, Optional[str], int]:
49
+ """
50
+ Returns (preview, ref_key, size_bytes).
51
+ Uploads full content to S3 in a background thread (fire and forget).
52
+ ref_key is None in no-op mode (no MinIO endpoint configured).
53
+ """
54
+ preview = content[:_PREVIEW_LEN]
55
+ encoded = content.encode()
56
+ size_bytes = len(encoded)
57
+
58
+ if self._client is None:
59
+ return preview, None, size_bytes
60
+
61
+ ref_key = f"{trace_id}/{span_id}/{field_name}"
62
+ threading.Thread(
63
+ target=self._upload,
64
+ args=(ref_key, encoded),
65
+ daemon=True,
66
+ ).start()
67
+ return preview, ref_key, size_bytes
68
+
69
+ def _upload(self, key: str, data: bytes) -> None:
70
+ try:
71
+ self._client.put_object(
72
+ self._bucket,
73
+ key,
74
+ io.BytesIO(data),
75
+ length=len(data),
76
+ )
77
+ except Exception:
78
+ logger.exception("S3 upload failed for key %s", key)
79
+
80
+ def fetch(self, ref_key: str) -> str:
81
+ """Download and return full content by S3 key. Synchronous."""
82
+ if self._client is None:
83
+ raise RuntimeError("PayloadOffloader is in no-op mode; cannot fetch")
84
+ response = self._client.get_object(self._bucket, ref_key)
85
+ try:
86
+ return response.read().decode()
87
+ finally:
88
+ response.close()
89
+ response.release_conn()
@@ -0,0 +1,62 @@
1
+ from __future__ import annotations
2
+ from typing import Optional
3
+ from pydantic import BaseModel
4
+
5
+
6
+ class AgentEvent(BaseModel):
7
+ """Single agent action event. The unit of observability in Cogent."""
8
+
9
+ # Correlation — always present
10
+ trace_id: str
11
+ span_id: str
12
+ parent_span_id: Optional[str] = None
13
+ start_time: float
14
+ end_time: float
15
+ duration_ms: float
16
+
17
+ # Agent context
18
+ agent_name: str
19
+ operation: (
20
+ str # llm_call|tool_call|retrieval|handoff|evaluation|human_annotation|custom
21
+ )
22
+ service_name: str
23
+ environment: str
24
+
25
+ # LLM metadata — no inline content
26
+ model: Optional[str] = None
27
+ provider: Optional[str] = None
28
+ input_tokens: Optional[int] = None
29
+ output_tokens: Optional[int] = None
30
+ cost_usd: Optional[float] = None
31
+ finish_reason: Optional[str] = None
32
+
33
+ # Payload previews (first 500 chars; set whenever content exists)
34
+ prompt_preview: Optional[str] = None
35
+ completion_preview: Optional[str] = None
36
+ tool_input_preview: Optional[str] = None
37
+ tool_output_preview: Optional[str] = None
38
+
39
+ # S3 reference keys
40
+ prompt_ref: Optional[str] = None
41
+ completion_ref: Optional[str] = None
42
+ tool_input_ref: Optional[str] = None
43
+ tool_output_ref: Optional[str] = None
44
+
45
+ # Full payload sizes (set whenever content exists)
46
+ prompt_size_bytes: Optional[int] = None
47
+ completion_size_bytes: Optional[int] = None
48
+ tool_input_size_bytes: Optional[int] = None
49
+ tool_output_size_bytes: Optional[int] = None
50
+
51
+ # Tool metadata
52
+ tool_name: Optional[str] = None
53
+ tool_error: Optional[str] = None # always inline; errors are small
54
+
55
+ # Evaluation
56
+ eval_score: Optional[float] = None
57
+ eval_label: Optional[str] = None
58
+ eval_reason: Optional[str] = None
59
+ eval_source: Optional[str] = None # realtime|batch_eval|human_annotation
60
+
61
+ # Arbitrary metadata
62
+ metadata: Optional[dict] = None
@@ -0,0 +1,153 @@
1
+ from __future__ import annotations
2
+ import logging
3
+ import time
4
+ import uuid
5
+ from contextvars import ContextVar, Token
6
+ from typing import Optional, TYPE_CHECKING
7
+
8
+ from .schema import AgentEvent
9
+
10
+ try:
11
+ from kafka import KafkaProducer
12
+ except ImportError:
13
+ KafkaProducer = None # type: ignore[assignment,misc]
14
+
15
+ if TYPE_CHECKING:
16
+ from .offload import PayloadOffloader
17
+
18
+ logger = logging.getLogger(__name__)
19
+
20
+ _CONTENT_FIELDS = ("prompt", "completion", "tool_input", "tool_output")
21
+
22
+ _current_trace_id: ContextVar[Optional[str]] = ContextVar(
23
+ "cogent_trace_id", default=None
24
+ )
25
+ _current_span_id: ContextVar[Optional[str]] = ContextVar("cogent_span_id", default=None)
26
+
27
+
28
+ class AgentTelemetry:
29
+ """
30
+ Initialise once per process. Reuse across all agents.
31
+ KafkaProducer is thread-safe and created once.
32
+ """
33
+
34
+ def __init__(
35
+ self,
36
+ bootstrap_servers: str,
37
+ topic: str = "cogent-telemetry",
38
+ offloader: Optional["PayloadOffloader"] = None,
39
+ service_name: str = "default",
40
+ environment: str = "production",
41
+ ) -> None:
42
+ self._producer = KafkaProducer(bootstrap_servers=bootstrap_servers)
43
+ self._topic = topic
44
+ self._offloader = offloader
45
+ self._service_name = service_name
46
+ self._environment = environment
47
+
48
+ def span(self, operation: str, agent_name: str, **meta) -> "_Span":
49
+ """Create a span context manager. Extra kwargs stored as event fields."""
50
+ return _Span(self, operation, agent_name, meta)
51
+
52
+
53
+ class _Span:
54
+ """Context manager for one agent action. Supports sync (with) and async (async with)."""
55
+
56
+ def __init__(
57
+ self, tel: AgentTelemetry, operation: str, agent_name: str, meta: dict
58
+ ):
59
+ self._tel = tel
60
+ self._operation = operation
61
+ self._agent_name = agent_name
62
+ self._meta = meta
63
+ self._logged = False
64
+ self._trace_token: Optional[Token] = None
65
+ self._span_token: Optional[Token] = None
66
+ self._span_id: Optional[str] = None
67
+ self._trace_id: Optional[str] = None
68
+ self._parent_span_id: Optional[str] = None
69
+ self._start_time: float = 0.0
70
+
71
+ def _enter(self) -> "_Span":
72
+ self._span_id = str(uuid.uuid4())
73
+ trace_id = _current_trace_id.get()
74
+ if trace_id is None:
75
+ trace_id = str(uuid.uuid4())
76
+ self._trace_id = trace_id
77
+ self._parent_span_id = _current_span_id.get()
78
+ self._start_time = time.time()
79
+ self._trace_token = _current_trace_id.set(self._trace_id)
80
+ self._span_token = _current_span_id.set(self._span_id)
81
+ return self
82
+
83
+ def _exit(self, exc_val: Optional[BaseException]) -> None:
84
+ _current_trace_id.reset(self._trace_token)
85
+ _current_span_id.reset(self._span_token)
86
+ if not self._logged:
87
+ fields: dict = {}
88
+ if exc_val is not None:
89
+ fields["tool_error"] = str(exc_val)
90
+ self.log(**fields)
91
+
92
+ def __enter__(self) -> "_Span":
93
+ return self._enter()
94
+
95
+ def __exit__(self, exc_type, exc_val, exc_tb):
96
+ self._exit(exc_val)
97
+ return False
98
+
99
+ async def __aenter__(self) -> "_Span":
100
+ return self._enter()
101
+
102
+ async def __aexit__(self, exc_type, exc_val, exc_tb):
103
+ self._exit(exc_val)
104
+ return False
105
+
106
+ def log(self, **fields) -> None:
107
+ """Build, validate, and emit the event. Idempotent — second call is a no-op."""
108
+ if self._logged:
109
+ return
110
+ self._logged = True
111
+
112
+ end_time = time.time()
113
+ extra: dict = {}
114
+
115
+ for field in _CONTENT_FIELDS:
116
+ content = fields.pop(field, None)
117
+ if content is None:
118
+ continue
119
+ if self._tel._offloader is not None:
120
+ preview, ref, size = self._tel._offloader.prepare(
121
+ field, content, self._trace_id, self._span_id
122
+ )
123
+ else:
124
+ preview = content[:500]
125
+ ref = None
126
+ size = len(content.encode())
127
+ extra[f"{field}_preview"] = preview
128
+ if ref is not None:
129
+ extra[f"{field}_ref"] = ref
130
+ extra[f"{field}_size_bytes"] = size
131
+
132
+ combined = {**self._meta, **fields, **extra}
133
+
134
+ event = AgentEvent(
135
+ trace_id=self._trace_id,
136
+ span_id=self._span_id,
137
+ parent_span_id=self._parent_span_id,
138
+ start_time=self._start_time,
139
+ end_time=end_time,
140
+ duration_ms=(end_time - self._start_time) * 1000,
141
+ agent_name=self._agent_name,
142
+ operation=self._operation,
143
+ service_name=self._tel._service_name,
144
+ environment=self._tel._environment,
145
+ **combined,
146
+ )
147
+
148
+ payload = event.model_dump_json(exclude_none=True).encode()
149
+ try:
150
+ self._tel._producer.send(self._tel._topic, payload)
151
+ self._tel._producer.flush(timeout=10)
152
+ except Exception:
153
+ logger.exception("Failed to emit span %s to Kafka", self._span_id)
@@ -0,0 +1,14 @@
1
+ Metadata-Version: 2.4
2
+ Name: cogent-sdk
3
+ Version: 0.1.2
4
+ Summary: Stream-first observability for distributed LLM agents
5
+ Requires-Python: >=3.11
6
+ License-File: LICENSE
7
+ Provides-Extra: sdk
8
+ Requires-Dist: kafka-python>=2.0; extra == "sdk"
9
+ Requires-Dist: pydantic>=2.0; extra == "sdk"
10
+ Requires-Dist: minio>=7.0; extra == "sdk"
11
+ Provides-Extra: dev
12
+ Requires-Dist: pytest>=7.0; extra == "dev"
13
+ Requires-Dist: pytest-asyncio>=0.23; extra == "dev"
14
+ Dynamic: license-file
@@ -0,0 +1,14 @@
1
+ LICENSE
2
+ README.md
3
+ pyproject.toml
4
+ cogent/__init__.py
5
+ cogent/sdk/__init__.py
6
+ cogent/sdk/decorators.py
7
+ cogent/sdk/offload.py
8
+ cogent/sdk/schema.py
9
+ cogent/sdk/telemetry.py
10
+ cogent_sdk.egg-info/PKG-INFO
11
+ cogent_sdk.egg-info/SOURCES.txt
12
+ cogent_sdk.egg-info/dependency_links.txt
13
+ cogent_sdk.egg-info/requires.txt
14
+ cogent_sdk.egg-info/top_level.txt
@@ -0,0 +1,9 @@
1
+
2
+ [dev]
3
+ pytest>=7.0
4
+ pytest-asyncio>=0.23
5
+
6
+ [sdk]
7
+ kafka-python>=2.0
8
+ pydantic>=2.0
9
+ minio>=7.0
@@ -0,0 +1 @@
1
+ cogent
@@ -0,0 +1,24 @@
1
+ [project]
2
+ name = "cogent-sdk"
3
+ version = "0.1.2"
4
+ description = "Stream-first observability for distributed LLM agents"
5
+ requires-python = ">=3.11"
6
+
7
+ [project.optional-dependencies]
8
+ sdk = [
9
+ "kafka-python>=2.0",
10
+ "pydantic>=2.0",
11
+ "minio>=7.0",
12
+ ]
13
+ dev = [
14
+ "pytest>=7.0",
15
+ "pytest-asyncio>=0.23",
16
+ ]
17
+
18
+ [tool.setuptools.packages.find]
19
+ where = ["."]
20
+ include = ["cogent*"]
21
+
22
+ [tool.pytest.ini_options]
23
+ asyncio_mode = "auto"
24
+ testpaths = ["tests/python"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+