-
Notifications
You must be signed in to change notification settings - Fork 931
Genai utils | Add AgentInvocation type #4274
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
etserend
wants to merge
17
commits into
open-telemetry:main
Choose a base branch
from
etserend:genai-utils/agent-invocation
base: main
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.
Open
Changes from all commits
Commits
Show all changes
17 commits
Select commit
Hold shift + click to select a range
843124d
GenAI Utils | Agent Base Type and Creation Span
etserend da8232d
fix lint and add _BaseAgent to sphinx nitpick exceptions
etserend f849547
align AgentInvocation with invoke_agent semconv
etserend c6e9822
update span utils
etserend d28860a
apply _lifecycle_context and error handling
etserend c320ca6
apply general invoke methods and resolved merge conflict
etserend 650c3fd
clean up
etserend f1ded70
Merge remote-tracking branch 'upstream/main' into genai-utils/agent-i…
etserend be88d1a
Merge upstream/main into genai-utils/agent-invocation
etserend e851e74
fix(genai-utils): address review comments on AgentInvocation
etserend 9670da7
Merge remote-tracking branch 'upstream/main' into genai-utils/agent-i…
etserend ebc2699
fix(genai-utils): align AgentInvocation with invoke_agent semconv spec
etserend 27dcb43
chore: remove utils-demo app from PR
etserend 928069a
fix(genai-utils): address review comments on AgentInvocation
etserend fd08416
Merge remote-tracking branch 'upstream/main' into genai-utils/agent-i…
etserend a7c6e63
fix(genai-utils): move get_content_attributes to _invocation.py, add …
etserend c655e25
Merge remote-tracking branch 'upstream/main' into genai-utils/agent-i…
etserend 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
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
218 changes: 218 additions & 0 deletions
218
util/opentelemetry-util-genai/src/opentelemetry/util/genai/_agent_invocation.py
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 |
|---|---|---|
| @@ -0,0 +1,218 @@ | ||
| # Copyright The OpenTelemetry Authors | ||
| # | ||
| # 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. | ||
|
|
||
| from __future__ import annotations | ||
|
|
||
| from typing import Any | ||
|
|
||
| from opentelemetry._logs import Logger | ||
| from opentelemetry.semconv._incubating.attributes import ( | ||
| gen_ai_attributes as GenAI, | ||
| ) | ||
| from opentelemetry.semconv.attributes import server_attributes | ||
| from opentelemetry.trace import SpanKind, Tracer | ||
| from opentelemetry.util.genai._invocation import ( | ||
| Error, | ||
| GenAIInvocation, | ||
| get_content_attributes, | ||
| ) | ||
| from opentelemetry.util.genai.metrics import InvocationMetricsRecorder | ||
| from opentelemetry.util.genai.types import ( | ||
| InputMessage, | ||
| MessagePart, | ||
| OutputMessage, | ||
| ToolDefinition, | ||
| ) | ||
|
|
||
| _GEN_AI_USAGE_CACHE_CREATION_INPUT_TOKENS: str = getattr( | ||
| GenAI, | ||
| "GEN_AI_USAGE_CACHE_CREATION_INPUT_TOKENS", | ||
| "gen_ai.usage.cache_creation.input_tokens", | ||
| ) | ||
| _GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS: str = getattr( | ||
| GenAI, | ||
| "GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS", | ||
| "gen_ai.usage.cache_read.input_tokens", | ||
| ) | ||
|
|
||
|
|
||
| class AgentInvocation(GenAIInvocation): | ||
| """Represents a single agent invocation (invoke_agent span). | ||
|
|
||
| Use handler.start_invoke_local_agent() / handler.start_invoke_remote_agent() | ||
| or the handler.invoke_local_agent() / handler.invoke_remote_agent() context | ||
| managers rather than constructing this directly. | ||
|
|
||
| Reference: | ||
| Client span: https://github.com/open-telemetry/semantic-conventions/blob/main/docs/gen-ai/gen-ai-agent-spans.md#invoke-agent-client-span | ||
| Internal span: https://github.com/open-telemetry/semantic-conventions/blob/main/docs/gen-ai/gen-ai-agent-spans.md#invoke-agent-internal-span | ||
| """ | ||
|
|
||
| def __init__( | ||
| self, | ||
| tracer: Tracer, | ||
| metrics_recorder: InvocationMetricsRecorder, | ||
| logger: Logger, | ||
| provider: str, | ||
| *, | ||
| span_kind: SpanKind = SpanKind.INTERNAL, | ||
| request_model: str | None = None, | ||
| server_address: str | None = None, | ||
| server_port: int | None = None, | ||
| attributes: dict[str, Any] | None = None, | ||
| metric_attributes: dict[str, Any] | None = None, | ||
| ) -> None: | ||
| """Use handler.start_invoke_local_agent() or handler.start_invoke_remote_agent() instead of calling this directly.""" | ||
| _operation_name = GenAI.GenAiOperationNameValues.INVOKE_AGENT.value | ||
| super().__init__( | ||
| tracer, | ||
| metrics_recorder, | ||
| logger, | ||
| operation_name=_operation_name, | ||
| span_name=_operation_name, | ||
| span_kind=span_kind, | ||
| attributes=attributes, | ||
| metric_attributes=metric_attributes, | ||
| ) | ||
| self.provider = provider | ||
| self.request_model = request_model | ||
| self.server_address = server_address | ||
| self.server_port = server_port | ||
|
|
||
| self.agent_name: str | None = None | ||
| self.agent_id: str | None = None | ||
| self.agent_description: str | None = None | ||
| self.agent_version: str | None = None | ||
|
|
||
| self.conversation_id: str | None = None | ||
| self.data_source_id: str | None = None | ||
| self.output_type: str | None = None | ||
|
|
||
| self.temperature: float | None = None | ||
| self.top_p: float | None = None | ||
| self.frequency_penalty: float | None = None | ||
| self.presence_penalty: float | None = None | ||
| self.max_tokens: int | None = None | ||
| self.stop_sequences: list[str] | None = None | ||
| self.seed: int | None = None | ||
| self.choice_count: int | None = None | ||
|
|
||
| self.input_tokens: int | None = None | ||
| self.output_tokens: int | None = None | ||
| self.cache_creation_input_tokens: int | None = None | ||
| self.cache_read_input_tokens: int | None = None | ||
|
|
||
| self.input_messages: list[InputMessage] = [] | ||
| self.output_messages: list[OutputMessage] = [] | ||
| self.system_instruction: list[MessagePart] = [] | ||
| self.tool_definitions: list[ToolDefinition] | None = None | ||
|
|
||
| self._start() | ||
|
|
||
| def _get_common_attributes(self) -> dict[str, Any]: | ||
| optional_attrs = ( | ||
| (GenAI.GEN_AI_REQUEST_MODEL, self.request_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. question(blocking): We have these two attributes |
||
| (server_attributes.SERVER_ADDRESS, self.server_address), | ||
| (server_attributes.SERVER_PORT, self.server_port), | ||
| (GenAI.GEN_AI_AGENT_NAME, self.agent_name), | ||
| (GenAI.GEN_AI_AGENT_ID, self.agent_id), | ||
| (GenAI.GEN_AI_AGENT_DESCRIPTION, self.agent_description), | ||
| (GenAI.GEN_AI_AGENT_VERSION, self.agent_version), | ||
| ) | ||
| return { | ||
| GenAI.GEN_AI_OPERATION_NAME: self._operation_name, | ||
| GenAI.GEN_AI_PROVIDER_NAME: self.provider, | ||
| **{k: v for k, v in optional_attrs if v is not None}, | ||
| } | ||
|
|
||
| def _get_request_attributes(self) -> dict[str, Any]: | ||
| optional_attrs = ( | ||
| (GenAI.GEN_AI_CONVERSATION_ID, self.conversation_id), | ||
| (GenAI.GEN_AI_DATA_SOURCE_ID, self.data_source_id), | ||
| (GenAI.GEN_AI_OUTPUT_TYPE, self.output_type), | ||
| (GenAI.GEN_AI_REQUEST_TEMPERATURE, self.temperature), | ||
| (GenAI.GEN_AI_REQUEST_TOP_P, self.top_p), | ||
| (GenAI.GEN_AI_REQUEST_FREQUENCY_PENALTY, self.frequency_penalty), | ||
| (GenAI.GEN_AI_REQUEST_PRESENCE_PENALTY, self.presence_penalty), | ||
| (GenAI.GEN_AI_REQUEST_MAX_TOKENS, self.max_tokens), | ||
| (GenAI.GEN_AI_REQUEST_STOP_SEQUENCES, self.stop_sequences), | ||
| (GenAI.GEN_AI_REQUEST_SEED, self.seed), | ||
| (GenAI.GEN_AI_REQUEST_CHOICE_COUNT, self.choice_count), | ||
| ) | ||
| return {k: v for k, v in optional_attrs if v is not None} | ||
|
|
||
| def _get_usage_attributes(self) -> dict[str, Any]: | ||
| optional_attrs = ( | ||
| (GenAI.GEN_AI_USAGE_INPUT_TOKENS, self.input_tokens), | ||
| (GenAI.GEN_AI_USAGE_OUTPUT_TOKENS, self.output_tokens), | ||
| ( | ||
| _GEN_AI_USAGE_CACHE_CREATION_INPUT_TOKENS, | ||
| self.cache_creation_input_tokens, | ||
| ), | ||
| ( | ||
| _GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS, | ||
| self.cache_read_input_tokens, | ||
| ), | ||
| ) | ||
| return {k: v for k, v in optional_attrs if v is not None} | ||
|
|
||
| def _get_content_attributes_for_span(self) -> dict[str, Any]: | ||
| return get_content_attributes( | ||
| input_messages=self.input_messages, | ||
| output_messages=self.output_messages, | ||
| system_instruction=self.system_instruction, | ||
| tool_definitions=self.tool_definitions, | ||
| for_span=True, | ||
| ) | ||
|
|
||
| def _get_metric_attributes(self) -> dict[str, Any]: | ||
| optional_attrs = ( | ||
| (GenAI.GEN_AI_PROVIDER_NAME, self.provider), | ||
| (GenAI.GEN_AI_REQUEST_MODEL, self.request_model), | ||
| (server_attributes.SERVER_ADDRESS, self.server_address), | ||
| (server_attributes.SERVER_PORT, self.server_port), | ||
| ) | ||
| attrs: dict[str, Any] = { | ||
| GenAI.GEN_AI_OPERATION_NAME: self._operation_name, | ||
| **{k: v for k, v in optional_attrs if v is not None}, | ||
| } | ||
| attrs.update(self.metric_attributes) | ||
| return attrs | ||
|
|
||
| def _get_metric_token_counts(self) -> dict[str, int]: | ||
| counts: dict[str, int] = {} | ||
| if self.input_tokens is not None: | ||
| counts[GenAI.GenAiTokenTypeValues.INPUT.value] = self.input_tokens | ||
| if self.output_tokens is not None: | ||
| counts[GenAI.GenAiTokenTypeValues.OUTPUT.value] = ( | ||
| self.output_tokens | ||
| ) | ||
| return counts | ||
|
|
||
| def _apply_finish(self, error: Error | None = None) -> None: | ||
| if error is not None: | ||
| self._apply_error_attributes(error) | ||
|
|
||
| # Update span name if agent_name was set after construction | ||
| if self.agent_name: | ||
| self.span.update_name(f"{self._operation_name} {self.agent_name}") | ||
|
|
||
| attributes: dict[str, Any] = {} | ||
| attributes.update(self._get_common_attributes()) | ||
| attributes.update(self._get_request_attributes()) | ||
| attributes.update(self._get_usage_attributes()) | ||
| attributes.update(self._get_content_attributes_for_span()) | ||
| attributes.update(self.attributes) | ||
| self.span.set_attributes(attributes) | ||
| self._metrics_recorder.record(self) | ||
|
etserend marked this conversation as resolved.
|
||
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.
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.