circleflake 0.1.3__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.
Files changed (34) hide show
  1. circleflake-0.1.3/.gitignore +8 -0
  2. circleflake-0.1.3/LICENSE +15 -0
  3. circleflake-0.1.3/PKG-INFO +114 -0
  4. circleflake-0.1.3/README.md +78 -0
  5. circleflake-0.1.3/examples/deep_agent.py +12 -0
  6. circleflake-0.1.3/examples/langchain_agent.py +70 -0
  7. circleflake-0.1.3/examples/langgraph_agent.py +11 -0
  8. circleflake-0.1.3/pyproject.toml +26 -0
  9. circleflake-0.1.3/src/circleflake/__init__.py +5 -0
  10. circleflake-0.1.3/src/circleflake/client.py +36 -0
  11. circleflake-0.1.3/src/circleflake/config.py +11 -0
  12. circleflake-0.1.3/src/circleflake/core/__init__.py +0 -0
  13. circleflake-0.1.3/src/circleflake/core/context.py +25 -0
  14. circleflake-0.1.3/src/circleflake/core/processor.py +8 -0
  15. circleflake-0.1.3/src/circleflake/core/provider.py +9 -0
  16. circleflake-0.1.3/src/circleflake/core/tracer.py +71 -0
  17. circleflake-0.1.3/src/circleflake/exporters/__init__.py +0 -0
  18. circleflake-0.1.3/src/circleflake/exporters/exporter.py +34 -0
  19. circleflake-0.1.3/src/circleflake/exporters/serializer.py +10 -0
  20. circleflake-0.1.3/src/circleflake/integrations/__init__.py +0 -0
  21. circleflake-0.1.3/src/circleflake/integrations/_callback_base.py +8 -0
  22. circleflake-0.1.3/src/circleflake/integrations/deepagents/__init__.py +3 -0
  23. circleflake-0.1.3/src/circleflake/integrations/deepagents/handler.py +16 -0
  24. circleflake-0.1.3/src/circleflake/integrations/deepagents/mapper.py +7 -0
  25. circleflake-0.1.3/src/circleflake/integrations/langchain/__init__.py +3 -0
  26. circleflake-0.1.3/src/circleflake/integrations/langchain/handler.py +108 -0
  27. circleflake-0.1.3/src/circleflake/integrations/langchain/mapper.py +18 -0
  28. circleflake-0.1.3/src/circleflake/integrations/langgraph/__init__.py +3 -0
  29. circleflake-0.1.3/src/circleflake/integrations/langgraph/handler.py +20 -0
  30. circleflake-0.1.3/src/circleflake/integrations/langgraph/mapper.py +9 -0
  31. circleflake-0.1.3/src/circleflake/schemas/__init__.py +0 -0
  32. circleflake-0.1.3/src/circleflake/schemas/spans.py +50 -0
  33. circleflake-0.1.3/tests/test_callbacks.py +31 -0
  34. circleflake-0.1.3/tests/test_core.py +33 -0
@@ -0,0 +1,8 @@
1
+ __pycache__/
2
+ *.py[cod]
3
+ .venv/
4
+ dist/
5
+ build/
6
+ *.egg-info/
7
+ .pytest_cache/
8
+ .env
@@ -0,0 +1,15 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Circle Flake
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND.
@@ -0,0 +1,114 @@
1
+ Metadata-Version: 2.5
2
+ Name: circleflake
3
+ Version: 0.1.3
4
+ Summary: Agent execution tracing SDK for Circle Flake
5
+ Author: Circle Flake
6
+ License: MIT License
7
+
8
+ Copyright (c) 2026 Circle Flake
9
+
10
+ Permission is hereby granted, free of charge, to any person obtaining a copy
11
+ of this software and associated documentation files (the "Software"), to deal
12
+ in the Software without restriction, including without limitation the rights
13
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
14
+ copies of the Software, and to permit persons to whom the Software is
15
+ furnished to do so, subject to the following conditions:
16
+
17
+ The above copyright notice and this permission notice shall be included in all
18
+ copies or substantial portions of the Software.
19
+
20
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND.
21
+ License-File: LICENSE
22
+ Requires-Python: >=3.10
23
+ Provides-Extra: deepagents
24
+ Requires-Dist: deepagents; extra == 'deepagents'
25
+ Requires-Dist: langchain-core>=0.3; extra == 'deepagents'
26
+ Requires-Dist: langgraph; extra == 'deepagents'
27
+ Provides-Extra: dev
28
+ Requires-Dist: build>=1.2; extra == 'dev'
29
+ Requires-Dist: pytest>=8; extra == 'dev'
30
+ Provides-Extra: langchain
31
+ Requires-Dist: langchain>=1.0; extra == 'langchain'
32
+ Provides-Extra: langgraph
33
+ Requires-Dist: langchain-core>=0.3; extra == 'langgraph'
34
+ Requires-Dist: langgraph>=0.2; extra == 'langgraph'
35
+ Description-Content-Type: text/markdown
36
+
37
+ # Circle Flake Python SDK
38
+
39
+ Capture agent execution from LangChain, LangGraph, and Deep Agents using one
40
+ framework-independent trace/span model.
41
+
42
+ ## Install
43
+
44
+ ```bash
45
+ pip install -e ".[langchain,dev]"
46
+ ```
47
+
48
+ Install `.[langgraph]` or `.[deepagents]` when using those frameworks.
49
+
50
+ ## LangChain
51
+
52
+ Run the included deterministic sample (no provider API key required):
53
+
54
+ ```bash
55
+ python examples/langchain_agent.py
56
+ ```
57
+
58
+
59
+ ```python
60
+ from circleflake import CircleFlake
61
+
62
+ cf = CircleFlake(agent_name="gtm-agent")
63
+
64
+ # Pass the handler to a chain/model invoke call.
65
+ result = chain.invoke(
66
+ {"input": "Qualify Acme"},
67
+ config={"callbacks": [cf.langchain_handler]},
68
+ )
69
+
70
+ # Export captured traces as JSON.
71
+ print(cf.exporter.exported)
72
+
73
+ # Optional: POST completed traces to your Circle Flake ingestion endpoint.
74
+ # cf = CircleFlake(agent_name="gtm-agent",
75
+ # endpoint="https://api.example.com/v1/traces",
76
+ # api_key="...")
77
+ cf.flush()
78
+ ```
79
+
80
+ ## LangGraph
81
+
82
+ LangGraph accepts LangChain callback handlers through RunnableConfig:
83
+
84
+ ```python
85
+ result = graph.invoke(
86
+ {"messages": [...]},
87
+ config={"callbacks": [cf.langgraph_handler]},
88
+ )
89
+ ```
90
+
91
+ The LangGraph adapter uses the callback lifecycle and records graph/node metadata
92
+ when supplied by the runtime.
93
+
94
+ ## Deep Agents
95
+
96
+ Deep Agents are built on the LangGraph/LangChain runtime. Start by passing the
97
+ Deep Agents adapter in the same callbacks config:
98
+
99
+ ```python
100
+ result = agent.invoke(
101
+ {"messages": [...]},
102
+ config={"callbacks": [cf.deepagents_handler]},
103
+ )
104
+ ```
105
+
106
+ This captures framework callback activity. Deep-Agent-specific planning and
107
+ delegation semantics are not yet normalized into dedicated span types; those
108
+ will be added against the exact Deep Agents version used by your application.
109
+
110
+ ## Data handling
111
+
112
+ Inputs and outputs are not captured by default. Set `capture_content=True` only
113
+ if you have reviewed the privacy implications for your prompts, tool arguments,
114
+ and outputs.
@@ -0,0 +1,78 @@
1
+ # Circle Flake Python SDK
2
+
3
+ Capture agent execution from LangChain, LangGraph, and Deep Agents using one
4
+ framework-independent trace/span model.
5
+
6
+ ## Install
7
+
8
+ ```bash
9
+ pip install -e ".[langchain,dev]"
10
+ ```
11
+
12
+ Install `.[langgraph]` or `.[deepagents]` when using those frameworks.
13
+
14
+ ## LangChain
15
+
16
+ Run the included deterministic sample (no provider API key required):
17
+
18
+ ```bash
19
+ python examples/langchain_agent.py
20
+ ```
21
+
22
+
23
+ ```python
24
+ from circleflake import CircleFlake
25
+
26
+ cf = CircleFlake(agent_name="gtm-agent")
27
+
28
+ # Pass the handler to a chain/model invoke call.
29
+ result = chain.invoke(
30
+ {"input": "Qualify Acme"},
31
+ config={"callbacks": [cf.langchain_handler]},
32
+ )
33
+
34
+ # Export captured traces as JSON.
35
+ print(cf.exporter.exported)
36
+
37
+ # Optional: POST completed traces to your Circle Flake ingestion endpoint.
38
+ # cf = CircleFlake(agent_name="gtm-agent",
39
+ # endpoint="https://api.example.com/v1/traces",
40
+ # api_key="...")
41
+ cf.flush()
42
+ ```
43
+
44
+ ## LangGraph
45
+
46
+ LangGraph accepts LangChain callback handlers through RunnableConfig:
47
+
48
+ ```python
49
+ result = graph.invoke(
50
+ {"messages": [...]},
51
+ config={"callbacks": [cf.langgraph_handler]},
52
+ )
53
+ ```
54
+
55
+ The LangGraph adapter uses the callback lifecycle and records graph/node metadata
56
+ when supplied by the runtime.
57
+
58
+ ## Deep Agents
59
+
60
+ Deep Agents are built on the LangGraph/LangChain runtime. Start by passing the
61
+ Deep Agents adapter in the same callbacks config:
62
+
63
+ ```python
64
+ result = agent.invoke(
65
+ {"messages": [...]},
66
+ config={"callbacks": [cf.deepagents_handler]},
67
+ )
68
+ ```
69
+
70
+ This captures framework callback activity. Deep-Agent-specific planning and
71
+ delegation semantics are not yet normalized into dedicated span types; those
72
+ will be added against the exact Deep Agents version used by your application.
73
+
74
+ ## Data handling
75
+
76
+ Inputs and outputs are not captured by default. Set `capture_content=True` only
77
+ if you have reviewed the privacy implications for your prompts, tool arguments,
78
+ and outputs.
@@ -0,0 +1,12 @@
1
+ from circleflake import CircleFlake
2
+
3
+ cf = CircleFlake(agent_name="gtm-deep-agent")
4
+
5
+ # Deep Agents run on LangGraph/LangChain callback infrastructure.
6
+ # Pass this handler using the agent's supported RunnableConfig/callbacks path:
7
+ #
8
+ # result = agent.invoke(
9
+ # {"messages": [...]},
10
+ # config={"callbacks": [cf.deepagents_handler]},
11
+ # )
12
+ # cf.flush()
@@ -0,0 +1,70 @@
1
+ """A no-API-key LangChain sample for validating Circle Flake instrumentation.
2
+
3
+ Run from the repository root:
4
+ python examples/langchain_agent.py
5
+
6
+ This uses LangChain's FakeListChatModel so you can test callback capture before
7
+ connecting a paid model provider.
8
+ """
9
+
10
+ import json
11
+
12
+ from langchain_core.language_models.fake_chat_models import FakeListChatModel
13
+ from langchain_core.prompts import ChatPromptTemplate
14
+ from langchain_core.output_parsers import StrOutputParser
15
+
16
+ from circleflake import CircleFlake
17
+
18
+
19
+ def main() -> None:
20
+ circleflake = CircleFlake(
21
+ agent_name="gtm-lead-qualifier",
22
+ environment="local",
23
+ )
24
+
25
+ prompt = ChatPromptTemplate.from_messages([
26
+ ("system", "You are a concise B2B GTM lead qualification assistant."),
27
+ ("human", "Qualify this company and explain briefly: {company}"),
28
+ ])
29
+
30
+ # Deterministic response: no OpenAI key or external API call is needed.
31
+ model = FakeListChatModel(
32
+ responses=[
33
+ "Qualified: Acme is a strong potential customer because it sells "
34
+ "B2B software and appears to have a relevant sales use case."
35
+ ]
36
+ )
37
+
38
+ chain = prompt | model | StrOutputParser()
39
+
40
+ result = chain.invoke(
41
+ {"company": "Acme, a B2B SaaS company with a 20-person sales team"},
42
+ config={
43
+ "callbacks": [circleflake.langchain_handler],
44
+ "tags": ["circleflake-demo", "gtm"],
45
+ "metadata": {"workflow": "lead_qualification"},
46
+ },
47
+ )
48
+
49
+ print("\nMODEL RESULT")
50
+ print(result)
51
+
52
+ # Export locally. With no endpoint configured, this records the payload
53
+ # in circleflake.exporter.exported rather than making an HTTP request.
54
+ circleflake.flush()
55
+
56
+ print("\nCAPTURED TRACE PAYLOAD")
57
+ print(json.dumps(circleflake.exporter.exported, indent=2, default=str))
58
+
59
+ if not circleflake.exporter.exported:
60
+ raise RuntimeError("Circle Flake did not capture any traces")
61
+
62
+ spans = circleflake.exporter.exported[0]["spans"]
63
+ if not any(span["framework"] == "langchain" for span in spans):
64
+ raise RuntimeError("No LangChain spans were captured")
65
+
66
+ print(f"\nCaptured {len(spans)} spans successfully.")
67
+
68
+
69
+ if __name__ == "__main__":
70
+ main()
@@ -0,0 +1,11 @@
1
+ from circleflake import CircleFlake
2
+
3
+ cf = CircleFlake(agent_name="gtm-graph-agent")
4
+
5
+ # Pass the handler through LangGraph RunnableConfig:
6
+ #
7
+ # result = graph.invoke(
8
+ # {"messages": [...]},
9
+ # config={"callbacks": [cf.langgraph_handler]},
10
+ # )
11
+ # cf.flush()
@@ -0,0 +1,26 @@
1
+ [build-system]
2
+ requires = ["hatchling>=1.26"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "circleflake"
7
+ version = "0.1.3"
8
+ description = "Agent execution tracing SDK for Circle Flake"
9
+ readme = "README.md"
10
+ requires-python = ">=3.10"
11
+ license = { file = "LICENSE" }
12
+ authors = [{ name = "Circle Flake" }]
13
+ dependencies = []
14
+
15
+ [project.optional-dependencies]
16
+ langchain = ["langchain>=1.0"]
17
+ langgraph = ["langgraph>=0.2", "langchain-core>=0.3"]
18
+ deepagents = ["deepagents", "langgraph", "langchain-core>=0.3"]
19
+ dev = ["pytest>=8", "build>=1.2"]
20
+
21
+ [tool.hatch.build.targets.wheel]
22
+ packages = ["src/circleflake"]
23
+
24
+ [tool.pytest.ini_options]
25
+ pythonpath = ["src"]
26
+ testpaths = ["tests"]
@@ -0,0 +1,5 @@
1
+ from .client import CircleFlake
2
+ from .schemas.spans import Span, Trace
3
+
4
+ __all__ = ["CircleFlake", "Span", "Trace"]
5
+ __version__ = "0.1.0"
@@ -0,0 +1,36 @@
1
+ from __future__ import annotations
2
+
3
+ from .config import CircleFlakeConfig
4
+ from .core.provider import TracingProvider
5
+ from .exporters.exporter import CircleFlakeExporter
6
+ from .integrations.langchain.handler import CircleFlakeLangChainHandler
7
+ from .integrations.langgraph.handler import CircleFlakeLangGraphHandler
8
+ from .integrations.deepagents.handler import CircleFlakeDeepAgentsHandler
9
+
10
+
11
+ class CircleFlake:
12
+ def __init__(self, agent_name: str, *, endpoint: str | None = None,
13
+ api_key: str | None = None, environment: str = "development",
14
+ capture_content: bool = False, timeout_seconds: float = 10.0):
15
+ self.config = CircleFlakeConfig(
16
+ agent_name=agent_name, endpoint=endpoint, api_key=api_key,
17
+ environment=environment, capture_content=capture_content,
18
+ timeout_seconds=timeout_seconds,
19
+ )
20
+ self.provider = TracingProvider(agent_name, environment)
21
+ self.tracer = self.provider.get_tracer()
22
+ self.exporter = CircleFlakeExporter(endpoint, api_key, timeout_seconds)
23
+ self.langchain_handler = CircleFlakeLangChainHandler(
24
+ self.tracer, capture_content=capture_content
25
+ )
26
+ self.langgraph_handler = CircleFlakeLangGraphHandler(
27
+ self.tracer, capture_content=capture_content
28
+ )
29
+ self.deepagents_handler = CircleFlakeDeepAgentsHandler(
30
+ self.tracer, capture_content=capture_content
31
+ )
32
+
33
+ def flush(self) -> None:
34
+ traces = self.tracer.get_traces()
35
+ self.exporter.export(traces)
36
+ self.tracer.traces.clear()
@@ -0,0 +1,11 @@
1
+ from dataclasses import dataclass
2
+
3
+
4
+ @dataclass(slots=True)
5
+ class CircleFlakeConfig:
6
+ agent_name: str
7
+ endpoint: str | None = None
8
+ api_key: str | None = None
9
+ environment: str = "development"
10
+ capture_content: bool = False
11
+ timeout_seconds: float = 10.0
File without changes
@@ -0,0 +1,25 @@
1
+ from contextvars import ContextVar
2
+ from dataclasses import dataclass
3
+
4
+
5
+ @dataclass(frozen=True)
6
+ class SpanContext:
7
+ trace_id: str
8
+ span_id: str
9
+
10
+
11
+ _current_span: ContextVar[SpanContext | None] = ContextVar(
12
+ "circleflake_current_span", default=None
13
+ )
14
+
15
+
16
+ def current_span() -> SpanContext | None:
17
+ return _current_span.get()
18
+
19
+
20
+ def set_current_span(value: SpanContext | None):
21
+ return _current_span.set(value)
22
+
23
+
24
+ def reset_current_span(token) -> None:
25
+ _current_span.reset(token)
@@ -0,0 +1,8 @@
1
+ from ..schemas.spans import Span
2
+
3
+
4
+ class SpanProcessor:
5
+ """Extension point for completed spans."""
6
+
7
+ def on_end(self, span: Span) -> None:
8
+ pass
@@ -0,0 +1,9 @@
1
+ from .tracer import Tracer
2
+
3
+
4
+ class TracingProvider:
5
+ def __init__(self, agent_name: str, environment: str = "development"):
6
+ self.tracer = Tracer(agent_name, environment)
7
+
8
+ def get_tracer(self) -> Tracer:
9
+ return self.tracer
@@ -0,0 +1,71 @@
1
+ from __future__ import annotations
2
+
3
+ from contextlib import contextmanager
4
+ from typing import Any
5
+ import uuid
6
+
7
+ from .context import SpanContext, current_span, reset_current_span, set_current_span
8
+ from ..schemas.spans import Span, Trace
9
+
10
+
11
+ class Tracer:
12
+ def __init__(self, agent_name: str, environment: str = "development"):
13
+ self.agent_name = agent_name
14
+ self.environment = environment
15
+ self.traces: dict[str, Trace] = {}
16
+
17
+ def start_span(
18
+ self,
19
+ name: str,
20
+ *,
21
+ trace_id: str | None = None,
22
+ parent_span_id: str | None = None,
23
+ framework: str = "custom",
24
+ kind: str = "internal",
25
+ attributes: dict[str, Any] | None = None,
26
+ ) -> Span:
27
+ parent = current_span()
28
+ trace_id = trace_id or (parent.trace_id if parent else uuid.uuid4().hex)
29
+ if parent_span_id is None and parent and parent.trace_id == trace_id:
30
+ parent_span_id = parent.span_id
31
+
32
+ trace = self.traces.get(trace_id)
33
+ if trace is None:
34
+ trace = Trace(trace_id, self.agent_name, self.environment)
35
+ self.traces[trace_id] = trace
36
+
37
+ span = Span(
38
+ name=name,
39
+ trace_id=trace_id,
40
+ parent_span_id=parent_span_id,
41
+ framework=framework,
42
+ kind=kind,
43
+ attributes=attributes or {},
44
+ )
45
+ trace.spans.append(span)
46
+ return span
47
+
48
+ @contextmanager
49
+ def span(self, name: str, **kwargs):
50
+ span = self.start_span(name, **kwargs)
51
+ token = set_current_span(SpanContext(span.trace_id, span.span_id))
52
+ try:
53
+ yield span
54
+ except BaseException as exc:
55
+ span.attributes["error.type"] = type(exc).__name__
56
+ span.attributes["error.message"] = str(exc)
57
+ span.finish("error")
58
+ raise
59
+ else:
60
+ span.finish("ok")
61
+ finally:
62
+ reset_current_span(token)
63
+
64
+ def complete_span(self, span: Span, *, status: str = "ok",
65
+ attributes: dict[str, Any] | None = None) -> None:
66
+ if attributes:
67
+ span.attributes.update(attributes)
68
+ span.finish(status)
69
+
70
+ def get_traces(self) -> list[Trace]:
71
+ return list(self.traces.values())
@@ -0,0 +1,34 @@
1
+ from __future__ import annotations
2
+
3
+ from urllib.request import Request, urlopen
4
+
5
+ from .serializer import serialize_traces
6
+ from ..schemas.spans import Trace
7
+
8
+
9
+ class CircleFlakeExporter:
10
+ def __init__(self, endpoint: str | None = None, api_key: str | None = None,
11
+ timeout_seconds: float = 10.0):
12
+ self.endpoint = endpoint
13
+ self.api_key = api_key
14
+ self.timeout_seconds = timeout_seconds
15
+ self.exported: list[dict] = []
16
+
17
+ def export(self, traces: list[Trace]) -> None:
18
+ if not traces:
19
+ return
20
+ # Keep a local copy for tests and local development.
21
+ self.exported.extend(trace.to_dict() for trace in traces)
22
+ if not self.endpoint:
23
+ return
24
+
25
+ headers = {"Content-Type": "application/json"}
26
+ if self.api_key:
27
+ headers["Authorization"] = f"Bearer {self.api_key}"
28
+ request = Request(
29
+ self.endpoint, data=serialize_traces(traces),
30
+ headers=headers, method="POST"
31
+ )
32
+ with urlopen(request, timeout=self.timeout_seconds) as response:
33
+ if not 200 <= response.status < 300:
34
+ raise RuntimeError(f"Circle Flake ingestion failed: HTTP {response.status}")
@@ -0,0 +1,10 @@
1
+ import json
2
+ from ..schemas.spans import Trace
3
+
4
+
5
+ def serialize_traces(traces: list[Trace]) -> bytes:
6
+ return json.dumps(
7
+ {"traces": [trace.to_dict() for trace in traces]},
8
+ default=str,
9
+ separators=(",", ":"),
10
+ ).encode("utf-8")
@@ -0,0 +1,8 @@
1
+ """Optional LangChain callback base with a no-dependency fallback."""
2
+
3
+ try:
4
+ from langchain_core.callbacks import BaseCallbackHandler
5
+ except ImportError:
6
+ class BaseCallbackHandler: # type: ignore[no-redef]
7
+ """Fallback so importing circleflake does not require LangChain."""
8
+ pass
@@ -0,0 +1,3 @@
1
+ from .handler import CircleFlakeDeepAgentsHandler
2
+
3
+ __all__ = ["CircleFlakeDeepAgentsHandler"]
@@ -0,0 +1,16 @@
1
+ from ..langgraph.handler import CircleFlakeLangGraphHandler
2
+
3
+
4
+ class CircleFlakeDeepAgentsHandler(CircleFlakeLangGraphHandler):
5
+ """Initial Deep Agents adapter.
6
+
7
+ Deep Agents currently execute on the LangGraph/LangChain callback stack,
8
+ so this captures those runs. Dedicated planning/subagent/tool semantics
9
+ will be added once the target Deep Agents version and hook contracts are
10
+ pinned and covered by integration tests.
11
+ """
12
+
13
+ def _start(self, run_id, parent_run_id, name, kind, attributes=None):
14
+ attrs = dict(attributes or {})
15
+ attrs["framework"] = "deepagents"
16
+ return super()._start(run_id, parent_run_id, name, kind, attrs)
@@ -0,0 +1,7 @@
1
+ def deep_agent_attributes(metadata=None, tags=None):
2
+ metadata = metadata or {}
3
+ attrs = {"tags": tags or []}
4
+ for key, value in metadata.items():
5
+ if key.startswith(("langgraph_", "deepagents_")):
6
+ attrs[f"deepagents.{key}"] = value
7
+ return attrs
@@ -0,0 +1,3 @@
1
+ from .handler import CircleFlakeLangChainHandler
2
+
3
+ __all__ = ["CircleFlakeLangChainHandler"]
@@ -0,0 +1,108 @@
1
+ from __future__ import annotations
2
+
3
+ from typing import Any
4
+ from uuid import UUID
5
+
6
+ from .._callback_base import BaseCallbackHandler
7
+ from .mapper import run_name, safe_attributes
8
+
9
+
10
+ class CircleFlakeLangChainHandler(BaseCallbackHandler):
11
+ """Maps LangChain callback lifecycle events into Circle Flake spans."""
12
+
13
+ def __init__(self, tracer, *, capture_content: bool = False):
14
+ self.tracer = tracer
15
+ self.capture_content = capture_content
16
+ self._runs: dict[str, Any] = {}
17
+
18
+ def _start(self, run_id, parent_run_id, name, kind, attributes=None):
19
+ run_key = str(run_id)
20
+ parent = self._runs.get(str(parent_run_id)) if parent_run_id else None
21
+ span = self.tracer.start_span(
22
+ name, trace_id=parent.trace_id if parent else None,
23
+ parent_span_id=parent.span_id if parent else None,
24
+ framework="langchain", kind=kind, attributes=attributes or {},
25
+ )
26
+ self._runs[run_key] = span
27
+ return span
28
+
29
+ def _end(self, run_id, *, status="ok", attributes=None):
30
+ span = self._runs.pop(str(run_id), None)
31
+ if span:
32
+ self.tracer.complete_span(span, status=status, attributes=attributes)
33
+
34
+ def on_chain_start(self, serialized, inputs, *, run_id, parent_run_id=None,
35
+ tags=None, metadata=None, **kwargs):
36
+ attrs = {"tags": tags or [], "metadata": metadata or {}}
37
+ if self.capture_content:
38
+ attrs.update(safe_attributes(inputs, True))
39
+ self._start(run_id, parent_run_id, run_name(serialized, "chain"),
40
+ "chain", attrs)
41
+
42
+ def on_chain_end(self, outputs, *, run_id, **kwargs):
43
+ self._end(run_id, attributes=safe_attributes(outputs, self.capture_content))
44
+
45
+ def on_chain_error(self, error, *, run_id, **kwargs):
46
+ self._end(run_id, status="error", attributes={
47
+ "error.type": type(error).__name__, "error.message": str(error)
48
+ })
49
+
50
+ def on_llm_start(self, serialized, prompts, *, run_id, parent_run_id=None,
51
+ tags=None, metadata=None, **kwargs):
52
+ attrs = {"tags": tags or [], "metadata": metadata or {}}
53
+ if self.capture_content:
54
+ attrs["prompts"] = prompts
55
+ self._start(run_id, parent_run_id, run_name(serialized, "llm"),
56
+ "llm", attrs)
57
+
58
+ def on_chat_model_start(self, serialized, messages, *, run_id,
59
+ parent_run_id=None, tags=None, metadata=None, **kwargs):
60
+ attrs = {"tags": tags or [], "metadata": metadata or {}}
61
+ if self.capture_content:
62
+ attrs["messages"] = str(messages)[:8000]
63
+ self._start(run_id, parent_run_id, run_name(serialized, "chat_model"),
64
+ "llm", attrs)
65
+
66
+ def on_llm_end(self, response, *, run_id, **kwargs):
67
+ attrs = {}
68
+ usage = getattr(response, "llm_output", None) or {}
69
+ if isinstance(usage, dict):
70
+ attrs["llm.usage"] = usage.get("token_usage", usage.get("usage", {}))
71
+ self._end(run_id, attributes=attrs)
72
+
73
+ def on_llm_error(self, error, *, run_id, **kwargs):
74
+ self._end(run_id, status="error", attributes={
75
+ "error.type": type(error).__name__, "error.message": str(error)
76
+ })
77
+
78
+ def on_tool_start(self, serialized, input_str, *, run_id, parent_run_id=None,
79
+ tags=None, metadata=None, inputs=None, **kwargs):
80
+ attrs = {"tags": tags or [], "metadata": metadata or {}}
81
+ if self.capture_content:
82
+ attrs["input"] = input_str
83
+ self._start(run_id, parent_run_id, run_name(serialized, "tool"),
84
+ "tool", attrs)
85
+
86
+ def on_tool_end(self, output, *, run_id, **kwargs):
87
+ self._end(run_id, attributes=safe_attributes(output, self.capture_content))
88
+
89
+ def on_tool_error(self, error, *, run_id, **kwargs):
90
+ self._end(run_id, status="error", attributes={
91
+ "error.type": type(error).__name__, "error.message": str(error)
92
+ })
93
+
94
+ def on_retriever_start(self, serialized, query, *, run_id, parent_run_id=None,
95
+ tags=None, metadata=None, **kwargs):
96
+ attrs = {"tags": tags or [], "metadata": metadata or {}}
97
+ if self.capture_content:
98
+ attrs["query"] = query
99
+ self._start(run_id, parent_run_id, run_name(serialized, "retriever"),
100
+ "retriever", attrs)
101
+
102
+ def on_retriever_end(self, documents, *, run_id, **kwargs):
103
+ self._end(run_id, attributes={"retriever.document_count": len(documents)})
104
+
105
+ def on_retriever_error(self, error, *, run_id, **kwargs):
106
+ self._end(run_id, status="error", attributes={
107
+ "error.type": type(error).__name__, "error.message": str(error)
108
+ })
@@ -0,0 +1,18 @@
1
+ from typing import Any
2
+
3
+
4
+ def safe_attributes(value: Any, capture_content: bool) -> dict[str, Any]:
5
+ if not capture_content:
6
+ return {}
7
+ if isinstance(value, (str, int, float, bool)) or value is None:
8
+ return {"content": value}
9
+ return {"content": str(value)[:4000]}
10
+
11
+
12
+ def run_name(serialized: dict | None, fallback: str) -> str:
13
+ serialized = serialized or {}
14
+ name = serialized.get("name")
15
+ if name:
16
+ return name
17
+ identifier = serialized.get("id") or []
18
+ return identifier[-1] if identifier else fallback
@@ -0,0 +1,3 @@
1
+ from .handler import CircleFlakeLangGraphHandler
2
+
3
+ __all__ = ["CircleFlakeLangGraphHandler"]
@@ -0,0 +1,20 @@
1
+ from ..langchain.handler import CircleFlakeLangChainHandler
2
+ from .mapper import graph_attributes
3
+
4
+
5
+ class CircleFlakeLangGraphHandler(CircleFlakeLangChainHandler):
6
+ """LangGraph adapter; graph runs and node callbacks share the core span model."""
7
+
8
+ def _start(self, run_id, parent_run_id, name, kind, attributes=None):
9
+ attrs = dict(attributes or {})
10
+ attrs["framework"] = "langgraph"
11
+ return super()._start(run_id, parent_run_id, name, kind, attrs)
12
+
13
+ def on_chain_start(self, serialized, inputs, *, run_id, parent_run_id=None,
14
+ tags=None, metadata=None, **kwargs):
15
+ attrs = graph_attributes(metadata, tags)
16
+ if self.capture_content:
17
+ attrs["input"] = str(inputs)[:4000]
18
+ self._start(run_id, parent_run_id,
19
+ serialized.get("name", "graph_or_node"),
20
+ "graph", attrs)
@@ -0,0 +1,9 @@
1
+ def graph_attributes(metadata=None, tags=None):
2
+ metadata = metadata or {}
3
+ attrs = {"tags": tags or []}
4
+ # LangGraph commonly annotates callback metadata with node and graph context.
5
+ for key in ("langgraph_node", "langgraph_step", "langgraph_path",
6
+ "checkpoint_id", "thread_id"):
7
+ if key in metadata:
8
+ attrs[f"langgraph.{key}"] = metadata[key]
9
+ return attrs
File without changes
@@ -0,0 +1,50 @@
1
+ from __future__ import annotations
2
+
3
+ from dataclasses import asdict, dataclass, field
4
+ from datetime import datetime, timezone
5
+ from typing import Any
6
+ import uuid
7
+
8
+
9
+ def utc_now() -> str:
10
+ return datetime.now(timezone.utc).isoformat()
11
+
12
+
13
+ @dataclass
14
+ class Span:
15
+ name: str
16
+ trace_id: str
17
+ span_id: str = field(default_factory=lambda: uuid.uuid4().hex[:16])
18
+ parent_span_id: str | None = None
19
+ framework: str = "custom"
20
+ kind: str = "internal"
21
+ started_at: str = field(default_factory=utc_now)
22
+ ended_at: str | None = None
23
+ status: str = "running"
24
+ attributes: dict[str, Any] = field(default_factory=dict)
25
+ events: list[dict[str, Any]] = field(default_factory=list)
26
+
27
+ def finish(self, status: str = "ok") -> None:
28
+ self.ended_at = utc_now()
29
+ self.status = status
30
+
31
+ def to_dict(self) -> dict[str, Any]:
32
+ return asdict(self)
33
+
34
+
35
+ @dataclass
36
+ class Trace:
37
+ trace_id: str
38
+ agent_name: str
39
+ environment: str
40
+ spans: list[Span] = field(default_factory=list)
41
+ started_at: str = field(default_factory=utc_now)
42
+
43
+ def to_dict(self) -> dict[str, Any]:
44
+ return {
45
+ "trace_id": self.trace_id,
46
+ "agent_name": self.agent_name,
47
+ "environment": self.environment,
48
+ "started_at": self.started_at,
49
+ "spans": [span.to_dict() for span in self.spans],
50
+ }
@@ -0,0 +1,31 @@
1
+ from uuid import uuid4
2
+ from circleflake import CircleFlake
3
+
4
+
5
+ def test_langchain_callback_maps_parent_child():
6
+ cf = CircleFlake("test-agent")
7
+ handler = cf.langchain_handler
8
+ root_id, child_id = uuid4(), uuid4()
9
+
10
+ handler.on_chain_start({"name": "root"}, {}, run_id=root_id)
11
+ handler.on_tool_start(
12
+ {"name": "lookup"}, "query", run_id=child_id, parent_run_id=root_id
13
+ )
14
+ handler.on_tool_end("result", run_id=child_id)
15
+ handler.on_chain_end({}, run_id=root_id)
16
+
17
+ spans = cf.tracer.get_traces()[0].spans
18
+ assert [s.name for s in spans] == ["root", "lookup"]
19
+ assert spans[1].parent_span_id == spans[0].span_id
20
+ assert spans[0].status == spans[1].status == "ok"
21
+
22
+
23
+ def test_callback_error_status():
24
+ cf = CircleFlake("test-agent")
25
+ run_id = uuid4()
26
+ cf.langchain_handler.on_llm_start(
27
+ {"name": "model"}, ["prompt"], run_id=run_id
28
+ )
29
+ cf.langchain_handler.on_llm_error(RuntimeError("failed"), run_id=run_id)
30
+ span = cf.tracer.get_traces()[0].spans[0]
31
+ assert span.status == "error"
@@ -0,0 +1,33 @@
1
+ from circleflake import CircleFlake
2
+
3
+
4
+ def test_nested_spans_share_trace_and_parent():
5
+ cf = CircleFlake("test-agent")
6
+ with cf.tracer.span("root") as root:
7
+ with cf.tracer.span("child") as child:
8
+ pass
9
+ assert child.trace_id == root.trace_id
10
+ assert child.parent_span_id == root.span_id
11
+ assert root.status == child.status == "ok"
12
+ assert root.ended_at and child.ended_at
13
+
14
+
15
+ def test_exception_marks_span_error():
16
+ cf = CircleFlake("test-agent")
17
+ try:
18
+ with cf.tracer.span("failing"):
19
+ raise ValueError("bad")
20
+ except ValueError:
21
+ pass
22
+ span = cf.tracer.get_traces()[0].spans[0]
23
+ assert span.status == "error"
24
+ assert span.attributes["error.type"] == "ValueError"
25
+
26
+
27
+ def test_flush_exports_and_clears():
28
+ cf = CircleFlake("test-agent")
29
+ with cf.tracer.span("root"):
30
+ pass
31
+ cf.flush()
32
+ assert len(cf.exporter.exported) == 1
33
+ assert cf.tracer.get_traces() == []