cogno-synapse 0.1.0__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,201 @@
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, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2026 Sudoers AI
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
@@ -0,0 +1,121 @@
1
+ Metadata-Version: 2.4
2
+ Name: cogno-synapse
3
+ Version: 0.1.0
4
+ Summary: Model-transport layer for the Cogno cognitive pipeline — LLM + embedding backend protocols, Ollama + cloud backends, a single-backend factory, and a resilient fallback chain
5
+ Author: Vinicius Vale
6
+ Maintainer: Sudoers AI
7
+ License-Expression: Apache-2.0
8
+ Project-URL: Homepage, https://github.com/sudoers-ai/cogno-synapse
9
+ Project-URL: Repository, https://github.com/sudoers-ai/cogno-synapse
10
+ Project-URL: Issues, https://github.com/sudoers-ai/cogno-synapse/issues
11
+ Keywords: llm,embeddings,ollama,openai,anthropic,fallback,agents,function-calling
12
+ Classifier: Development Status :: 3 - Alpha
13
+ Classifier: Intended Audience :: Developers
14
+ Classifier: Programming Language :: Python :: 3
15
+ Classifier: Programming Language :: Python :: 3.10
16
+ Classifier: Programming Language :: Python :: 3.11
17
+ Classifier: Programming Language :: Python :: 3.12
18
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
19
+ Classifier: Topic :: Software Development :: Libraries
20
+ Classifier: Operating System :: OS Independent
21
+ Classifier: Typing :: Typed
22
+ Requires-Python: >=3.10
23
+ Description-Content-Type: text/markdown
24
+ License-File: LICENSE
25
+ Requires-Dist: httpx>=0.20.0
26
+ Requires-Dist: cogno-homeo<0.2,>=0.1
27
+ Provides-Extra: dev
28
+ Requires-Dist: pytest>=8.0; extra == "dev"
29
+ Requires-Dist: pytest-asyncio>=0.23.0; extra == "dev"
30
+ Requires-Dist: pytest-cov>=5.0; extra == "dev"
31
+ Requires-Dist: ruff>=0.5; extra == "dev"
32
+ Requires-Dist: mypy>=1.8; extra == "dev"
33
+ Provides-Extra: openai
34
+ Requires-Dist: openai>=1.0; extra == "openai"
35
+ Provides-Extra: anthropic
36
+ Requires-Dist: anthropic>=0.34; extra == "anthropic"
37
+ Provides-Extra: groq
38
+ Requires-Dist: groq>=0.9; extra == "groq"
39
+ Provides-Extra: gemini
40
+ Requires-Dist: google-genai>=0.3; extra == "gemini"
41
+ Provides-Extra: bedrock
42
+ Requires-Dist: boto3>=1.34; extra == "bedrock"
43
+ Provides-Extra: llm
44
+ Requires-Dist: openai>=1.0; extra == "llm"
45
+ Requires-Dist: anthropic>=0.34; extra == "llm"
46
+ Requires-Dist: groq>=0.9; extra == "llm"
47
+ Requires-Dist: google-genai>=0.3; extra == "llm"
48
+ Requires-Dist: boto3>=1.34; extra == "llm"
49
+ Dynamic: license-file
50
+
51
+ # cogno-synapse
52
+
53
+ **Model-transport layer for the [Cogno](https://github.com/sudoers-ai/cogno-anima) cognitive pipeline** — LLM + embedding backend protocols, Ollama + cloud backends, a single-backend factory, and a resilient fallback chain.
54
+
55
+ Named for the *synapse*: the junction that carries the signal between neurons. Where [`cogno-anima`](https://github.com/sudoers-ai/cogno-anima) is the *mind* and [`cogno-engram`](https://github.com/sudoers-ai/cogno-engram) is the *memory*, `cogno-synapse` is the **channel the mind speaks to language/embedding models through**.
56
+
57
+ > Status: **alpha** — extracted from `cogno-anima`'s `llm/` package; unit suite (mocked SDKs) in place.
58
+
59
+ ## Protocol first, implementation optional
60
+
61
+ The light, stable contract everyone shares is a set of structurally-typed `Protocol`s (no inheritance required):
62
+
63
+ - `LLMBackend` — `async generate(system, prompt) -> (text, tokens_in, tokens_out)` + a `model` attr.
64
+ - `ToolCallingBackend` (extends `LLMBackend`) — adds `chat_with_tools(...)` + `supports_native_tools()` for native function calling. **Separate and optional**, so a text-only backend (a stub, a distilled student) satisfies only `LLMBackend`.
65
+ - `Embedder` — `async embed(text) -> list[float]`, `async similarity(a, b) -> float`.
66
+
67
+ The heavy concrete cloud backends are **optional extras** (lazy-imported SDKs) — depend on the protocol, install only the providers you use:
68
+
69
+ ```bash
70
+ pip install cogno-synapse # protocols + Ollama + OpenAI-compatible HTTP + fallback (httpx only)
71
+ pip install "cogno-synapse[openai]" # + OpenAI SDK
72
+ pip install "cogno-synapse[anthropic|groq|gemini|bedrock]"
73
+ pip install "cogno-synapse[llm]" # all cloud SDKs
74
+ ```
75
+
76
+ ## Backends
77
+
78
+ `OllamaBackend`/`OllamaEmbedder` (local, `think=false` by default so reasoning models still return direct JSON), plus `OpenAIBackend`, `AnthropicBackend`, `GroqBackend`, `GeminiBackend`, `BedrockBackend` — each implements `LLMBackend` + `ToolCallingBackend`. OpenAI-compatible providers (DeepSeek, Moonshot, xAI/Grok, OpenRouter, Together, Fireworks) reuse `OpenAIBackend` via `base_url`; `create_backend("provider:model")` instantiates one by string. Backends **raise** on transport/auth failure (`InvalidAPIKeyError` for 401/403) rather than degrading silently.
79
+
80
+ `CachingEmbedder` wraps any `Embedder` with a bounded LRU + token accounting (`EmbeddingUsage`). `parse_tool_calls_from_text` reads `<TOOL_CALL>` tags for the text-fallback function-calling path (and rescues FC leaks).
81
+
82
+ ## Resilient fallback — over `cogno-homeo`
83
+
84
+ `FallbackBackend` tries an ordered chain, first success wins, last error propagates. The loop runs on [`cogno-homeo`](https://github.com/sudoers-ai/cogno-homeo)'s `resilient_call`, so you can opt into a circuit breaker, retry/backoff, and a metrics seam — with none supplied it behaves like the historical "try each once" chain:
85
+
86
+ ```python
87
+ from cogno_synapse import FallbackBackend, create_backend
88
+ from cogno_homeo import CircuitBreaker, RetryPolicy
89
+
90
+ chain = FallbackBackend(
91
+ [create_backend("openai:gpt-4o-mini"), create_backend("groq:llama-3.1-8b-instant")],
92
+ breaker=CircuitBreaker(), policy=RetryPolicy(max_retries=2), # optional
93
+ )
94
+ text, tin, tout = await chain.generate(system, prompt)
95
+ ```
96
+
97
+ ## Scope
98
+
99
+ This library is **transport only** — it produces raw token counts but does not price them (the host does), and it carries no business model-ladder/`_FALLBACK_MATRIX` (also host). Resilience is delegated to `cogno-homeo`; cognition lives in `cogno-anima`.
100
+
101
+ ## The Cogno ecosystem
102
+
103
+ `cogno-synapse` is one organ of **[Cogno](https://github.com/sudoers-ai)** — a family of
104
+ small, composable, Apache-2.0 libraries that together form a complete
105
+ conversational-agent platform. Each library owns a single concern and stays
106
+ infra-agnostic; a **host** assembles them into a running agent:
107
+
108
+ ![The Cogno ecosystem](docs/assets/cogno-ecosystem.svg)
109
+
110
+ The open-source libraries are the organs; the **host is the body** that joins
111
+ them. Our reference host — `cogno-host`, with its `cogno-ui` dashboard — is the
112
+ private product layer, but it holds no special powers: everything it does rides
113
+ on the public seams documented in each library's `docs/HOST_INTEGRATION.md`, so
114
+ you can assemble a body of your own.
115
+
116
+ ## Test
117
+
118
+ ```bash
119
+ pip install -e ".[dev]" # unit tests mock every SDK — no cloud keys needed
120
+ pytest tests/unit -q
121
+ ```
@@ -0,0 +1,71 @@
1
+ # cogno-synapse
2
+
3
+ **Model-transport layer for the [Cogno](https://github.com/sudoers-ai/cogno-anima) cognitive pipeline** — LLM + embedding backend protocols, Ollama + cloud backends, a single-backend factory, and a resilient fallback chain.
4
+
5
+ Named for the *synapse*: the junction that carries the signal between neurons. Where [`cogno-anima`](https://github.com/sudoers-ai/cogno-anima) is the *mind* and [`cogno-engram`](https://github.com/sudoers-ai/cogno-engram) is the *memory*, `cogno-synapse` is the **channel the mind speaks to language/embedding models through**.
6
+
7
+ > Status: **alpha** — extracted from `cogno-anima`'s `llm/` package; unit suite (mocked SDKs) in place.
8
+
9
+ ## Protocol first, implementation optional
10
+
11
+ The light, stable contract everyone shares is a set of structurally-typed `Protocol`s (no inheritance required):
12
+
13
+ - `LLMBackend` — `async generate(system, prompt) -> (text, tokens_in, tokens_out)` + a `model` attr.
14
+ - `ToolCallingBackend` (extends `LLMBackend`) — adds `chat_with_tools(...)` + `supports_native_tools()` for native function calling. **Separate and optional**, so a text-only backend (a stub, a distilled student) satisfies only `LLMBackend`.
15
+ - `Embedder` — `async embed(text) -> list[float]`, `async similarity(a, b) -> float`.
16
+
17
+ The heavy concrete cloud backends are **optional extras** (lazy-imported SDKs) — depend on the protocol, install only the providers you use:
18
+
19
+ ```bash
20
+ pip install cogno-synapse # protocols + Ollama + OpenAI-compatible HTTP + fallback (httpx only)
21
+ pip install "cogno-synapse[openai]" # + OpenAI SDK
22
+ pip install "cogno-synapse[anthropic|groq|gemini|bedrock]"
23
+ pip install "cogno-synapse[llm]" # all cloud SDKs
24
+ ```
25
+
26
+ ## Backends
27
+
28
+ `OllamaBackend`/`OllamaEmbedder` (local, `think=false` by default so reasoning models still return direct JSON), plus `OpenAIBackend`, `AnthropicBackend`, `GroqBackend`, `GeminiBackend`, `BedrockBackend` — each implements `LLMBackend` + `ToolCallingBackend`. OpenAI-compatible providers (DeepSeek, Moonshot, xAI/Grok, OpenRouter, Together, Fireworks) reuse `OpenAIBackend` via `base_url`; `create_backend("provider:model")` instantiates one by string. Backends **raise** on transport/auth failure (`InvalidAPIKeyError` for 401/403) rather than degrading silently.
29
+
30
+ `CachingEmbedder` wraps any `Embedder` with a bounded LRU + token accounting (`EmbeddingUsage`). `parse_tool_calls_from_text` reads `<TOOL_CALL>` tags for the text-fallback function-calling path (and rescues FC leaks).
31
+
32
+ ## Resilient fallback — over `cogno-homeo`
33
+
34
+ `FallbackBackend` tries an ordered chain, first success wins, last error propagates. The loop runs on [`cogno-homeo`](https://github.com/sudoers-ai/cogno-homeo)'s `resilient_call`, so you can opt into a circuit breaker, retry/backoff, and a metrics seam — with none supplied it behaves like the historical "try each once" chain:
35
+
36
+ ```python
37
+ from cogno_synapse import FallbackBackend, create_backend
38
+ from cogno_homeo import CircuitBreaker, RetryPolicy
39
+
40
+ chain = FallbackBackend(
41
+ [create_backend("openai:gpt-4o-mini"), create_backend("groq:llama-3.1-8b-instant")],
42
+ breaker=CircuitBreaker(), policy=RetryPolicy(max_retries=2), # optional
43
+ )
44
+ text, tin, tout = await chain.generate(system, prompt)
45
+ ```
46
+
47
+ ## Scope
48
+
49
+ This library is **transport only** — it produces raw token counts but does not price them (the host does), and it carries no business model-ladder/`_FALLBACK_MATRIX` (also host). Resilience is delegated to `cogno-homeo`; cognition lives in `cogno-anima`.
50
+
51
+ ## The Cogno ecosystem
52
+
53
+ `cogno-synapse` is one organ of **[Cogno](https://github.com/sudoers-ai)** — a family of
54
+ small, composable, Apache-2.0 libraries that together form a complete
55
+ conversational-agent platform. Each library owns a single concern and stays
56
+ infra-agnostic; a **host** assembles them into a running agent:
57
+
58
+ ![The Cogno ecosystem](docs/assets/cogno-ecosystem.svg)
59
+
60
+ The open-source libraries are the organs; the **host is the body** that joins
61
+ them. Our reference host — `cogno-host`, with its `cogno-ui` dashboard — is the
62
+ private product layer, but it holds no special powers: everything it does rides
63
+ on the public seams documented in each library's `docs/HOST_INTEGRATION.md`, so
64
+ you can assemble a body of your own.
65
+
66
+ ## Test
67
+
68
+ ```bash
69
+ pip install -e ".[dev]" # unit tests mock every SDK — no cloud keys needed
70
+ pytest tests/unit -q
71
+ ```
@@ -0,0 +1,58 @@
1
+ """
2
+ cogno-synapse — the model-transport layer of the Cogno stack.
3
+
4
+ Named for the *synapse*: the junction that carries the signal between neurons.
5
+ Where cogno-anima is the mind and cogno-engram is the memory, cogno-synapse is
6
+ the channel the mind speaks to language/embedding models through — a set of
7
+ structurally-typed backend protocols plus concrete implementations (Ollama +
8
+ cloud providers), a single-backend factory, a resilient fallback chain, and the
9
+ text-fallback tool-call parser.
10
+
11
+ The protocols are the light, stable contract everyone shares; the concrete cloud
12
+ backends are optional extras (lazy-imported SDKs). Resilience (breaker/retry/
13
+ metrics) is delegated to cogno-homeo.
14
+ """
15
+
16
+ from importlib.metadata import PackageNotFoundError
17
+ from importlib.metadata import version as _dist_version
18
+
19
+ try:
20
+ __version__ = _dist_version("cogno-synapse")
21
+ except PackageNotFoundError: # source tree without an installed dist (e.g. vendored checkout)
22
+ __version__ = "0.0.0"
23
+
24
+
25
+ from cogno_synapse.base import LLMBackend, ToolCallingBackend, Embedder
26
+ from cogno_synapse.ollama import OllamaBackend, OllamaEmbedder
27
+ from cogno_synapse.cache import CachingEmbedder, EmbeddingUsage
28
+ from cogno_synapse.tool_parsing import parse_tool_calls_from_text
29
+ from cogno_synapse.openai_backend import OpenAIBackend
30
+ from cogno_synapse.anthropic_backend import AnthropicBackend
31
+ from cogno_synapse.groq_backend import GroqBackend
32
+ from cogno_synapse.gemini_backend import GeminiBackend
33
+ from cogno_synapse.bedrock_backend import BedrockBackend
34
+ from cogno_synapse.fallback import FallbackBackend
35
+ from cogno_synapse.factory import create_backend, parse_model_string
36
+ from cogno_synapse.errors import SynapseError, MissingAPIKeyError, InvalidAPIKeyError
37
+
38
+ __all__ = [
39
+ "LLMBackend",
40
+ "ToolCallingBackend",
41
+ "Embedder",
42
+ "OllamaBackend",
43
+ "OllamaEmbedder",
44
+ "CachingEmbedder",
45
+ "EmbeddingUsage",
46
+ "parse_tool_calls_from_text",
47
+ "OpenAIBackend",
48
+ "AnthropicBackend",
49
+ "GroqBackend",
50
+ "GeminiBackend",
51
+ "BedrockBackend",
52
+ "FallbackBackend",
53
+ "create_backend",
54
+ "parse_model_string",
55
+ "SynapseError",
56
+ "MissingAPIKeyError",
57
+ "InvalidAPIKeyError",
58
+ ]
@@ -0,0 +1,21 @@
1
+ """Tiny pure-Python vector math used by the embedding backends/cache.
2
+
3
+ Vendored (not imported from a sibling) so cogno-synapse stays free of any
4
+ cogno-anima dependency — this is a self-contained 10-line helper.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import math
10
+
11
+
12
+ def cosine_similarity(v1: list[float], v2: list[float]) -> float:
13
+ """Calculates cosine similarity between two vector lists in pure Python."""
14
+ if not v1 or not v2 or len(v1) != len(v2):
15
+ return 0.0
16
+ dot_product = sum(a * b for a, b in zip(v1, v2))
17
+ magnitude_v1 = math.sqrt(sum(a * a for a in v1))
18
+ magnitude_v2 = math.sqrt(sum(b * b for b in v2))
19
+ if magnitude_v1 == 0.0 or magnitude_v2 == 0.0:
20
+ return 0.0
21
+ return dot_product / (magnitude_v1 * magnitude_v2)
@@ -0,0 +1,59 @@
1
+ """
2
+ cogno_synapse._obs — tiny logging helpers shared by the backends.
3
+
4
+ Keeps the ``key=value`` log lines byte-identical across the six backends without
5
+ a logging framework. Per LOGGING.md: libs emit, the host configures. INFO marks
6
+ the (relatively expensive) "call finished" milestone; WARNING flags a recoverable
7
+ transport error (429/5xx) just before it propagates to a ``FallbackBackend``;
8
+ the request body goes to DEBUG only (dev-only — it carries user content/PII), and
9
+ the ``api_key`` is never logged.
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ import logging
15
+ import time
16
+ from typing import Any
17
+
18
+ # HTTP statuses worth a WARNING (rate limit / transient upstream) before re-raise.
19
+ _RETRYABLE_STATUS = frozenset({429, 500, 502, 503, 504})
20
+
21
+
22
+ def status_of(exc: Exception) -> Any:
23
+ """Best-effort HTTP status from an SDK/httpx exception (None if absent)."""
24
+ direct = getattr(exc, "status_code", None) or getattr(exc, "http_status", None)
25
+ if direct is not None:
26
+ return direct
27
+ resp = getattr(exc, "response", None)
28
+ return getattr(resp, "status_code", None)
29
+
30
+
31
+ def is_retryable(exc: Exception) -> bool:
32
+ return status_of(exc) in _RETRYABLE_STATUS
33
+
34
+
35
+ def log_request(logger: logging.Logger, provider: str, model: str, system: str, prompt: str) -> None:
36
+ """DEV-ONLY full request trace (DEBUG). Carries user content — never on in prod."""
37
+ if logger.isEnabledFor(logging.DEBUG):
38
+ logger.debug(
39
+ "event=generate provider=%s model=%s system_len=%d prompt_len=%d prompt=%s",
40
+ provider, model, len(system), len(prompt), prompt,
41
+ )
42
+
43
+
44
+ def log_done(
45
+ logger: logging.Logger, provider: str, model: str, t0: float, tokens_in: int, tokens_out: int
46
+ ) -> None:
47
+ logger.info(
48
+ "event=generate_done provider=%s model=%s latency_ms=%.1f tokens_in=%d tokens_out=%d",
49
+ provider, model, (time.perf_counter() - t0) * 1000.0, tokens_in, tokens_out,
50
+ )
51
+
52
+
53
+ def warn_if_retryable(logger: logging.Logger, provider: str, model: str, exc: Exception) -> None:
54
+ """WARNING on a recoverable transport error before it propagates (fallback catches)."""
55
+ if is_retryable(exc):
56
+ logger.warning(
57
+ "event=generate_retryable provider=%s model=%s status=%s error=%s",
58
+ provider, model, status_of(exc), exc,
59
+ )