-
Notifications
You must be signed in to change notification settings - Fork 23
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
Support nested pydantic models with Gemini tool calling [DRAFT] #222
Draft
barapa
wants to merge
3
commits into
Mirascope:dev
Choose a base branch
from
barapa:json-ref
base: dev
Could not load branches
Branch not found: {{ refName }}
Could not load tags
Nothing to show
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Draft
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,15 +1,20 @@ | ||
"""Classes for using tools with Google's Gemini API.""" | ||
from __future__ import annotations | ||
|
||
from typing import Callable, Type | ||
import pprint | ||
from typing import Any, Callable, Type | ||
|
||
import jsonref | ||
from google.ai.generativelanguage import FunctionCall | ||
from google.generativeai.types import ( # type: ignore | ||
FunctionDeclaration, | ||
Tool, | ||
) | ||
from pydantic import BaseModel, ConfigDict | ||
|
||
from mirascope.base.tools import DEFAULT_TOOL_DOCSTRING | ||
from mirascope.gemini.utils import remove_invalid_title_keys_from_parameters | ||
|
||
from ..base import ( | ||
BaseTool, | ||
BaseType, | ||
|
@@ -68,20 +73,42 @@ def tool_schema(cls) -> Tool: | |
Returns: | ||
The constructed `Tool` schema. | ||
""" | ||
tool_schema = super().tool_schema() | ||
if "parameters" in tool_schema: | ||
if "$defs" in tool_schema["parameters"]: | ||
raise ValueError( | ||
"Unfortunately Google's Gemini API cannot handle nested structures " | ||
"with $defs." | ||
super().tool_schema() | ||
model_schema: dict[str, Any] = cls.model_json_schema() | ||
pprint.pprint(model_schema) | ||
|
||
# Replace all references with their values | ||
without_refs: dict[str, Any] = jsonref.replace_refs(model_schema) # type: ignore | ||
pprint.pprint(without_refs) | ||
|
||
# Remove all Defs | ||
without_refs.pop("$defs") | ||
pprint.pprint(without_refs) | ||
|
||
# Get the name and description, and remove them from the schema | ||
name: str = without_refs.pop("title") # type: ignore | ||
description: str = ( # type: ignore | ||
without_refs.pop("description", None) or DEFAULT_TOOL_DOCSTRING | ||
) | ||
parameters: dict[str, Any] = without_refs | ||
|
||
# Remove all instances of title key in each param definition | ||
# This is careful not to delete keys that represent a field with the name title | ||
remove_invalid_title_keys_from_parameters(parameters) | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. what if all of the conversion of |
||
|
||
print(f"{name=}") | ||
print(f"{description=}") | ||
print(f"{parameters=}") | ||
|
||
return Tool( | ||
function_declarations=[ | ||
FunctionDeclaration( | ||
name=name, | ||
description=description, | ||
parameters=parameters, | ||
) | ||
tool_schema["parameters"]["properties"] = { | ||
prop: { | ||
key: value for key, value in prop_schema.items() if key != "title" | ||
} | ||
for prop, prop_schema in tool_schema["parameters"]["properties"].items() | ||
} | ||
return Tool(function_declarations=[FunctionDeclaration(**tool_schema)]) | ||
] | ||
) | ||
|
||
@classmethod | ||
def from_tool_call(cls, tool_call: FunctionCall) -> GeminiTool: | ||
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,55 @@ | ||
from typing import Any | ||
|
||
|
||
def remove_invalid_title_keys_from_parameters(d: dict[str, Any] | Any) -> None: | ||
""" | ||
For each property, remove the title key. However, we make sure to only remove | ||
the title key in each schema | ||
Before | ||
{ | ||
"properties": { | ||
"books": { | ||
"items": { | ||
"properties": { | ||
"author_name": {"title": "Author Name", "type": "string"}, | ||
"title": {"title": "Title", "type": "string"}, | ||
}, | ||
"required": ["author_name", "title"], | ||
"title": "Book", | ||
"type": "object", | ||
}, | ||
"title": "Books", | ||
"type": "array", | ||
} | ||
}, | ||
"required": ["books"], | ||
"title": "Books", | ||
"type": "object", | ||
} | ||
|
||
AFTER | ||
{ | ||
"properties": { | ||
"books": { | ||
"items": { | ||
"properties": { | ||
"author_name": {"type": "string"}, | ||
"title": {"type": "string"}, | ||
}, | ||
"required": ["author_name", "title"], | ||
"type": "object", | ||
}, | ||
"type": "array", | ||
} | ||
}, | ||
"required": ["books"], | ||
"type": "object", | ||
} | ||
|
||
""" | ||
if isinstance(d, dict): | ||
for key in list(d.keys()): | ||
if key == "title" and "type" in d.keys(): | ||
del d[key] | ||
else: | ||
remove_invalid_title_keys_from_parameters(d[key]) |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
quick note:
name and description are already in
super().tool_schema()
, so it's really just theparameters
field that needs to be modified (and thus remove duplicate code).