diff --git a/LICENSE b/LICENSE index 5c37e25..589e5e1 100644 --- a/LICENSE +++ b/LICENSE @@ -1,49 +1,179 @@ -Business Source License 1.1 - -Licensor: WildEdge -Licensed Work: The python-sdk software and associated documentation files. -Change Date: 2030-03-17 -Change License: Apache License, Version 2.0 -Additional Use Grant: You may use the Licensed Work for development, testing, and evaluation purposes only. - ---- - -### Business Source License 1.1 - -Terms - -The Licensor hereby grants you the right to copy, modify, create derivative works, redistribute, and make non-production use of the Licensed Work. The Licensor may make an Additional Use Grant, above, permitting limited production use. - -Effective on the Change Date, or the fourth anniversary of the first public availability of a specific version of the Licensed Work under this License, whichever comes first, the Licensor hereby grants you rights under the terms of the Change License, and the rights granted in the paragraph above terminate. - -If your use of the Licensed Work does not comply with the requirements currently in effect as described in this License, you must purchase a commercial license from the Licensor, its affiliated entities, or authorized resellers, or you must refrain from using the Licensed Work. - -All copies of the Licensed Work must include this License. - -Any use of the Licensed Work in violation of this License will automatically terminate your rights under this License for the current and all other versions of the Licensed Work. - -This License does not grant you any right in any trademark or logo of Licensor or its affiliates. - -TO THE EXTENT PERMITTED BY APPLICABLE LAW, THE LICENSED WORK IS PROVIDED ON AN “AS IS” BASIS. LICENSOR HEREBY DISCLAIMS ALL WARRANTIES AND CONDITIONS, EXPRESS OR IMPLIED, INCLUDING (WITHOUT LIMITATION) WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, NON-INFRINGEMENT, AND TITLE. - ---- - -### Definitions - -“License” means this Business Source License. - -“Licensor” means the individual or entity that offers the Licensed Work under the terms of this License. - -“Licensed Work” means the work of authorship made available under this License. - -“Use” means to use, reproduce, modify, distribute, or otherwise exploit the Licensed Work. - -“Change Date” means the date specified by the Licensor after which the Licensed Work will be governed by the Change License. - -“Change License” means the license that will govern the Licensed Work after the Change Date. - ---- - -### Notice - -The text of this License is based on the Business Source License 1.1, published by MariaDB plc. + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship made available under + the License, as indicated by a copyright notice that is included in + or attached to the work (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean, as submitted to the Licensor for inclusion + in the Work by the copyright owner or by an individual or Legal Entity + authorized to submit on behalf of the copyright owner. For the purposes + of this definition, "submitted" means any form of electronic, verbal, + or written communication sent to the Licensor or its representatives, + including but not limited to communication on electronic mailing lists, + source code control systems, and issue tracking systems that are managed + by, or on behalf of, the Licensor for the purpose of recording and + discussing information about the Work, but excluding communication that + is conspicuously marked or designated in writing by the copyright owner + as "Not a Contribution." + + "Contributor" shall mean Licensor and any Legal Entity on behalf of + whom a Contribution has been received by the Licensor and included + within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by the combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a cross-claim + or counterclaim in a lawsuit) alleging that the Work or any + Contribution embodied within the Work constitutes direct or contributory + patent infringement, then any patent licenses granted to You under + this License for that Work shall terminate as of the date such + litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or Derivative + Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, You must include a readable copy of the + attribution notices contained within such NOTICE file, in + at least one of the following places: within a NOTICE text + file distributed as part of the Derivative Works; within + the Source form or documentation, if provided along with the + Derivative Works; or, within a display generated by the + Derivative Works, if and wherever such third-party notices + normally appear. The contents of the NOTICE file are for + informational purposes only and do not modify the License. + You may add Your own attribution notices within Derivative + Works that You distribute, alongside or in addition to the + NOTICE text from the Work, provided that such additional + attribution notices cannot be construed as modifying the + License. + + You may add Your own license statement for Your modifications and + may provide additional grant of rights to use, copy, modify, merge, + publish, distribute, sublicense, and/or sell copies of the + Contribution, either on its own terms or under the terms of this + License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any conditions of TITLE, + MERCHANTABLITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely + responsible for determining the appropriateness of using or + reproducing the Work and assume any risks associated with Your + exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or exemplary damages of any character arising as a + result of this License or out of the use or inability to use the + Work (even if such Contributor has been advised of the possibility + of such damages). + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may offer only + conditions consistent with this License. + + END OF TERMS AND CONDITIONS + + Copyright 2024 WildEdge + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/README.md b/README.md index 1777cd2..955a221 100644 --- a/README.md +++ b/README.md @@ -79,6 +79,7 @@ If no DSN is configured, the client becomes a no-op and logs a warning. | Integration | Example | |---|---| +| `anthropic` | [anthropic_example.py](https://github.com/wild-edge/wildedge-python/blob/main/examples/anthropic_example.py) | | `openai` | [openai_example.py](https://github.com/wild-edge/wildedge-python/blob/main/examples/openai_example.py) | **Hub tracking** @@ -109,6 +110,7 @@ For advanced options (batching, queue tuning, dead-letter storage), see [Configu | Name | Link | |---|---| | agntr | [github.com/pmaciolek/agntr](https://github.com/pmaciolek/agntr) | +| demo-app | [github.com/wild-edge/demo-app](https://github.com/wild-edge/demo-app) | | *(your project here)* | - | Using WildEdge in your project? Open a PR to add it to the list. diff --git a/docs/compatibility.md b/docs/compatibility.md index 45c53d2..9f417fa 100644 --- a/docs/compatibility.md +++ b/docs/compatibility.md @@ -4,6 +4,8 @@ The table below is generated from `scripts/compat_matrix.py`. | Integration | Version set | Dependencies | Supported Python | |---|---|---|---| +| `anthropic` | `min` | `anthropic==0.25.0` | 3.10, 3.11, 3.12, 3.13 | +| `anthropic` | `current` | `anthropic==0.92.0` | 3.10, 3.11, 3.12, 3.13 | | `onnx` | `min` | `onnxruntime==1.18.1`, `numpy==1.26.4` | 3.10, 3.11, 3.12, 3.13, 3.14 | | `onnx` | `min` (`py3.13` override) | `onnxruntime==1.20.1`, `numpy==2.1.3` | 3.13 | | `onnx` | `current` | `onnxruntime==1.20.1`, `numpy==2.1.3` | 3.10, 3.11, 3.12, 3.13, 3.14 | diff --git a/examples/anthropic_example.py b/examples/anthropic_example.py new file mode 100644 index 0000000..62fca35 --- /dev/null +++ b/examples/anthropic_example.py @@ -0,0 +1,48 @@ +# /// script +# requires-python = ">=3.10" +# dependencies = ["wildedge-sdk", "anthropic"] +# +# [tool.uv.sources] +# wildedge-sdk = { path = "..", editable = true } +# /// +"""Anthropic integration example. + +WildEdge patches anthropic.Anthropic (and AsyncAnthropic) at instrumentation +time, so inference tracking happens automatically for every messages.create call. + +Run with: uv run anthropic_example.py +Requires: ANTHROPIC_API_KEY environment variable. Set WILDEDGE_DSN to send events. +""" + +import anthropic + +import wildedge + +client = wildedge.init( + app_version="1.0.0", # uses WILDEDGE_DSN if set; otherwise no-op + integrations="anthropic", +) + +anthropic_client = anthropic.Anthropic() # set ANTHROPIC_API_KEY or pass api_key= + +prompts = [ + "Explain transformer attention in one sentence.", + "What is the capital of Japan?", + "Write a haiku about edge AI.", +] + +for prompt in prompts: + stream = anthropic_client.messages.create( + model="claude-haiku-4-5", + max_tokens=256, + messages=[{"role": "user", "content": prompt}], + stream=True, + ) + print(f"Q: {prompt}\nA: ", end="", flush=True) + for event in stream: + if event.type == "content_block_delta" and event.delta.type == "text_delta": + print(event.delta.text, end="", flush=True) + print("\n") + +client.flush() +print("Done. Events flushed to WildEdge.") diff --git a/pyproject.toml b/pyproject.toml index fa9edea..a1257ad 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "wildedge-sdk" -version = "0.1.3" +version = "0.1.4" description = "On-device ML inference monitoring for Python" readme = "README.md" requires-python = ">=3.10" @@ -14,7 +14,7 @@ classifiers = [ "Development Status :: 4 - Beta", "Intended Audience :: Developers", "Intended Audience :: Science/Research", - "License :: Other/Proprietary License", + "License :: OSI Approved :: Apache Software License", "Programming Language :: Python :: 3", "Programming Language :: Python :: 3.10", "Programming Language :: Python :: 3.11", diff --git a/scripts/compat_matrix.py b/scripts/compat_matrix.py index 610df72..7cb5d22 100644 --- a/scripts/compat_matrix.py +++ b/scripts/compat_matrix.py @@ -8,6 +8,10 @@ import sys MATRIX = { + "anthropic": { + "min": ["anthropic==0.25.0"], + "current": ["anthropic==0.92.0"], + }, "onnx": { "min": ["onnxruntime==1.18.1", "numpy==1.26.4"], "current": ["onnxruntime==1.20.1", "numpy==2.1.3"], @@ -56,6 +60,7 @@ } SUPPORTED_PYTHON = { + "anthropic": ["3.10", "3.11", "3.12", "3.13"], "onnx": ["3.10", "3.11", "3.12", "3.13", "3.14"], "torch": ["3.10", "3.11", "3.12", "3.13", "3.14"], "timm": ["3.10", "3.11", "3.12", "3.13", "3.14"], diff --git a/tests/compat/test_anthropic_compat.py b/tests/compat/test_anthropic_compat.py new file mode 100644 index 0000000..0b7fadc --- /dev/null +++ b/tests/compat/test_anthropic_compat.py @@ -0,0 +1,9 @@ +from __future__ import annotations + +import pytest + + +def test_anthropic_import_and_instrument(compat_client): + anthropic = pytest.importorskip("anthropic") + assert getattr(anthropic, "__version__", None) + compat_client.instrument("anthropic") diff --git a/tests/test_integrations_anthropic.py b/tests/test_integrations_anthropic.py new file mode 100644 index 0000000..f565e68 --- /dev/null +++ b/tests/test_integrations_anthropic.py @@ -0,0 +1,613 @@ +"""Tests for the Anthropic SDK integration.""" + +from __future__ import annotations + +import types +from types import SimpleNamespace +from unittest.mock import MagicMock + +import pytest + +import wildedge.integrations.anthropic as anthropic_mod +from wildedge.integrations.anthropic import ( + AnthropicExtractor, + build_api_meta, + build_input_meta, + build_output_meta, + wrap_async_messages, + wrap_sync_messages, +) +from wildedge.integrations.common import AsyncStreamWrapper, SyncStreamWrapper +from wildedge.model import ModelHandle, ModelInfo + +# --------------------------------------------------------------------------- +# Fake objects — no anthropic library required +# --------------------------------------------------------------------------- + + +class FakeUsage: + input_tokens = 10 + output_tokens = 20 + cache_read_input_tokens = 4 + + +class FakeUsageNoCache: + input_tokens = 10 + output_tokens = 20 + cache_read_input_tokens = None + + +class FakeResponse: + model = "claude-opus-4-6-20251101" + stop_reason = "end_turn" + usage = FakeUsage() + + +class FakeResponseNoUsage: + model = None + stop_reason = None + usage = None + + +class FakeMessages: + def __init__(self, response=None): + self._response = response or FakeResponse() + + def create(self, *args, **kwargs): + return self._response + + +class FakeAsyncMessages: + def __init__(self, response=None): + self._response = response or FakeResponse() + + async def create(self, *args, **kwargs): + return self._response + + +class RawMessageStartEvent: + def __init__(self, input_tokens=10, cached=4, model="claude-opus-4-6"): + usage = SimpleNamespace( + input_tokens=input_tokens, cache_read_input_tokens=cached + ) + self.message = SimpleNamespace(usage=usage, model=model) + + +class RawMessageDeltaEvent: + def __init__(self, output_tokens=20, stop_reason="end_turn"): + self.usage = SimpleNamespace(output_tokens=output_tokens) + self.delta = SimpleNamespace(stop_reason=stop_reason) + + +class RawContentBlockDeltaEvent: + def __init__(self, text="hi"): + self.delta = SimpleNamespace(type="text_delta", text=text) + + +def make_message_start_event(input_tokens=10, cached=4, model="claude-opus-4-6"): + return RawMessageStartEvent(input_tokens=input_tokens, cached=cached, model=model) + + +def make_message_delta_event(output_tokens=20, stop_reason="end_turn"): + return RawMessageDeltaEvent(output_tokens=output_tokens, stop_reason=stop_reason) + + +def make_content_block_delta_event(text="hi"): + return RawContentBlockDeltaEvent(text=text) + + +class FakeStreamingMessages: + def __init__(self, events): + self._events = events + + def create(self, *args, **kwargs): + if kwargs.get("stream"): + return iter(self._events) + return FakeResponse() + + +class FakeAsyncStreamingMessages: + def __init__(self, events): + self._events = events + + async def create(self, *args, **kwargs): + if kwargs.get("stream"): + return FakeAsyncIterator(self._events) + return FakeResponse() + + +class FakeAsyncIterator: + def __init__(self, items): + self._iter = iter(items) + + def __aiter__(self): + return self + + async def __anext__(self): + try: + return next(self._iter) + except StopIteration: + raise StopAsyncIteration + + +# Named "Anthropic" / "AsyncAnthropic" so can_handle sees the right type name. +class Anthropic: + def __init__(self, api_key=None): + pass + + +class AsyncAnthropic: + def __init__(self, api_key=None): + pass + + +def make_handle(publish_spy) -> ModelHandle: + info = ModelInfo( + model_name="test", + model_version="1.0", + model_source="anthropic", + model_format="api", + ) + return ModelHandle(model_id="claude-opus-4-6", info=info, publish=publish_spy) + + +def make_fake_client(closed=False): + client = SimpleNamespace(closed=closed, handles={}) + + def register_model(obj, *, model_id=None, source=None, **kwargs): + if model_id not in client.handles: + client.handles[model_id] = SimpleNamespace( + model_id=model_id, + track_inference=MagicMock(), + track_error=MagicMock(), + ) + return client.handles[model_id] + + client.register_model = register_model + return client + + +# --------------------------------------------------------------------------- +# build_input_meta +# --------------------------------------------------------------------------- + + +def test_build_input_meta_picks_last_user_message(): + messages = [ + {"role": "user", "content": "First message"}, + {"role": "assistant", "content": "Reply"}, + {"role": "user", "content": "Hello world"}, + ] + meta = build_input_meta(messages, tokens_in=5) + assert meta is not None + assert meta.char_count == len("Hello world") + assert meta.word_count == 2 + assert meta.token_count == 5 + assert meta.prompt_type == "chat" + + +def test_build_input_meta_content_block_list(): + messages = [ + { + "role": "user", + "content": [ + {"type": "text", "text": "Hello world"}, + {"type": "image", "source": {}}, + ], + } + ] + meta = build_input_meta(messages, tokens_in=None) + assert meta is not None + assert meta.char_count == len("Hello world") + assert meta.word_count == 2 + + +def test_build_input_meta_no_user_message_returns_none(): + assert ( + build_input_meta([{"role": "assistant", "content": "Hi"}], tokens_in=None) + is None + ) + + +def test_build_input_meta_empty_messages_returns_none(): + assert build_input_meta([], tokens_in=None) is None + + +def test_build_input_meta_empty_content_returns_none(): + assert build_input_meta([{"role": "user", "content": ""}], tokens_in=None) is None + + +# --------------------------------------------------------------------------- +# build_output_meta +# --------------------------------------------------------------------------- + + +def test_build_output_meta_extracts_tokens_and_stop_reason(): + meta = build_output_meta(FakeResponse(), duration_ms=500) + assert meta is not None + assert meta.tokens_in == 10 + assert meta.tokens_out == 20 + assert meta.stop_reason == "end_turn" + assert meta.tokens_per_second == pytest.approx(40.0) + + +def test_build_output_meta_extracts_cached_tokens(): + meta = build_output_meta(FakeResponse(), duration_ms=500) + assert meta is not None + assert meta.cached_input_tokens == 4 + + +def test_build_output_meta_none_cached_when_absent(): + response = SimpleNamespace( + usage=SimpleNamespace( + input_tokens=10, output_tokens=5, cache_read_input_tokens=None + ), + stop_reason="end_turn", + ) + meta = build_output_meta(response, duration_ms=100) + assert meta is not None + assert meta.cached_input_tokens is None + + +def test_build_output_meta_none_when_no_usage(): + assert build_output_meta(FakeResponseNoUsage(), duration_ms=500) is None + + +def test_build_output_meta_zero_duration_gives_no_tps(): + meta = build_output_meta(FakeResponse(), duration_ms=0) + assert meta is not None + assert meta.tokens_per_second is None + + +# --------------------------------------------------------------------------- +# build_api_meta +# --------------------------------------------------------------------------- + + +def test_build_api_meta_extracts_resolved_model_id(): + meta = build_api_meta(FakeResponse()) + assert meta is not None + assert meta.resolved_model_id == "claude-opus-4-6-20251101" + + +def test_build_api_meta_none_when_model_absent(): + assert build_api_meta(FakeResponseNoUsage()) is None + + +def test_build_api_meta_to_dict_contains_resolved_model_id(): + meta = build_api_meta(FakeResponse()) + assert meta is not None + assert "resolved_model_id" in meta.to_dict() + + +# --------------------------------------------------------------------------- +# AnthropicExtractor +# --------------------------------------------------------------------------- + + +class TestAnthropicExtractor: + extractor = AnthropicExtractor() + + def test_can_handle_anthropic(self): + assert self.extractor.can_handle(Anthropic()) + + def test_can_handle_async_anthropic(self): + assert self.extractor.can_handle(AsyncAnthropic()) + + def test_can_handle_rejects_other_types(self): + assert not self.extractor.can_handle(object()) + assert not self.extractor.can_handle("string") + + def test_extract_info_uses_override_model_id(self): + obj = Anthropic() + model_id, info = self.extractor.extract_info(obj, {"id": "claude-opus-4-6"}) + assert model_id == "claude-opus-4-6" + assert info.model_name == "claude-opus-4-6" + assert info.model_format == "api" + + def test_extract_info_source_defaults_to_anthropic(self): + _, info = self.extractor.extract_info(Anthropic(), {"id": "claude-opus-4-6"}) + assert info.model_source == "anthropic" + + def test_extract_info_returns_none_model_id_when_not_provided(self): + model_id, _ = self.extractor.extract_info(Anthropic(), {}) + assert model_id is None + + def test_install_hooks_is_noop(self, publish_spy): + handle = make_handle(publish_spy) + self.extractor.install_hooks(Anthropic(), handle) # must not raise + + +# --------------------------------------------------------------------------- +# wrap_sync_messages +# --------------------------------------------------------------------------- + + +class TestWrapSyncMessages: + def setup(self, response=None, closed=False): + messages = FakeMessages(response) + client = make_fake_client(closed=closed) + wrap_sync_messages(messages, lambda: client) + return messages, client + + def test_returns_response(self): + messages, _ = self.setup() + result = messages.create( + model="claude-opus-4-6", messages=[{"role": "user", "content": "hi"}] + ) + assert isinstance(result, FakeResponse) + + def test_registers_model_on_first_call(self): + messages, client = self.setup() + messages.create(model="claude-opus-4-6", messages=[]) + assert "claude-opus-4-6" in client.handles + + def test_lazy_registration_only_once(self): + messages, client = self.setup() + messages.create(model="claude-opus-4-6", messages=[]) + messages.create(model="claude-opus-4-6", messages=[]) + assert len(client.handles) == 1 + + def test_tracks_inference_with_token_counts(self): + messages, client = self.setup() + messages.create( + model="claude-opus-4-6", messages=[{"role": "user", "content": "hello"}] + ) + handle = client.handles["claude-opus-4-6"] + handle.track_inference.assert_called_once() + kwargs = handle.track_inference.call_args.kwargs + assert kwargs["input_modality"] == "text" + assert kwargs["output_modality"] == "generation" + assert kwargs["success"] is True + assert kwargs["output_meta"].tokens_out == 20 + + def test_tracks_api_meta(self): + messages, client = self.setup() + messages.create(model="claude-opus-4-6", messages=[]) + kwargs = client.handles["claude-opus-4-6"].track_inference.call_args.kwargs + assert kwargs["api_meta"] is not None + assert kwargs["api_meta"].resolved_model_id == "claude-opus-4-6-20251101" + + def test_tracks_error_and_reraises(self): + class ErrorMessages: + def create(self, *args, **kwargs): + raise RuntimeError("api error") + + client = make_fake_client() + messages = ErrorMessages() + wrap_sync_messages(messages, lambda: client) + + with pytest.raises(RuntimeError, match="api error"): + messages.create(model="claude-opus-4-6", messages=[]) + + client.handles["claude-opus-4-6"].track_error.assert_called_once() + client.handles["claude-opus-4-6"].track_inference.assert_not_called() + + def test_streaming_returns_sync_stream_wrapper(self): + events = [make_content_block_delta_event("hi"), make_message_delta_event()] + messages = FakeStreamingMessages(events) + client = make_fake_client() + wrap_sync_messages(messages, lambda: client) + result = messages.create(model="claude-opus-4-6", messages=[], stream=True) + assert isinstance(result, SyncStreamWrapper) + + def test_streaming_records_inference_on_exhaustion(self): + events = [ + make_message_start_event( + input_tokens=10, cached=4, model="claude-opus-4-6-20251101" + ), + make_content_block_delta_event("Hello world"), + make_message_delta_event(output_tokens=20, stop_reason="end_turn"), + ] + messages = FakeStreamingMessages(events) + client = make_fake_client() + wrap_sync_messages(messages, lambda: client) + stream = messages.create( + model="claude-opus-4-6", + messages=[{"role": "user", "content": "hi"}], + stream=True, + ) + list(stream) + handle = client.handles["claude-opus-4-6"] + handle.track_inference.assert_called_once() + kwargs = handle.track_inference.call_args.kwargs + assert kwargs["output_meta"].time_to_first_token_ms is not None + assert kwargs["output_meta"].stop_reason == "end_turn" + assert kwargs["output_meta"].tokens_out == 20 + assert kwargs["input_modality"] == "text" + assert kwargs["success"] is True + + def test_streaming_captures_token_counts_from_events(self): + events = [ + make_message_start_event(input_tokens=8, cached=2), + make_message_delta_event(output_tokens=15, stop_reason="end_turn"), + ] + messages = FakeStreamingMessages(events) + client = make_fake_client() + wrap_sync_messages(messages, lambda: client) + list(messages.create(model="claude-opus-4-6", messages=[], stream=True)) + out = client.handles["claude-opus-4-6"].track_inference.call_args.kwargs[ + "output_meta" + ] + assert out.tokens_in == 8 + assert out.tokens_out == 15 + assert out.cached_input_tokens == 2 + + def test_streaming_error_during_iteration_tracks_error(self): + def bad_iter(): + yield make_content_block_delta_event("hi") + raise RuntimeError("stream error") + + class ErrorStreamMessages: + def create(self, *args, **kwargs): + return bad_iter() + + client = make_fake_client() + messages = ErrorStreamMessages() + wrap_sync_messages(messages, lambda: client) + stream = messages.create(model="claude-opus-4-6", messages=[], stream=True) + with pytest.raises(RuntimeError, match="stream error"): + list(stream) + client.handles["claude-opus-4-6"].track_error.assert_called_once() + client.handles["claude-opus-4-6"].track_inference.assert_not_called() + + def test_closed_client_passes_through(self): + messages, client = self.setup(closed=True) + result = messages.create(model="claude-opus-4-6", messages=[]) + assert isinstance(result, FakeResponse) + assert "claude-opus-4-6" not in client.handles + + def test_different_models_get_separate_handles(self): + messages, client = self.setup() + messages.create(model="claude-opus-4-6", messages=[]) + messages.create(model="claude-haiku-4-5", messages=[]) + assert "claude-opus-4-6" in client.handles + assert "claude-haiku-4-5" in client.handles + + +# --------------------------------------------------------------------------- +# wrap_async_messages +# --------------------------------------------------------------------------- + + +class TestWrapAsyncMessages: + def setup(self, response=None, closed=False): + messages = FakeAsyncMessages(response) + client = make_fake_client(closed=closed) + wrap_async_messages(messages, lambda: client) + return messages, client + + async def test_returns_response(self): + messages, _ = self.setup() + result = await messages.create( + model="claude-opus-4-6", messages=[{"role": "user", "content": "hi"}] + ) + assert isinstance(result, FakeResponse) + + async def test_registers_model_on_first_call(self): + messages, client = self.setup() + await messages.create(model="claude-opus-4-6", messages=[]) + assert "claude-opus-4-6" in client.handles + + async def test_tracks_inference(self): + messages, client = self.setup() + await messages.create( + model="claude-opus-4-6", messages=[{"role": "user", "content": "hello"}] + ) + handle = client.handles["claude-opus-4-6"] + handle.track_inference.assert_called_once() + assert handle.track_inference.call_args.kwargs["output_meta"].tokens_out == 20 + + async def test_tracks_error_and_reraises(self): + class ErrorAsyncMessages: + async def create(self, *args, **kwargs): + raise RuntimeError("timeout") + + client = make_fake_client() + messages = ErrorAsyncMessages() + wrap_async_messages(messages, lambda: client) + + with pytest.raises(RuntimeError, match="timeout"): + await messages.create(model="claude-opus-4-6", messages=[]) + + client.handles["claude-opus-4-6"].track_error.assert_called_once() + + async def test_streaming_returns_async_stream_wrapper(self): + events = [make_content_block_delta_event("hi"), make_message_delta_event()] + messages = FakeAsyncStreamingMessages(events) + client = make_fake_client() + wrap_async_messages(messages, lambda: client) + result = await messages.create( + model="claude-opus-4-6", messages=[], stream=True + ) + assert isinstance(result, AsyncStreamWrapper) + + async def test_streaming_records_inference_on_exhaustion(self): + events = [ + make_message_start_event(input_tokens=10, model="claude-opus-4-6-20251101"), + make_content_block_delta_event("Hello world"), + make_message_delta_event(output_tokens=20, stop_reason="end_turn"), + ] + messages = FakeAsyncStreamingMessages(events) + client = make_fake_client() + wrap_async_messages(messages, lambda: client) + stream = await messages.create( + model="claude-opus-4-6", + messages=[{"role": "user", "content": "hi"}], + stream=True, + ) + async for _ in stream: + pass + handle = client.handles["claude-opus-4-6"] + handle.track_inference.assert_called_once() + kwargs = handle.track_inference.call_args.kwargs + assert kwargs["output_meta"].time_to_first_token_ms is not None + assert kwargs["output_meta"].stop_reason == "end_turn" + assert kwargs["success"] is True + + +# --------------------------------------------------------------------------- +# install_auto_load_patch +# --------------------------------------------------------------------------- + + +def test_install_auto_load_patch_is_idempotent(monkeypatch): + class FakeAnthropic: + def __init__(self, *args, **kwargs): + pass + + class FakeAsyncAnthropic: + def __init__(self, *args, **kwargs): + pass + + fake_anthropic = types.SimpleNamespace( + Anthropic=FakeAnthropic, AsyncAnthropic=FakeAsyncAnthropic + ) + monkeypatch.setattr(anthropic_mod, "_anthropic", fake_anthropic) + monkeypatch.setattr(anthropic_mod, "_anthropic_patched", False) + + AnthropicExtractor.install_auto_load_patch(lambda: None) + first_sync = fake_anthropic.Anthropic.__init__ + first_async = fake_anthropic.AsyncAnthropic.__init__ + + AnthropicExtractor.install_auto_load_patch(lambda: None) + assert fake_anthropic.Anthropic.__init__ is first_sync + assert fake_anthropic.AsyncAnthropic.__init__ is first_async + + +def test_install_auto_load_patch_skips_when_anthropic_missing(monkeypatch): + monkeypatch.setattr(anthropic_mod, "_anthropic", None) + monkeypatch.setattr(anthropic_mod, "_anthropic_patched", False) + + AnthropicExtractor.install_auto_load_patch(lambda: None) + assert not anthropic_mod._anthropic_patched + + +def test_install_auto_load_patch_wraps_new_client_instances(monkeypatch): + class FakeMessagesInner: + def create(self, *args, **kwargs): + return FakeResponseNoUsage() + + class FakeAnthropic: + messages = FakeMessagesInner() + + def __init__(self, *args, **kwargs): + pass + + class FakeAsyncAnthropic: + messages = FakeMessagesInner() + + def __init__(self, *args, **kwargs): + pass + + fake_anthropic = types.SimpleNamespace( + Anthropic=FakeAnthropic, AsyncAnthropic=FakeAsyncAnthropic + ) + monkeypatch.setattr(anthropic_mod, "_anthropic", fake_anthropic) + monkeypatch.setattr(anthropic_mod, "_anthropic_patched", False) + + client = make_fake_client() + AnthropicExtractor.install_auto_load_patch(lambda: client) + + instance = FakeAnthropic() + assert instance.messages.create is not FakeMessagesInner.create diff --git a/uv.lock b/uv.lock index 5043436..58a4ccf 100644 --- a/uv.lock +++ b/uv.lock @@ -419,7 +419,7 @@ wheels = [ [[package]] name = "wildedge-sdk" -version = "0.1.2" +version = "0.1.3" source = { editable = "." } [package.dev-dependencies] diff --git a/wildedge/client.py b/wildedge/client.py index 627cbc1..a6ac911 100644 --- a/wildedge/client.py +++ b/wildedge/client.py @@ -18,6 +18,7 @@ from wildedge.hubs.huggingface import HuggingFaceHubTracker from wildedge.hubs.registry import supported_hubs from wildedge.hubs.torchhub import TorchHubTracker +from wildedge.integrations.anthropic import AnthropicExtractor from wildedge.integrations.base import BaseExtractor from wildedge.integrations.gguf import GgufExtractor from wildedge.integrations.keras import KerasExtractor @@ -224,6 +225,7 @@ class WildEdge: SUPPORTED_INTEGRATIONS = supported_integrations() NOOP_INTEGRATIONS = noop_integrations() PATCH_INSTALLERS = { + "anthropic": AnthropicExtractor.install_auto_load_patch, "gguf": GgufExtractor.install_auto_load_patch, "mlx": MlxExtractor.install_auto_load_patch, "onnx": OnnxExtractor.install_auto_load_patch, diff --git a/wildedge/integrations/anthropic.py b/wildedge/integrations/anthropic.py new file mode 100644 index 0000000..407e097 --- /dev/null +++ b/wildedge/integrations/anthropic.py @@ -0,0 +1,367 @@ +"""Anthropic SDK integration.""" + +from __future__ import annotations + +import functools +import threading +import time +from typing import TYPE_CHECKING + +from wildedge import constants +from wildedge.events.inference import ApiMeta, GenerationOutputMeta, TextInputMeta +from wildedge.integrations.base import BaseExtractor +from wildedge.integrations.common import ( + AsyncStreamWrapper, + SyncStreamWrapper, + debug_failure, +) +from wildedge.model import ModelInfo +from wildedge.timing import elapsed_ms + +try: + import anthropic as _anthropic +except ImportError: + _anthropic = None # type: ignore[assignment] + +if TYPE_CHECKING: + from wildedge.model import ModelHandle + +_anthropic_patched = False +_ANTHROPIC_PATCH_LOCK = threading.Lock() +ANTHROPIC_INIT_PATCH_NAME = "anthropic_auto_load" + +debug_anthropic_failure = functools.partial(debug_failure, "anthropic") + + +def _extract_text(content: object) -> str: + """Return text from a string or Anthropic content-block list.""" + if isinstance(content, str): + return content + if isinstance(content, list): + parts = [] + for block in content: + text = ( + block.get("text", "") + if isinstance(block, dict) + else getattr(block, "text", "") + ) + if text: + parts.append(text) + return " ".join(parts) + return "" + + +def build_input_meta( + messages: list, + tokens_in: int | None, +) -> TextInputMeta | None: + last_user = next( + ( + m + for m in reversed(messages) + if (m.get("role") if isinstance(m, dict) else getattr(m, "role", None)) + == "user" + ), + None, + ) + if not last_user: + return None + raw = ( + last_user.get("content", "") + if isinstance(last_user, dict) + else getattr(last_user, "content", "") + ) + content = _extract_text(raw) + if not content: + return None + return TextInputMeta( + char_count=len(content), + word_count=len(content.split()), + token_count=tokens_in, + prompt_type="chat", + ) + + +def build_output_meta( + response: object, duration_ms: int +) -> GenerationOutputMeta | None: + try: + usage = getattr(response, "usage", None) + if usage is None: + return None + tokens_in = getattr(usage, "input_tokens", None) + tokens_out = getattr(usage, "output_tokens", None) + cached_input_tokens = getattr(usage, "cache_read_input_tokens", None) + stop_reason = getattr(response, "stop_reason", None) + tps = ( + round(tokens_out / duration_ms * 1000, 1) + if duration_ms > 0 and tokens_out + else None + ) + return GenerationOutputMeta( + task="generation", + tokens_in=tokens_in, + tokens_out=tokens_out, + cached_input_tokens=cached_input_tokens, + tokens_per_second=tps, + stop_reason=stop_reason, + ) + except Exception as exc: + debug_anthropic_failure("output meta extraction", exc) + return None + + +def build_api_meta(response: object) -> ApiMeta | None: + try: + resolved_model_id = getattr(response, "model", None) + if not resolved_model_id: + return None + return ApiMeta(resolved_model_id=resolved_model_id) + except Exception as exc: + debug_anthropic_failure("api meta extraction", exc) + return None + + +def resolve_handle( + model_id: str, + messages_obj: object, + model_handles: dict[str, ModelHandle], + client: object, +) -> ModelHandle | None: + if model_id not in model_handles: + try: + model_handles[model_id] = client.register_model( # type: ignore[attr-defined] + messages_obj, model_id=model_id, source="anthropic" + ) + except Exception as exc: + debug_anthropic_failure("model registration", exc) + return model_handles.get(model_id) + + +def make_anthropic_stream_callbacks( + handle: ModelHandle, + messages: list, +) -> tuple: + """Return (on_chunk, on_done) callbacks for an Anthropic streaming response. + + on_chunk dispatches on event type to accumulate token counts and stop reason. + on_done is called with (duration_ms, ttft_ms) when the stream is exhausted. + """ + tokens_in: list[int | None] = [None] + tokens_out: list[int | None] = [None] + cached_tokens: list[int | None] = [None] + stop_reason: list[str | None] = [None] + resolved_model: list[str | None] = [None] + + def on_chunk(event: object) -> None: + event_type = type(event).__name__ + if event_type == "RawMessageStartEvent": + msg = getattr(event, "message", None) + if msg is not None: + usage = getattr(msg, "usage", None) + if usage is not None: + tokens_in[0] = getattr(usage, "input_tokens", None) + cached_tokens[0] = getattr(usage, "cache_read_input_tokens", None) + resolved_model[0] = getattr(msg, "model", None) + elif event_type == "RawMessageDeltaEvent": + usage = getattr(event, "usage", None) + if usage is not None: + tokens_out[0] = getattr(usage, "output_tokens", None) + delta = getattr(event, "delta", None) + if delta is not None: + reason = getattr(delta, "stop_reason", None) + if reason: + stop_reason[0] = reason + + def on_done(duration_ms: int, ttft_ms: int | None) -> None: + ti, to, cr, sr = tokens_in[0], tokens_out[0], cached_tokens[0], stop_reason[0] + tps = round(to / duration_ms * 1000, 1) if duration_ms > 0 and to else None + api_meta = ( + ApiMeta(resolved_model_id=resolved_model[0]) if resolved_model[0] else None + ) + handle.track_inference( + duration_ms=duration_ms, + input_modality="text", + output_modality="generation", + success=True, + input_meta=build_input_meta(messages, ti), + output_meta=GenerationOutputMeta( + task="generation", + tokens_in=ti, + tokens_out=to, + cached_input_tokens=cr, + time_to_first_token_ms=ttft_ms, + tokens_per_second=tps, + stop_reason=sr, + ), + api_meta=api_meta, + ) + + return on_chunk, on_done + + +def wrap_sync_messages(messages_obj: object, client_ref: object) -> None: + original_create = messages_obj.create # type: ignore[attr-defined] + model_handles: dict[str, ModelHandle] = {} + + def patched_create(*args, **kwargs): + model_id: str | None = kwargs.get("model") or (args[0] if args else None) + messages: list = kwargs.get("messages", []) + is_streaming: bool = bool(kwargs.get("stream", False)) + c = client_ref() # type: ignore[call-arg] + if c is None or c.closed or not model_id: + return original_create(*args, **kwargs) + handle = resolve_handle(model_id, messages_obj, model_handles, c) + t0 = time.perf_counter() + try: + result = original_create(*args, **kwargs) + if handle is not None: + if is_streaming: + on_chunk, on_done = make_anthropic_stream_callbacks( + handle, messages + ) + return SyncStreamWrapper(result, handle, t0, on_chunk, on_done) + else: + duration = elapsed_ms(t0) + usage = getattr(result, "usage", None) + tokens_in = getattr(usage, "input_tokens", None) if usage else None + handle.track_inference( + duration_ms=duration, + input_modality="text", + output_modality="generation", + success=True, + input_meta=build_input_meta(messages, tokens_in), + output_meta=build_output_meta(result, duration), + api_meta=build_api_meta(result), + ) + return result + except Exception as exc: + if handle is not None: + handle.track_error( + error_code="UNKNOWN", + error_message=str(exc)[: constants.ERROR_MSG_MAX_LEN], + ) + raise + + messages_obj.create = patched_create # type: ignore[attr-defined] + + +def wrap_async_messages(messages_obj: object, client_ref: object) -> None: + original_create = messages_obj.create # type: ignore[attr-defined] + model_handles: dict[str, ModelHandle] = {} + + async def patched_create(*args, **kwargs): + model_id: str | None = kwargs.get("model") or (args[0] if args else None) + messages: list = kwargs.get("messages", []) + is_streaming: bool = bool(kwargs.get("stream", False)) + c = client_ref() # type: ignore[call-arg] + if c is None or c.closed or not model_id: + return await original_create(*args, **kwargs) + handle = resolve_handle(model_id, messages_obj, model_handles, c) + t0 = time.perf_counter() + try: + result = await original_create(*args, **kwargs) + if handle is not None: + if is_streaming: + on_chunk, on_done = make_anthropic_stream_callbacks( + handle, messages + ) + return AsyncStreamWrapper(result, handle, t0, on_chunk, on_done) + else: + duration = elapsed_ms(t0) + usage = getattr(result, "usage", None) + tokens_in = getattr(usage, "input_tokens", None) if usage else None + handle.track_inference( + duration_ms=duration, + input_modality="text", + output_modality="generation", + success=True, + input_meta=build_input_meta(messages, tokens_in), + output_meta=build_output_meta(result, duration), + api_meta=build_api_meta(result), + ) + return result + except Exception as exc: + if handle is not None: + handle.track_error( + error_code="UNKNOWN", + error_message=str(exc)[: constants.ERROR_MSG_MAX_LEN], + ) + raise + + messages_obj.create = patched_create # type: ignore[attr-defined] + + +class AnthropicExtractor(BaseExtractor): + def can_handle(self, obj: object) -> bool: + return type(obj).__name__ in ( + "Anthropic", + "AsyncAnthropic", + "Messages", + "AsyncMessages", + ) + + def extract_info( + self, obj: object, overrides: dict + ) -> tuple[str | None, ModelInfo]: + model_id = overrides.pop("id", None) + info = ModelInfo( + model_name=model_id or "anthropic-model", + model_version=overrides.pop("version", "unknown"), + model_source=overrides.pop("source", "anthropic"), + model_format="api", + model_family=overrides.pop("family", None), + quantization=None, + ) + return model_id, info + + def install_hooks(self, obj: object, handle: ModelHandle) -> None: + pass + + @classmethod + def install_auto_load_patch(cls, client_ref: object) -> None: + """Patch anthropic.Anthropic and anthropic.AsyncAnthropic to wrap messages.create.""" + global _anthropic_patched + if _anthropic_patched or _anthropic is None: + return + + with _ANTHROPIC_PATCH_LOCK: + if _anthropic_patched: + return + + original_sync_init = _anthropic.Anthropic.__init__ + original_async_init = _anthropic.AsyncAnthropic.__init__ + + if ( + getattr(original_sync_init, "__wildedge_patch_name__", None) + == ANTHROPIC_INIT_PATCH_NAME + ): + _anthropic_patched = True + return + + def patched_sync_init(self_inner, *args, **kwargs): # type: ignore[no-untyped-def] + original_sync_init(self_inner, *args, **kwargs) + c = client_ref() # type: ignore[call-arg] + if c is not None and not c.closed: + try: + wrap_sync_messages(self_inner.messages, client_ref) + except Exception as exc: + debug_anthropic_failure("sync client wrap", exc) + + def patched_async_init(self_inner, *args, **kwargs): # type: ignore[no-untyped-def] + original_async_init(self_inner, *args, **kwargs) + c = client_ref() # type: ignore[call-arg] + if c is not None and not c.closed: + try: + wrap_async_messages(self_inner.messages, client_ref) + except Exception as exc: + debug_anthropic_failure("async client wrap", exc) + + patched_sync_init.__wildedge_patch_name__ = ANTHROPIC_INIT_PATCH_NAME # type: ignore[attr-defined] + patched_sync_init.__wildedge_original_call__ = original_sync_init # type: ignore[attr-defined] + patched_async_init.__wildedge_patch_name__ = ANTHROPIC_INIT_PATCH_NAME # type: ignore[attr-defined] + patched_async_init.__wildedge_original_call__ = original_async_init # type: ignore[attr-defined] + + _anthropic.Anthropic.__init__ = patched_sync_init + _anthropic.AsyncAnthropic.__init__ = patched_async_init + _anthropic_patched = True diff --git a/wildedge/integrations/registry.py b/wildedge/integrations/registry.py index e795f38..8321720 100644 --- a/wildedge/integrations/registry.py +++ b/wildedge/integrations/registry.py @@ -23,6 +23,7 @@ class IntegrationSpec: INTEGRATION_SPECS: tuple[IntegrationSpec, ...] = ( + IntegrationSpec("anthropic", ("anthropic",), "client_patch"), IntegrationSpec("gguf", ("llama_cpp",), "client_patch"), IntegrationSpec("onnx", ("onnxruntime",), "client_patch"), IntegrationSpec("openai", ("openai",), "client_patch"),