Skip to content

Add support for structured output to VertexAI class #701

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

Closed
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 libs/vertexai/langchain_google_vertexai/llms.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,9 @@
GenerativeModel,
Image,
)
from vertexai.generative_models._generative_models import ( # type: ignore[import-untyped]
_convert_schema_dict_to_gapic,
)
from vertexai.language_models import ( # type: ignore[import-untyped]
CodeGenerationModel,
TextGenerationModel,
Expand Down Expand Up @@ -115,6 +118,21 @@ class VertexAI(_VertexAICommon, BaseLLM):
model_name will be used to determine the model family
"""

response_mime_type: Optional[str] = None
"""Optional. Output response mimetype of the generated candidate text. Only
supported in Gemini 1.5 and later models. Supported mimetype:
* "text/plain": (default) Text output.
* "application/json": JSON response in the candidates.
* "text/x.enum": Enum in plain text.
The model also needs to be prompted to output the appropriate response
type, otherwise the behavior is undefined. This is a preview feature.
"""

response_schema: Optional[Dict[str, Any]] = None
""" Optional. Enforce an schema to the output.
The format of the dictionary should follow Open API schema.
"""

def __init__(self, *, model_name: Optional[str] = None, **kwargs: Any) -> None:
"""Needed for mypy typing to recognize model_name as a valid arg."""
if model_name:
Expand Down Expand Up @@ -191,6 +209,27 @@ def validate_environment(self) -> Self:
raise ValueError("Only one candidate can be generated with streaming!")
return self

@property
def _default_params(self) -> Dict[str, Any]:
updated_params = super()._default_params

if self.response_mime_type is not None:
updated_params["response_mime_type"] = self.response_mime_type

if self.response_schema is not None:
allowed_mime_types = ("application/json", "text/x.enum")
if self.response_mime_type not in allowed_mime_types:
error_message = (
"`response_schema` is only supported when "
f"`response_mime_type` is set to one of {allowed_mime_types}"
)
raise ValueError(error_message)

gapic_response_schema = _convert_schema_dict_to_gapic(self.response_schema)
updated_params["response_schema"] = gapic_response_schema

return updated_params

def _get_ls_params(
self, stop: Optional[List[str]] = None, **kwargs: Any
) -> LangSmithParams:
Expand Down
Loading