diff --git a/ddtrace/contrib/internal/anthropic/utils.py b/ddtrace/contrib/internal/anthropic/utils.py index 1f383113c86..d662d41a030 100644 --- a/ddtrace/contrib/internal/anthropic/utils.py +++ b/ddtrace/contrib/internal/anthropic/utils.py @@ -88,6 +88,10 @@ def tag_params_on_span(span, kwargs, integration): for k, v in kwargs.items(): if k == "system" and integration.is_pc_sampled_span(span): span.set_tag_str("anthropic.request.system", integration.trunc(str(v))) + elif k == "metadata" and isinstance(v, dict): + user_id = _get_attr(v, "user_id", None) + if user_id: + span.set_tag_str("anthropic.request.user_id", str(user_id)) elif k not in ("messages", "model"): tagged_params[k] = v span.set_tag_str("anthropic.request.parameters", safe_json(tagged_params)) diff --git a/releasenotes/notes/add-userid-tag-anthropic-b842a8cbe209c5f1.yaml b/releasenotes/notes/add-userid-tag-anthropic-b842a8cbe209c5f1.yaml new file mode 100644 index 00000000000..0af58a7d4e7 --- /dev/null +++ b/releasenotes/notes/add-userid-tag-anthropic-b842a8cbe209c5f1.yaml @@ -0,0 +1,4 @@ +--- +features: + - | + tracing: Add ``anthropic.request.user_id`` tag to Anthropic spans from ``metadata.user_id`` parameter. diff --git a/tests/contrib/anthropic/test_anthropic.py b/tests/contrib/anthropic/test_anthropic.py index b77c520710c..6c84320d475 100644 --- a/tests/contrib/anthropic/test_anthropic.py +++ b/tests/contrib/anthropic/test_anthropic.py @@ -38,6 +38,22 @@ def test_global_tags(ddtrace_config_anthropic, anthropic, request_vcr, mock_trac assert span.get_tag("anthropic.request.api_key") == "sk-...key>" +def test_user_id_tag(ddtrace_config_anthropic, anthropic, request_vcr, mock_tracer): + llm = anthropic.Anthropic() + with override_global_config(dict(service="test-svc", env="staging", version="1234")): + cassette_name = "anthropic_completion.yaml" + with request_vcr.use_cassette(cassette_name): + llm.messages.create( + model="claude-3-opus-20240229", + max_tokens=15, + messages=[{"role": "user", "content": "What does Nietzsche mean by 'God is dead'?"}], + metadata={"user_id": "1234567890"}, + ) + + span = mock_tracer.pop_traces()[0][0] + assert span.get_tag("anthropic.request.user_id") == "1234567890" + + @pytest.mark.snapshot(token="tests.contrib.anthropic.test_anthropic.test_anthropic_llm", ignores=["resource"]) def test_anthropic_llm_sync_create(anthropic, request_vcr): llm = anthropic.Anthropic()