Skip to content

fix(py): plugin action key prefixing, Dev UI runtime paths, middleware exports - #7145

Closed
huangjeff5 wants to merge 11 commits into
mainfrom
fix/py-1.0-pr6-devui-middleware-mcp
Closed

huangjeff5 wants to merge 11 commits into
mainfrom
fix/py-1.0-pr6-devui-middleware-mcp

Conversation

@huangjeff5

Copy link
Copy Markdown
Contributor

Plugin ABI, Dev UI runtime file paths, and middleware export cleanup.

Main Changes

  • Plugin action key prefixing: Prefixes action keys with the plugin name to prevent collisions across plugins registering standard actions.
  • Project root pathing for Dev UI: Writes Dev UI runtime and reflection files relative to CLI project root instead of process cwd.
  • Exported middleware configs: Exported middleware configuration classes from public namespaces.

Registry.list_actions() advertised /model/org/name for a plugin returning
an unprefixed slash id, which 404s on /api/runAction. Apply the same
prefix rule as init().
…chemas

- Model wraps an unannotated request parameter as ModelRequest, like
  Embedder, so Dev UI / CLI runs pass a ModelRequest, not a dict.
- DynamicActionProvider stamps itself on its action, so one returned
  from Plugin.init() is recoverable from the registry.
- genkit-openai wraps non-object tool input schemas under 'input' and
  unwraps tool requests, matching genkit-google-genai.
RuntimeManager wrote .genkit/runtimes to cwd while the CLI reads it from
findProjectRoot(). From a subdirectory the Dev UI showed 0 actions. Walk
ancestors with the CLI's marker list; fall back to cwd.
- /api/runAction awaits flush_instrumentations() before answering, as v2
  and JS do, so the root span is exported when the response lands.
- Error details.stack carries the Python traceback when empty, so
  genkit flow:run prints Python frames (matches v2).
- /api/notify also enables log export and warns on spec-version
  mismatch; /api/__health?id= answers 503 for another runtime; a
  missing runAction key is 400, not a KeyError 500.
websockets defaults max_size to 1 MiB; a runAction with one screenshot
closed the socket with 1009. Match the CLI's 100 MiB. register now
sends pid and reflectionApiSpecVersion as integers.
structlog's default factory printed to stdout, breaking
`python cli.py | jq .`. Default to stderr unless the app set a factory.
define_value / define_schema now overwrite on re-registration, like
flows, tools, and prompts, so re-running a Jupyter cell works.
…untime dirs

- ai.run_main() under Jupyter/IPython raises a RuntimeError that points
  to `await main()` and closes the coroutine (no unawaited warning).
- The reflection port-range error was unreachable; instance #101 got a
  bare EADDRINUSE. Name the cause and the fix.
- RuntimeManager removes .genkit/runtimes and .genkit when it leaves
  them empty.
- use=[Mw(...)] ran a fresh cls(config=...) rebuilt from serialized
  config: custom __init__ crashed, __init__ state reset, re.Pattern lost
  its flags (SECRET bypassed an IGNORECASE guard), Callable config fields
  raised PydanticSerializationError. The call's child registry now keeps
  the caller's instance and the per-call copy is a shallow copy.copy.
  MiddlewareRef serialization stays for traces and the Dev UI.
- A Middleware subclass defining 0.12 model()/generate()/tool() without
  the matching wrap_* raises TypeError at class definition instead of
  becoming a silent no-op.
…ks commit

- A string Fallback entry inherits the caller's config narrowed to keys
  the backup's config class accepts (portable generation keys when it
  has none), instead of {} wiping max_output_tokens/temperature. Matches
  JS (entry.config ?? req.config). version/extra never carry over.
- Retry and Fallback no longer retry or fail over once the failed
  attempt streamed chunks to the caller, which spliced a second answer
  onto partial JSON in ChunkAccumulator.

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request introduces several enhancements and bug fixes across the Genkit Python SDK. Key changes include adding streaming safety to fallback and retry middleware to prevent retries or failovers after chunks are committed, supporting scalar tool input wrapping and unwrapping in the OpenAI provider, enabling overwriting of registered values and schemas to support Jupyter notebooks, and aligning the Dev UI reflection server behavior with the JS implementation (such as flushing traces before responding, increasing websocket message limits, and handling project root detection). The review feedback highlights two important improvements: resolving the path in find_project_root to an absolute path to ensure relative paths are handled correctly, and wrapping await req.json() in a try...except block within the reflection server's run endpoint to gracefully handle invalid JSON payloads with a 400 error instead of crashing with a 500.

Mirrors the CLI: walk up from cwd, stop before the filesystem root, and
fall back to cwd when no marker is found.
"""
cwd = Path(start) if start is not None else Path.cwd()

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

If start is passed as a relative path, find_project_root will remain relative and fail to find the project root if it is located at or above the current working directory (since the loop terminates when current reaches Path('.')). Resolving the path to an absolute path first ensures that the directory traversal works correctly for both relative and absolute inputs.

Suggested change
cwd = Path(start) if start is not None else Path.cwd()
cwd = Path(start or Path.cwd()).resolve()

async def run(req: Request) -> Response:
payload = await req.json()
key = payload['key']
key = payload.get('key') if isinstance(payload, dict) else None

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

The call to await req.json() on the previous line can raise a JSONDecodeError if the request body is not valid JSON. Since this is a raw ASGI/Starlette route, an unhandled exception here will result in a 500 Internal Server Error. It is safer to wrap await req.json() in a try...except block and handle invalid JSON gracefully (e.g., by returning a 400 Bad Request), similar to how it is done in the notify endpoint.

@huangjeff5

Copy link
Copy Markdown
Contributor Author

Closing: migrated to standalone repository genkit-ai/genkit-python (PR #53): genkit-ai/genkit-python#53

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant