Skip to content

Commit

Permalink
VertexAI emit user, system, and assistant events (open-telemetry#3203)
Browse files Browse the repository at this point in the history
* VertexAI emit user events

* Emit system and assistant events

* Fix for python 3.8

* Record events regardless of span recording

* fix tests

* Apply suggestions from code review

Co-authored-by: Emídio Neto <9735060+emdneto@users.noreply.github.com>

---------

Co-authored-by: Emídio Neto <9735060+emdneto@users.noreply.github.com>
  • Loading branch information
2 people authored and aryabharat committed Feb 2, 2025
1 parent 496738d commit 4b6cf60
Show file tree
Hide file tree
Showing 8 changed files with 534 additions and 11 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -13,3 +13,5 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
([#3123](https://github.com/open-telemetry/opentelemetry-python-contrib/pull/3123))
- Add server attributes to Vertex AI spans
([#3208](https://github.com/open-telemetry/opentelemetry-python-contrib/pull/3208))
- VertexAI emit user, system, and assistant events
([#3203](https://github.com/open-telemetry/opentelemetry-python-contrib/pull/3203))
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
# 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.

"""
Factories for event types described in
https://github.com/open-telemetry/semantic-conventions/blob/main/docs/gen-ai/gen-ai-events.md#system-event.
Hopefully this code can be autogenerated by Weaver once Gen AI semantic conventions are
schematized in YAML and the Weaver tool supports it.
"""

from opentelemetry._events import Event
from opentelemetry.semconv._incubating.attributes import gen_ai_attributes
from opentelemetry.util.types import AnyValue


def user_event(
*,
role: str = "user",
content: AnyValue = None,
) -> Event:
"""Creates a User event
https://github.com/open-telemetry/semantic-conventions/blob/v1.28.0/docs/gen-ai/gen-ai-events.md#user-event
"""
body: dict[str, AnyValue] = {
"role": role,
}
if content is not None:
body["content"] = content
return Event(
name="gen_ai.user.message",
attributes={
gen_ai_attributes.GEN_AI_SYSTEM: gen_ai_attributes.GenAiSystemValues.VERTEX_AI.value,
},
body=body,
)


def assistant_event(
*,
role: str = "assistant",
content: AnyValue = None,
) -> Event:
"""Creates an Assistant event
https://github.com/open-telemetry/semantic-conventions/blob/v1.28.0/docs/gen-ai/gen-ai-events.md#assistant-event
"""
body: dict[str, AnyValue] = {
"role": role,
}
if content is not None:
body["content"] = content
return Event(
name="gen_ai.assistant.message",
attributes={
gen_ai_attributes.GEN_AI_SYSTEM: gen_ai_attributes.GenAiSystemValues.VERTEX_AI.value,
},
body=body,
)


def system_event(
*,
role: str = "system",
content: AnyValue = None,
) -> Event:
"""Creates a System event
https://github.com/open-telemetry/semantic-conventions/blob/v1.28.0/docs/gen-ai/gen-ai-events.md#system-event
"""
body: dict[str, AnyValue] = {
"role": role,
}
if content is not None:
body["content"] = content
return Event(
name="gen_ai.system.message",
attributes={
gen_ai_attributes.GEN_AI_SYSTEM: gen_ai_attributes.GenAiSystemValues.VERTEX_AI.value,
},
body=body,
)
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@
get_genai_request_attributes,
get_server_attributes,
get_span_name,
request_to_events,
)
from opentelemetry.trace import SpanKind, Tracer

Expand Down Expand Up @@ -113,12 +114,10 @@ def traced_method(
kind=SpanKind.CLIENT,
attributes=span_attributes,
) as _span:
# TODO: emit request events
# if span.is_recording():
# for message in kwargs.get("messages", []):
# event_logger.emit(
# message_to_event(message, capture_content)
# )
for event in request_to_events(
params=params, capture_content=capture_content
):
event_logger.emit(event)

# TODO: set error.type attribute
# https://github.com/open-telemetry/semantic-conventions/blob/main/docs/gen-ai/gen-ai-spans.md
Expand All @@ -130,10 +129,9 @@ def traced_method(
# )

# TODO: add response attributes and events
# if span.is_recording():
# _set_response_attributes(
# span, result, event_logger, capture_content
# )
# _set_response_attributes(
# span, result, event_logger, capture_content
# )
return result

return traced_method
Original file line number Diff line number Diff line change
Expand Up @@ -19,16 +19,24 @@
from os import environ
from typing import (
TYPE_CHECKING,
Iterable,
Mapping,
Sequence,
cast,
)
from urllib.parse import urlparse

from opentelemetry._events import Event
from opentelemetry.instrumentation.vertexai.events import (
assistant_event,
system_event,
user_event,
)
from opentelemetry.semconv._incubating.attributes import (
gen_ai_attributes as GenAIAttributes,
)
from opentelemetry.semconv.attributes import server_attributes
from opentelemetry.util.types import AttributeValue
from opentelemetry.util.types import AnyValue, AttributeValue

if TYPE_CHECKING:
from google.cloud.aiplatform_v1.types import content, tool
Expand Down Expand Up @@ -157,3 +165,46 @@ def get_span_name(span_attributes: Mapping[str, AttributeValue]) -> str:
if not model:
return f"{name}"
return f"{name} {model}"


def request_to_events(
*, params: GenerateContentParams, capture_content: bool
) -> Iterable[Event]:
# System message
if params.system_instruction:
request_content = _parts_to_any_value(
capture_content=capture_content,
parts=params.system_instruction.parts,
)
yield system_event(
role=params.system_instruction.role, content=request_content
)

for content in params.contents or []:
# Assistant message
if content.role == "model":
request_content = _parts_to_any_value(
capture_content=capture_content, parts=content.parts
)

yield assistant_event(role=content.role, content=request_content)
# Assume user event but role should be "user"
else:
request_content = _parts_to_any_value(
capture_content=capture_content, parts=content.parts
)
yield user_event(role=content.role, content=request_content)


def _parts_to_any_value(
*,
capture_content: bool,
parts: Sequence[content.Part] | Sequence[content_v1beta1.Part],
) -> list[dict[str, AnyValue]] | None:
if not capture_content:
return None

return [
cast("dict[str, AnyValue]", type(part).to_dict(part)) # type: ignore[reportUnknownMemberType]
for part in parts
]
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
interactions:
- request:
body: |-
{
"contents": [
{
"role": "user",
"parts": [
{
"text": "My name is OpenTelemetry"
}
]
},
{
"role": "model",
"parts": [
{
"text": "Hello OpenTelemetry!"
}
]
},
{
"role": "user",
"parts": [
{
"text": "Address me by name and say this is a test"
}
]
}
],
"systemInstruction": {
"role": "user",
"parts": [
{
"text": "You are a clever language model"
}
]
}
}
headers:
Accept:
- '*/*'
Accept-Encoding:
- gzip, deflate
Connection:
- keep-alive
Content-Length:
- '548'
Content-Type:
- application/json
User-Agent:
- python-requests/2.32.3
method: POST
uri: https://us-central1-aiplatform.googleapis.com/v1/projects/fake-project/locations/us-central1/publishers/google/models/gemini-1.5-flash-002:generateContent?%24alt=json%3Benum-encoding%3Dint
response:
body:
string: |-
{
"candidates": [
{
"content": {
"role": "model",
"parts": [
{
"text": "OpenTelemetry, this is a test.\n"
}
]
},
"finishReason": 1,
"avgLogprobs": -1.1655389850299496e-06
}
],
"usageMetadata": {
"promptTokenCount": 25,
"candidatesTokenCount": 9,
"totalTokenCount": 34
},
"modelVersion": "gemini-1.5-flash-002"
}
headers:
Content-Type:
- application/json; charset=UTF-8
Transfer-Encoding:
- chunked
Vary:
- Origin
- X-Origin
- Referer
content-length:
- '422'
status:
code: 200
message: OK
version: 1
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
interactions:
- request:
body: |-
{
"contents": [
{
"role": "invalid_role",
"parts": [
{
"text": "Say this is a test"
}
]
}
]
}
headers:
Accept:
- '*/*'
Accept-Encoding:
- gzip, deflate
Connection:
- keep-alive
Content-Length:
- '149'
Content-Type:
- application/json
User-Agent:
- python-requests/2.32.3
method: POST
uri: https://us-central1-aiplatform.googleapis.com/v1/projects/fake-project/locations/us-central1/publishers/google/models/gemini-1.5-flash-002:generateContent?%24alt=json%3Benum-encoding%3Dint
response:
body:
string: |-
{
"error": {
"code": 400,
"message": "Please use a valid role: user, model.",
"status": "INVALID_ARGUMENT",
"details": []
}
}
headers:
Content-Type:
- application/json; charset=UTF-8
Transfer-Encoding:
- chunked
Vary:
- Origin
- X-Origin
- Referer
content-length:
- '416'
status:
code: 400
message: Bad Request
version: 1
Loading

0 comments on commit 4b6cf60

Please sign in to comment.