Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
39 changes: 39 additions & 0 deletions packages/genkit-google-genai/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -240,6 +240,45 @@ config = GeminiTtsConfig(
)
```

### Search grounding and candidate metadata

Gemini attaches per-candidate metadata (search sources, citations, URL context,
logprobs, safety ratings) to the reply. Genkit keeps it on `response.custom`
under the wire names: `custom['candidates'][i]` holds `groundingMetadata`,
`urlContextMetadata`, `citationMetadata`, `logprobsResult`, `safetyRatings`,
`avgLogprobs`, `finishMessage` and `tokenCount` for candidate `i`, and
`custom['promptFeedback']` explains a blocked prompt. `custom` is `{}` when
Gemini sent neither. Streamed replies merge the chunks' metadata into the same
shape.

```python
from genkit import Genkit
from genkit_google_genai import GeminiConfig, GoogleAI

# 1. Initialize Genkit with GoogleAI
ai = Genkit(plugins=[GoogleAI()], model=GoogleAI.gemini('gemini-flash-latest'))


async def main() -> None:
# 2. Ground the answer in Google Search
response = await ai.generate(
prompt='Which Chicago restaurants earned a new Michelin star this year?',
config=GeminiConfig(google_search=True),
)
print(response.text)
# => Two Chicago restaurants earned their first star this year: ...

# 3. List the pages Gemini grounded the answer in
candidates = (response.custom or {}).get('candidates') or [{}]
for chunk in candidates[0].get('groundingMetadata', {}).get('groundingChunks', []):
print(chunk['web']['uri'])
# => https://guide.michelin.com/us/en/illinois/chicago/restaurants


if __name__ == '__main__':
ai.run_main(main())
```

### Provider fields the plugin doesn't declare

Gemini, Gemini image, and Veo configs reject keys they don't declare, so a
Expand Down
19 changes: 12 additions & 7 deletions packages/genkit-google-genai/src/genkit_google_genai/_google.py
Original file line number Diff line number Diff line change
Expand Up @@ -159,6 +159,9 @@
)
from genkit_google_genai._models._sdk_config import (
check_timeout_seconds,
check_vertex_project,
is_missing_vertex_project,
missing_vertex_project_error,
request_client_kwargs,
timeout_seconds_to_ms,
)
Expand Down Expand Up @@ -297,10 +300,17 @@ def _plugin_client(client_kwargs: dict[str, Any]) -> genai.Client:
no project resolves ADC here; a missing or rejected credential becomes
UNAUTHENTICATED instead of a bare google.auth error.
"""
check_vertex_project(client_kwargs)
try:
return genai.client.Client(**client_kwargs)
except GOOGLE_AUTH_ERRORS as e:
raise_auth_error(e)
except ValueError as e:
# Vertex AI with no project, API key or ADC project: google-genai
# raises a bare ValueError naming its own arguments.
if is_missing_vertex_project(client_kwargs, e):
raise missing_vertex_project_error(e) from e
raise


def _call_client(plugin: GoogleAI | VertexAI, context: dict[str, Any] | None) -> genai.Client:
Expand Down Expand Up @@ -1241,7 +1251,8 @@ def __init__(
# base_url set the SDK skips its own ADC lookup, evaluator registration
# needs a concrete project, and doing it now keeps the blocking ADC IO
# off the event loop. Express mode (api_key) needs no project, so it
# only pays for the probe where a multi-region demands one.
# only pays for the probe where a multi-region demands one. A project
# still missing fails at call time in _plugin_client.
if not self._project and (api_key is None or multi_region):
if credentials is not None:
self._project = getattr(credentials, 'project_id', None)
Expand All @@ -1251,12 +1262,6 @@ def __init__(
except DefaultCredentialsError:
self._project = None

if multi_region and not self._project:
raise ValueError(
'VertexAI plugin requires a project when using a multi-region location. '
'Set the project parameter or GOOGLE_CLOUD_PROJECT environment variable.'
)

self._client_kwargs: dict[str, Any] = {
'vertexai': self._vertexai,
'api_key': api_key,
Expand Down
Loading
Loading