Skip to content

Commit 1b48349

Browse files
authored
instrument_google_genai docs (#1411)
1 parent 91c67b9 commit 1b48349

File tree

11 files changed

+89
-11
lines changed

11 files changed

+89
-11
lines changed

docs/guides/web-ui/llm-panels.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -45,6 +45,7 @@ Click an LLM span to open the details panel.
4545
|---------------------------------------------------------------------------------------|--------------|-------|-------------------|
4646
| [Pydantic AI](../../integrations/llms/pydanticai.md) ||||
4747
| [OpenAI](../../integrations/llms/openai.md) ||||
48+
| [Google Gen AI](../../integrations/llms/google-genai.md) ||||
4849
| [LangChain](../../integrations/llms/langchain.md) ||||
4950
| [Anthropic](../../integrations/llms/anthropic.md) | | ||
5051
| [Google ADK](https://github.com/pydantic/logfire/issues/1201#issuecomment-3012423974) || | |
63.4 KB
Loading
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
---
2+
integration: logfire
3+
---
4+
# Google Gen AI SDK
5+
6+
**Logfire** supports instrumenting calls to the [Google Gen AI SDK (`google-genai`)](https://googleapis.github.io/python-genai/) with the [`logfire.instrument_google_genai()`][logfire.Logfire.instrument_google_genai] method, for example:
7+
8+
```python
9+
import os
10+
11+
from google.genai import Client
12+
13+
import logfire
14+
15+
# This is required for prompts and completions to be captured in the spans
16+
os.environ['OTEL_INSTRUMENTATION_GENAI_CAPTURE_MESSAGE_CONTENT'] = 'true'
17+
18+
logfire.configure()
19+
logfire.instrument_google_genai()
20+
21+
client = Client()
22+
response = client.models.generate_content(model='gemini-2.5-flash', contents=['Hi'])
23+
print(response.text)
24+
# Hello! How can I help you today?
25+
```
26+
27+
This creates a span which shows the conversation in the Logfire UI:
28+
29+
<figure markdown="span">
30+
![Logfire Google Gen AI conversation](../../images/logfire-screenshot-google-genai-llm-panel.png){ width="259" }
31+
</figure>
32+
33+
!!! note
34+
If you don't set the environment variable `OTEL_INSTRUMENTATION_GENAI_CAPTURE_MESSAGE_CONTENT`
35+
to `true`, the spans will simply contain `<elided>` where the prompts and completions would be.
36+
37+
[`logfire.instrument_google_genai()`][logfire.Logfire.instrument_google_genai] uses the `GoogleGenAiSdkInstrumentor().instrument()` method of the [`opentelemetry-instrumentation-google-genai`](https://pypi.org/project/opentelemetry-instrumentation-google-genai/) package.

logfire/_internal/integrations/fastapi.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,7 @@
3030
from .asgi import tweak_asgi_spans_tracer_provider
3131
except ImportError:
3232
raise RuntimeError(
33-
'The `logfire.instrument_fastapi()` requires the `opentelemetry-instrumentation-fastapi` package.\n'
33+
'The `logfire.instrument_fastapi()` method requires the `opentelemetry-instrumentation-fastapi` package.\n'
3434
'You can install this with:\n'
3535
" pip install 'logfire[fastapi]'"
3636
)

logfire/_internal/integrations/google_genai.py

Lines changed: 17 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -5,13 +5,22 @@
55
from typing import Any
66

77
from opentelemetry._events import Event, EventLogger, EventLoggerProvider
8-
from opentelemetry.instrumentation.google_genai import GoogleGenAiSdkInstrumentor
98
from opentelemetry.trace import get_current_span
109
from typing_extensions import TypeAlias
1110

1211
import logfire
1312
from logfire._internal.utils import handle_internal_errors, safe_repr
1413

14+
try:
15+
from opentelemetry.instrumentation.google_genai import GoogleGenAiSdkInstrumentor
16+
except ImportError:
17+
raise RuntimeError(
18+
'The `logfire.instrument_google_genai()` method '
19+
'requires the `opentelemetry-instrumentation-google-genai` package.\n'
20+
'You can install this with:\n'
21+
" pip install 'logfire[google-genai]'"
22+
)
23+
1524
try:
1625
from opentelemetry.instrumentation.google_genai import dict_util
1726

@@ -67,9 +76,12 @@ def get_event_logger(self, *args: Any, **kwargs: Any) -> SpanEventLogger:
6776
return SpanEventLogger(*args, **kwargs)
6877

6978

70-
def instrument_google_genai(logfire_instance: logfire.Logfire):
79+
def instrument_google_genai(logfire_instance: logfire.Logfire, **kwargs: Any):
7180
GoogleGenAiSdkInstrumentor().instrument(
72-
event_logger_provider=SpanEventLoggerProvider(),
73-
tracer_provider=logfire_instance.config.get_tracer_provider(),
74-
meter_provider=logfire_instance.config.get_meter_provider(),
81+
**{
82+
'event_logger_provider': SpanEventLoggerProvider(),
83+
'tracer_provider': logfire_instance.config.get_tracer_provider(),
84+
'meter_provider': logfire_instance.config.get_meter_provider(),
85+
**kwargs,
86+
}
7587
)

logfire/_internal/main.py

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1280,11 +1280,21 @@ def instrument_anthropic(
12801280
is_async_client,
12811281
)
12821282

1283-
def instrument_google_genai(self):
1283+
def instrument_google_genai(self, **kwargs: Any):
1284+
"""Instrument the [Google Gen AI SDK (`google-genai`)](https://googleapis.github.io/python-genai/).
1285+
1286+
!!! note
1287+
To capture message contents (i.e. prompts and completions), set the environment variable
1288+
`OTEL_INSTRUMENTATION_GENAI_CAPTURE_MESSAGE_CONTENT` to `true`.
1289+
1290+
Uses the `GoogleGenAiSdkInstrumentor().instrument()` method of the
1291+
[`opentelemetry-instrumentation-google-genai`](https://pypi.org/project/opentelemetry-instrumentation-google-genai/)
1292+
package, to which it passes `**kwargs`.
1293+
"""
12841294
from .integrations.google_genai import instrument_google_genai
12851295

12861296
self._warn_if_not_initialized_for_instrumentation()
1287-
instrument_google_genai(self)
1297+
instrument_google_genai(self, **kwargs)
12881298

12891299
def instrument_litellm(self, **kwargs: Any):
12901300
from .integrations.litellm import instrument_litellm

mkdocs.yml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -114,6 +114,7 @@ nav:
114114
- LLMs:
115115
- Pydantic AI: integrations/llms/pydanticai.md
116116
- OpenAI: integrations/llms/openai.md
117+
- Google Gen AI: integrations/llms/google-genai.md
117118
- Anthropic: integrations/llms/anthropic.md
118119
- LangChain: integrations/llms/langchain.md
119120
- LLamaIndex: integrations/llms/llamaindex.md

pyproject.toml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -78,6 +78,7 @@ requests = ["opentelemetry-instrumentation-requests >= 0.42b0"]
7878
mysql = ["opentelemetry-instrumentation-mysql >= 0.42b0"]
7979
sqlite3 = ["opentelemetry-instrumentation-sqlite3 >= 0.42b0"]
8080
aws-lambda = ["opentelemetry-instrumentation-aws-lambda >= 0.42b0"]
81+
google-genai = ["opentelemetry-instrumentation-google-genai >= 0"]
8182

8283
[project.urls]
8384
Homepage = "https://logfire.pydantic.dev/"

tests/otel_integrations/test_fastapi.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,7 @@ def test_missing_opentelemetry_dependency() -> None:
3232
with pytest.raises(RuntimeError) as exc_info:
3333
importlib.reload(logfire._internal.integrations.fastapi)
3434
assert str(exc_info.value) == snapshot("""\
35-
The `logfire.instrument_fastapi()` requires the `opentelemetry-instrumentation-fastapi` package.
35+
The `logfire.instrument_fastapi()` method requires the `opentelemetry-instrumentation-fastapi` package.
3636
You can install this with:
3737
pip install 'logfire[fastapi]'\
3838
""")

tests/otel_integrations/test_google_genai.py

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import os
22
import sys
33
import warnings
4+
from unittest import mock
45
from unittest.mock import patch
56

67
import pydantic
@@ -25,6 +26,17 @@
2526
]
2627

2728

29+
def test_missing_opentelemetry_dependency() -> None:
30+
with mock.patch.dict('sys.modules', {'opentelemetry.instrumentation.google_genai': None}):
31+
with pytest.raises(RuntimeError) as exc_info:
32+
logfire.instrument_google_genai()
33+
assert str(exc_info.value) == snapshot("""\
34+
The `logfire.instrument_google_genai()` method requires the `opentelemetry-instrumentation-google-genai` package.
35+
You can install this with:
36+
pip install 'logfire[google-genai]'\
37+
""")
38+
39+
2840
@pytest.mark.vcr()
2941
def test_instrument_google_genai(exporter: TestExporter) -> None:
3042
from google.genai import Client, types

0 commit comments

Comments
 (0)