-
Notifications
You must be signed in to change notification settings - Fork 588
feat(cohere): upgrade integration from ai to gen_ai #5597
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
shellmayr
wants to merge
7
commits into
master
Choose a base branch
from
shellmayr/cohere/1-genai-migration
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+90
−63
Open
Changes from all commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
8fefe69
feat(cohere): upgrade integration from ai to gen_ai
shellmayr 623f173
format
shellmayr 2113d8f
fix role mapping
shellmayr f0e31e9
dont hardcode streaming parameter
shellmayr 8025537
do cohere specific mapping of roles
shellmayr 08c1c23
finish reasons as array
shellmayr 024cbff
use span.set_data & move system & op name out of try block to capture…
shellmayr File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -3,7 +3,7 @@ | |
|
|
||
| from sentry_sdk import consts | ||
| from sentry_sdk.ai.monitoring import record_token_usage | ||
| from sentry_sdk.consts import SPANDATA | ||
| from sentry_sdk.consts import OP, SPANDATA | ||
| from sentry_sdk.ai.utils import set_data_normalized | ||
|
|
||
| from typing import TYPE_CHECKING | ||
|
|
@@ -39,33 +39,35 @@ | |
| from cohere import StreamedChatResponse_StreamEnd as StreamEndStreamedChatResponse | ||
|
|
||
|
|
||
| COHERE_ROLE_MAPPING = { | ||
| "SYSTEM": "system", | ||
| "USER": "user", | ||
| "CHATBOT": "assistant", | ||
| "TOOL": "tool", | ||
| } | ||
|
|
||
|
|
||
| COLLECTED_CHAT_PARAMS = { | ||
| "model": SPANDATA.AI_MODEL_ID, | ||
| "k": SPANDATA.AI_TOP_K, | ||
| "p": SPANDATA.AI_TOP_P, | ||
| "seed": SPANDATA.AI_SEED, | ||
| "frequency_penalty": SPANDATA.AI_FREQUENCY_PENALTY, | ||
| "presence_penalty": SPANDATA.AI_PRESENCE_PENALTY, | ||
| "raw_prompting": SPANDATA.AI_RAW_PROMPTING, | ||
| "model": SPANDATA.GEN_AI_REQUEST_MODEL, | ||
| "k": SPANDATA.GEN_AI_REQUEST_TOP_K, | ||
| "p": SPANDATA.GEN_AI_REQUEST_TOP_P, | ||
| "seed": SPANDATA.GEN_AI_REQUEST_SEED, | ||
| "frequency_penalty": SPANDATA.GEN_AI_REQUEST_FREQUENCY_PENALTY, | ||
| "presence_penalty": SPANDATA.GEN_AI_REQUEST_PRESENCE_PENALTY, | ||
| } | ||
|
|
||
| COLLECTED_PII_CHAT_PARAMS = { | ||
| "tools": SPANDATA.AI_TOOLS, | ||
| "preamble": SPANDATA.AI_PREAMBLE, | ||
| "tools": SPANDATA.GEN_AI_REQUEST_AVAILABLE_TOOLS, | ||
| "preamble": SPANDATA.GEN_AI_SYSTEM_INSTRUCTIONS, | ||
| } | ||
|
|
||
| COLLECTED_CHAT_RESP_ATTRS = { | ||
| "generation_id": SPANDATA.AI_GENERATION_ID, | ||
| "is_search_required": SPANDATA.AI_SEARCH_REQUIRED, | ||
| "finish_reason": SPANDATA.AI_FINISH_REASON, | ||
| "generation_id": SPANDATA.GEN_AI_RESPONSE_ID, | ||
| "finish_reason": SPANDATA.GEN_AI_RESPONSE_FINISH_REASONS, | ||
shellmayr marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| } | ||
|
|
||
| COLLECTED_PII_CHAT_RESP_ATTRS = { | ||
| "citations": SPANDATA.AI_CITATIONS, | ||
| "documents": SPANDATA.AI_DOCUMENTS, | ||
| "search_queries": SPANDATA.AI_SEARCH_QUERIES, | ||
| "search_results": SPANDATA.AI_SEARCH_RESULTS, | ||
| "tool_calls": SPANDATA.AI_TOOL_CALLS, | ||
| "tool_calls": SPANDATA.GEN_AI_RESPONSE_TOOL_CALLS, | ||
| } | ||
|
|
||
|
|
||
|
|
@@ -102,16 +104,19 @@ def collect_chat_response_fields( | |
| if hasattr(res, "text"): | ||
| set_data_normalized( | ||
| span, | ||
| SPANDATA.AI_RESPONSES, | ||
| SPANDATA.GEN_AI_RESPONSE_TEXT, | ||
| [res.text], | ||
| ) | ||
| for pii_attr in COLLECTED_PII_CHAT_RESP_ATTRS: | ||
| if hasattr(res, pii_attr): | ||
| set_data_normalized(span, "ai." + pii_attr, getattr(res, pii_attr)) | ||
| for attr, spandata_key in COLLECTED_PII_CHAT_RESP_ATTRS.items(): | ||
| if hasattr(res, attr): | ||
| set_data_normalized(span, spandata_key, getattr(res, attr)) | ||
|
|
||
| for attr in COLLECTED_CHAT_RESP_ATTRS: | ||
| for attr, spandata_key in COLLECTED_CHAT_RESP_ATTRS.items(): | ||
| if hasattr(res, attr): | ||
| set_data_normalized(span, "ai." + attr, getattr(res, attr)) | ||
| value = getattr(res, attr) | ||
| if spandata_key == SPANDATA.GEN_AI_RESPONSE_FINISH_REASONS: | ||
| value = [value] | ||
| set_data_normalized(span, spandata_key, value) | ||
|
|
||
| if hasattr(res, "meta"): | ||
| if hasattr(res.meta, "billed_units"): | ||
|
|
@@ -127,9 +132,6 @@ def collect_chat_response_fields( | |
| output_tokens=res.meta.tokens.output_tokens, | ||
| ) | ||
|
|
||
| if hasattr(res.meta, "warnings"): | ||
| set_data_normalized(span, SPANDATA.AI_WARNINGS, res.meta.warnings) | ||
|
|
||
| @wraps(f) | ||
| def new_chat(*args: "Any", **kwargs: "Any") -> "Any": | ||
| integration = sentry_sdk.get_client().get_integration(CohereIntegration) | ||
|
|
@@ -142,13 +144,19 @@ def new_chat(*args: "Any", **kwargs: "Any") -> "Any": | |
| return f(*args, **kwargs) | ||
|
|
||
| message = kwargs.get("message") | ||
| model = kwargs.get("model", "") | ||
|
|
||
| span = sentry_sdk.start_span( | ||
| op=consts.OP.COHERE_CHAT_COMPLETIONS_CREATE, | ||
| name="cohere.client.Chat", | ||
| op=OP.GEN_AI_CHAT, | ||
| name=f"chat {model}".strip(), | ||
| origin=CohereIntegration.origin, | ||
| ) | ||
| span.__enter__() | ||
|
|
||
| with capture_internal_exceptions(): | ||
| span.set_data(SPANDATA.GEN_AI_SYSTEM, "cohere") | ||
| span.set_data(SPANDATA.GEN_AI_OPERATION_NAME, "chat") | ||
|
|
||
| try: | ||
| res = f(*args, **kwargs) | ||
| except Exception as e: | ||
|
|
@@ -160,19 +168,21 @@ def new_chat(*args: "Any", **kwargs: "Any") -> "Any": | |
|
|
||
| with capture_internal_exceptions(): | ||
| if should_send_default_pii() and integration.include_prompts: | ||
| messages = [] | ||
| for x in kwargs.get("chat_history", []): | ||
| role = getattr(x, "role", "") | ||
| messages.append( | ||
| { | ||
| "role": COHERE_ROLE_MAPPING.get(role, role), | ||
| "content": getattr(x, "message", ""), | ||
| } | ||
| ) | ||
| messages.append({"role": "user", "content": message}) | ||
| set_data_normalized( | ||
| span, | ||
| SPANDATA.AI_INPUT_MESSAGES, | ||
| list( | ||
| map( | ||
| lambda x: { | ||
| "role": getattr(x, "role", "").lower(), | ||
| "content": getattr(x, "message", ""), | ||
| }, | ||
| kwargs.get("chat_history", []), | ||
| ) | ||
| ) | ||
| + [{"role": "user", "content": message}], | ||
| SPANDATA.GEN_AI_REQUEST_MESSAGES, | ||
| messages, | ||
| unpack=False, | ||
| ) | ||
| for k, v in COLLECTED_PII_CHAT_PARAMS.items(): | ||
| if k in kwargs: | ||
|
|
@@ -181,7 +191,7 @@ def new_chat(*args: "Any", **kwargs: "Any") -> "Any": | |
| for k, v in COLLECTED_CHAT_PARAMS.items(): | ||
| if k in kwargs: | ||
| set_data_normalized(span, v, kwargs[k]) | ||
| set_data_normalized(span, SPANDATA.AI_STREAMING, False) | ||
| set_data_normalized(span, SPANDATA.GEN_AI_RESPONSE_STREAMING, streaming) | ||
|
|
||
| if streaming: | ||
| old_iterator = res | ||
|
|
@@ -226,27 +236,36 @@ def new_embed(*args: "Any", **kwargs: "Any") -> "Any": | |
| if integration is None: | ||
| return f(*args, **kwargs) | ||
|
|
||
| model = kwargs.get("model", "") | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. the documentation currently does not specify the AI Client Span's description when there is no request model. I'll bring this up in the sync, update the devdocs, and ping you once there's a concrete spec. https://develop.sentry.dev/sdk/telemetry/traces/modules/ai-agents/ |
||
|
|
||
| with sentry_sdk.start_span( | ||
| op=consts.OP.COHERE_EMBEDDINGS_CREATE, | ||
| name="Cohere Embedding Creation", | ||
| op=OP.GEN_AI_EMBEDDINGS, | ||
| name=f"embeddings {model}".strip(), | ||
| origin=CohereIntegration.origin, | ||
| ) as span: | ||
| span.set_data(SPANDATA.GEN_AI_SYSTEM, "cohere") | ||
| span.set_data(SPANDATA.GEN_AI_OPERATION_NAME, "embeddings") | ||
|
|
||
| if "texts" in kwargs and ( | ||
| should_send_default_pii() and integration.include_prompts | ||
| ): | ||
| if isinstance(kwargs["texts"], str): | ||
sentry[bot] marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| set_data_normalized(span, SPANDATA.AI_TEXTS, [kwargs["texts"]]) | ||
| set_data_normalized( | ||
| span, SPANDATA.GEN_AI_EMBEDDINGS_INPUT, [kwargs["texts"]] | ||
sentry[bot] marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| ) | ||
| elif ( | ||
| isinstance(kwargs["texts"], list) | ||
| and len(kwargs["texts"]) > 0 | ||
| and isinstance(kwargs["texts"][0], str) | ||
| ): | ||
| set_data_normalized( | ||
| span, SPANDATA.AI_INPUT_MESSAGES, kwargs["texts"] | ||
| span, SPANDATA.GEN_AI_EMBEDDINGS_INPUT, kwargs["texts"] | ||
| ) | ||
|
|
||
| if "model" in kwargs: | ||
| set_data_normalized(span, SPANDATA.AI_MODEL_ID, kwargs["model"]) | ||
| set_data_normalized( | ||
| span, SPANDATA.GEN_AI_REQUEST_MODEL, kwargs["model"] | ||
| ) | ||
| try: | ||
| res = f(*args, **kwargs) | ||
| except Exception as e: | ||
|
|
||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.