chore(py): re-organize file structure, api signatures, types#4879
chore(py): re-organize file structure, api signatures, types#4879huangjeff5 wants to merge 24 commits intomainfrom
Conversation
Summary of ChangesHello, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed! This pull request undertakes a substantial refactoring of the Python SDK, focusing on internal module consolidation and a more consistent, async-first public API. The changes aim to streamline development, improve clarity of core functionalities, and enhance the overall architectural design of the Genkit framework. Highlights
🧠 New Feature in Public Preview: You can now enable Memory to help Gemini Code Assist learn from your team's feedback. This makes future code reviews more consistent and personalized to your project's style. Click here to enable Memory in your admin console. Changelog
Using Gemini Code AssistThe full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips. Invoking Gemini You can request assistance from Gemini at any point by creating a comment using either
Customization To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a Limitations & Feedback Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for Github and other Google products, sign up here. You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension. Footnotes
|
There was a problem hiding this comment.
Code Review
This is a significant refactoring that reorganizes the file structure and simplifies several key API signatures. The changes, such as renaming arun() to run(), making core actions async-only, and replacing Input/Output wrappers with direct schema arguments, make the API more consistent and modern. The codebase, including samples and tests, has been updated thoroughly to reflect these changes. I've pointed out a few places where type hints for decorators and methods should be updated to match the new async requirements, which will improve static analysis and developer experience.
Note: Security Review did not run due to the size of the PR.
py/plugins/google-genai/src/genkit/plugins/google_genai/models/utils.py
Outdated
Show resolved
Hide resolved
py/plugins/google-genai/src/genkit/plugins/google_genai/models/utils.py
Outdated
Show resolved
Hide resolved
|
/gemini review |
There was a problem hiding this comment.
Code Review
This pull request introduces a major refactoring of the Python SDK, reorganizing the file structure into _core and _ai modules and establishing a new public API surface. A significant change is making actions, flows, and tools async-only, which simplifies the concurrency model. The refactoring appears well-executed and consistent. I've identified a couple of minor code quality issues related to duplicate entries in a configuration set and the __all__ export list, which should be addressed for better maintainability.
Note: Security Review did not run due to the size of the PR.
| config: dict[str, object] | None = None, | ||
| ) -> ModelRef: | ||
| """Create a ModelRef, optionally prefixing name with namespace.""" | ||
| # Logic: if (options.namespace && !name.startsWith(options.namespace + '/')) |
There was a problem hiding this comment.
remove logic comment, outdated
|
|
||
|
|
||
| def get_request_api_key(config: Mapping[str, object] | ModelConfig | object | None) -> str | None: | ||
| """Extract API key from config (snake_case or camelCase).""" |
There was a problem hiding this comment.
This is too complicated. We shouldn't have fallbacks. We need a well defined contract.
| ToolResponsePart, | ||
| ) | ||
|
|
||
| ModelStreamingCallback = StreamingCallback |
There was a problem hiding this comment.
Don't need/want this alias
| OutputT = TypeVar('OutputT') | ||
|
|
||
|
|
||
| class OutputOptions(TypedDict, total=False): |
| metadata: dict[str, Any] | None | ||
|
|
||
|
|
||
| class ModelStreamResponse(Generic[OutputT]): |
There was a problem hiding this comment.
Double check if this class makes sense
| class PromptCache: | ||
| """Model for a prompt cache.""" | ||
|
|
||
| user_prompt: PromptFunction[Any] | None = None |
| See Also: | ||
| - JavaScript RealtimeSpanProcessor: js/core/src/tracing/realtime-span-processor.ts | ||
| """ | ||
| """Realtime span processor for live trace visualization.""" |
There was a problem hiding this comment.
trace/ folder should be _trace/
| except Exception as e: | ||
| status_code = get_http_status(e) # 404 for NOT_FOUND, 500 otherwise | ||
| ``` | ||
| # ============================================================================= |
There was a problem hiding this comment.
remove this comment
|
|
||
| from pydantic import BaseModel, ConfigDict | ||
| from pydantic.alias_generators import to_camel | ||
| class Status(BaseModel): |
There was a problem hiding this comment.
Does status belong in this file?
| # Copyright 2025 Google LLC | ||
| # |
There was a problem hiding this comment.
file naming is a bit wierd
| cursor: int | ||
|
|
||
|
|
||
| def extract_items(text: str, cursor: int = 0) -> ExtractItemsResult: |
There was a problem hiding this comment.
beter naming? extract_json_array_from_text?
| T = TypeVar('T') | ||
|
|
||
|
|
||
| class _FlowDecorator: |
There was a problem hiding this comment.
does flow decorator belong here?
There was a problem hiding this comment.
Is there the equivalent decorator for tools? Other primitives?
Decorators should probably live together.
| _cache_lock = threading.Lock() | ||
|
|
||
|
|
||
| def get_cached_client( |
There was a problem hiding this comment.
This seems to be solving the same fundamental problem as _loop_cache.py. See if we can unify.
| aggregated=chunk.aggregated, | ||
| ) | ||
| else: | ||
| # Direct construction mode: role=..., content=... kwargs |
There was a problem hiding this comment.
Not understanding why this else block is "direct construction mode"
the conditional is "if chunk is not None"
| return await self.resolve_action(kind, name) | ||
|
|
||
| async def list_actions(self, allowed_kinds: list[ActionKind] | None = None) -> list[ActionMetadata]: | ||
| async def list_actions(self, allowed_kinds: list[str] | None = None) -> list[ActionMetadata]: |
There was a problem hiding this comment.
should still be ActionKind
| tool_choice: ToolChoice | None = Field(default=None) | ||
| output: OutputModel | None = None | ||
| docs: Docs | None = None | ||
| output: OutputConfig | None = None |
There was a problem hiding this comment.
If we extend this wire format we will expose output which is wrong
| ModelRequest, | ||
| ModelResponse, | ||
| ModelResponseChunk, | ||
| OutputConfig, |
| Media, | ||
| MediaPart, | ||
| Message, | ||
| Metadata, |
There was a problem hiding this comment.
what's this one?
|
|
||
| # Import embedder-related types from the embedder namespace | ||
| from genkit.embedder import ( | ||
| EmbedderOptions, |
There was a problem hiding this comment.
Is this the same as ModelConfig? EmbedderConfig?
| 'Metadata', | ||
| 'ReasoningPart', | ||
| 'FinishReason', | ||
| 'GenerationUsage', |
There was a problem hiding this comment.
Should this be ModelUsage maybe?
| @@ -21,41 +21,39 @@ def test_parses_simple_enum_value(self) -> None: | |||
| enum_fmt = EnumFormat() | |||
| fmt = enum_fmt.handle({'type': 'string', 'enum': ['VALUE1', 'VALUE2']}) | |||
|
|
|||
| result = fmt.parse_message(MessageWrapper(Message(role='model', content=[Part(root=TextPart(text='VALUE1'))]))) | |||
| result = fmt.parse_message(Message(Message(role='model', content=[Part(root=TextPart(text='VALUE1'))]))) | |||
There was a problem hiding this comment.
why is this double wrapped?
| chunk1 = GenerateResponseChunk(content=[Part(root=TextPart(text='"f'))]) | ||
| chunk2 = GenerateResponseChunk(content=[Part(root=TextPart(text='oo"'))]) | ||
| chunk1 = ModelResponseChunk(content=[Part(root=TextPart(text='"f'))]) | ||
| chunk2 = ModelResponseChunk(content=[Part(root=TextPart(text='oo"'))]) |
There was a problem hiding this comment.
stop using root=
| @@ -18,8 +18,8 @@ def test_parses_complete_json_object(self) -> None: | |||
| json_fmt = JsonFormat() | |||
| fmt = json_fmt.handle({'type': 'object'}) | |||
|
|
|||
| chunk = GenerateResponseChunk(content=[Part(root=TextPart(text='{"id": 1, "name": "test"}'))]) | |||
| result = fmt.parse_chunk(GenerateResponseChunkWrapper(chunk, index=0, previous_chunks=[])) | |||
| chunk = ModelResponseChunk(content=[Part(root=TextPart(text='{"id": 1, "name": "test"}'))]) | |||
There was a problem hiding this comment.
stop using root= everywhere
| @@ -92,7 +90,7 @@ def test_handles_empty_response(self) -> None: | |||
| jsonl_fmt = JsonlFormat() | |||
| fmt = jsonl_fmt.handle({'type': 'array', 'items': {'type': 'object'}}) | |||
|
|
|||
| result = fmt.parse_message(MessageWrapper(Message(role='model', content=[Part(root=TextPart(text=''))]))) | |||
| result = fmt.parse_message(Message(Message(role='model', content=[Part(root=TextPart(text=''))]))) | |||
There was a problem hiding this comment.
why double message wrapper
| @@ -112,7 +122,7 @@ async def test_simulates_doc_grounding( | |||
| content=[Part(root=TextPart(text='hi'))], | |||
| ), | |||
| ], | |||
| docs=[DocumentData(content=[DocumentPart(root=TextPart(text='doc content 1'))])], | |||
| docs=[Document(content=[DocumentPart(root=TextPart(text='doc content 1'))])], | |||
| want = clean_schema(spec['expectResponse']) | ||
| if got != want: | ||
| raise AssertionError( | ||
| f'{dump_json(got, indent=2)}\n\nis not equal to expected:\n\n{dump_json(want, indent=2)}' | ||
| f'{_to_json(got, indent=2)}\n\nis not equal to expected:\n\n{_to_json(want, indent=2)}' |
There was a problem hiding this comment.
what is _to_json?
|
|
||
| res4 = await ai.run('multiply', 10, multiply) | ||
| assert res4 == 20 | ||
| with pytest.raises(TypeError, match='fn must be a coroutine function'): |
There was a problem hiding this comment.
coroutine function = async function?
| StreamingFenceStripper, | ||
| maybe_strip_fences, | ||
| ) | ||
| from genkit.plugins.amazon_bedrock.typing import BedrockConfig |
There was a problem hiding this comment.
Double check this all actually makes sense... so many new concepts. also why is there a typing file
| from genkit.core.action import Action, ActionMetadata | ||
| from genkit.core.logging import get_logger | ||
| from genkit.core.registry import ActionKind | ||
| from genkit import Embedding, EmbedRequest, EmbedResponse |
There was a problem hiding this comment.
import from embedder
| @@ -168,12 +168,12 @@ class CohereToolChoice(StrEnum): | |||
| class GenkitCommonConfigMixin(BaseModel): | |||
| """Genkit common configuration parameters mixin. | |||
|
|
|||
| These parameters match the Genkit core GenerationCommonConfigSchema and are | |||
There was a problem hiding this comment.
?? It's duplicating core framework stuff
No description provided.