Skip to content

feat: Add support for per-request metadata/headers in GenerativeModel.generate_content. #709

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
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
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
19 changes: 19 additions & 0 deletions google/generativeai/generative_models.py
Original file line number Diff line number Diff line change
Expand Up @@ -244,6 +244,7 @@ def generate_content(
tools: content_types.FunctionLibraryType | None = None,
tool_config: content_types.ToolConfigType | None = None,
request_options: helper_types.RequestOptionsType | None = None,
extra_headers: dict[str, str] | None = None,
) -> generation_types.GenerateContentResponse:
"""A multipurpose function to generate responses from the model.

Expand Down Expand Up @@ -319,6 +320,14 @@ def generate_content(
if request_options is None:
request_options = {}

# Convert `extra_headers` to metadata format
if extra_headers:
metadata = [(k, v) for k, v in extra_headers.items()]
if "metadata" in request_options:
request_options["metadata"].extend(metadata)
else:
request_options["metadata"] = metadata

try:
if stream:
with generation_types.rewrite_stream_error():
Expand Down Expand Up @@ -351,6 +360,7 @@ async def generate_content_async(
tools: content_types.FunctionLibraryType | None = None,
tool_config: content_types.ToolConfigType | None = None,
request_options: helper_types.RequestOptionsType | None = None,
extra_headers: dict[str, str] | None = None,
) -> generation_types.AsyncGenerateContentResponse:
"""The async version of `GenerativeModel.generate_content`."""
if not contents:
Expand All @@ -373,6 +383,15 @@ async def generate_content_async(
if request_options is None:
request_options = {}

# Convert extra_headers to metadata format if provided
metadata = []
if extra_headers:
metadata = [(k, v) for k, v in extra_headers.items()]

# Add metadata to request_options
if metadata:
request_options["metadata"] = metadata

try:
if stream:
with generation_types.rewrite_stream_error():
Expand Down
12 changes: 12 additions & 0 deletions tests/test_generative_models.py
Original file line number Diff line number Diff line change
Expand Up @@ -48,20 +48,32 @@ def __init__(self, test):
def generate_content(
self,
request: protos.GenerateContentRequest,
*,
extra_headers: dict[str, str] | None = None,
**kwargs,
) -> protos.GenerateContentResponse:
self.test.assertIsInstance(request, protos.GenerateContentRequest)
self.observed_requests.append(request)
# Convert extra_headers to metadata format and ensure it's in kwargs
if extra_headers:
metadata = [(k, v) for k, v in extra_headers.items()]
kwargs.setdefault("metadata", []).extend(metadata)
self.observed_kwargs.append(kwargs)
response = self.responses["generate_content"].pop(0)
return response

def stream_generate_content(
self,
request: protos.GetModelRequest,
*,
extra_headers: dict[str, str] | None = None,
**kwargs,
) -> Iterable[protos.GenerateContentResponse]:
self.observed_requests.append(request)
# Convert extra_headers to metadata format and ensure it's in kwargs
if extra_headers:
metadata = [(k, v) for k, v in extra_headers.items()]
kwargs.setdefault("metadata", []).extend(metadata)
self.observed_kwargs.append(kwargs)
response = self.responses["stream_generate_content"].pop(0)
return response
Expand Down
16 changes: 16 additions & 0 deletions tests/test_generative_models_async.py
Original file line number Diff line number Diff line change
Expand Up @@ -53,19 +53,35 @@ def add_client_method(f):
@add_client_method
async def generate_content(
request: protos.GenerateContentRequest,
*,
extra_headers: dict[str, str] | None = None,
**kwargs,
) -> protos.GenerateContentResponse:
self.assertIsInstance(request, protos.GenerateContentRequest)
self.observed_requests.append(request)

if extra_headers:
metadata = [(k, v) for k, v in extra_headers.items()]
kwargs.setdefault("metadata", []).extend(metadata) # Merge with existing metadata if any

self.observed_kwargs.append(kwargs)
response = self.responses["generate_content"].pop(0)
return response

@add_client_method
async def stream_generate_content(
request: protos.GetModelRequest,
*,
extra_headers: dict[str, str] | None = None,
**kwargs,
) -> Iterable[protos.GenerateContentResponse]:
self.observed_requests.append(request)
# Convert extra_headers to metadata format and ensure it's in kwargs
if extra_headers:
metadata = [(k, v) for k, v in extra_headers.items()]
kwargs.setdefault("metadata", []).extend(metadata)

self.observed_kwargs.append(kwargs)
response = self.responses["stream_generate_content"].pop(0)
return response

Expand Down