From 4f9b70cab05efeae4c0112f0e0d76cdc2bbd53d9 Mon Sep 17 00:00:00 2001 From: Jeff Huang Date: Tue, 17 Nov 2026 15:37:55 -0600 Subject: [PATCH 1/3] feat(py): list an app's prompts with ai.list_prompts() ai.list_prompts() returns one Prompt handle per registered prompt, sorted by registered name: the same handle ai.prompt(name, variant=...) returns, so each entry can be called, rendered, or described. A variant is its own entry (greet.formal), a .prompt file in a subfolder keeps its folder (myns/a), and partials are not listed. Plugins start first, so a plugin whose init() fails makes it raise. Prompt gains a name property and an async describe() that returns a PromptDescription(name, description, input_schema). describe() loads the prompt first, including a .prompt file nothing has run, so every handle for the same prompt gives the same answer. An unknown name raises the same NOT_FOUND that calling the prompt raises. ai.list_tools() is covered by #92; this adds prompts only. --- packages/genkit/src/genkit/__init__.py | 2 + packages/genkit/src/genkit/_ai/_aio.py | 35 ++++ packages/genkit/src/genkit/_ai/_prompt.py | 57 +++++- .../genkit/tests/genkit/veneer/lookup_test.py | 181 +++++++++++++++++- 4 files changed, 271 insertions(+), 4 deletions(-) diff --git a/packages/genkit/src/genkit/__init__.py b/packages/genkit/src/genkit/__init__.py index c500d1d99..8ef1e6e2f 100644 --- a/packages/genkit/src/genkit/__init__.py +++ b/packages/genkit/src/genkit/__init__.py @@ -41,6 +41,7 @@ async def main() -> None: from genkit._ai._prompt import ( ModelStreamResponse, Prompt, + PromptDescription, ) from genkit._core._action import FlowContext, StreamResponse from genkit._core._error import ErrorReason, Failure, GenkitError, Interrupt, PublicError @@ -87,6 +88,7 @@ async def main() -> None: 'Flow', 'FlowContext', 'Prompt', + 'PromptDescription', 'GenkitError', 'PublicError', 'ErrorReason', diff --git a/packages/genkit/src/genkit/_ai/_aio.py b/packages/genkit/src/genkit/_ai/_aio.py index 46924c462..6f945fc4c 100644 --- a/packages/genkit/src/genkit/_ai/_aio.py +++ b/packages/genkit/src/genkit/_ai/_aio.py @@ -80,6 +80,7 @@ load_prompt_folder, parts_from_prompt, register_prompt_actions, + registry_definition_key, to_generate_options, ) from genkit._ai._tools import define_interrupt @@ -745,6 +746,40 @@ async def menu_price(dish: str) -> float: return None return Tool.from_action(action) + async def list_prompts(self) -> list[Prompt[Any, Any]]: + """Return every prompt registered on this app, sorted by registered name. + + Each entry is the handle ``ai.prompt(name, variant=...)`` returns: + calling it generates, and ``render()`` builds the request without + calling the model. A variant is its own entry (``'greet.formal'``), a + prompt from a ``.prompt`` subfolder keeps its folder (``'myns/a'``), and + partials aren't listed. Plugins are started first, and ``.prompt`` files + are loaded, so ``describe()`` on each entry is ready to read. + + Example: + ```python + ai.define_prompt(name='greet', prompt='Hello {{name}}') + ai.define_prompt(name='greet', variant='formal', prompt='Good day {{name}}') + + [p.name for p in await ai.list_prompts()] + # => ['greet', 'greet.formal'] + ``` + """ + await self._registry.initialize_all_plugins() + actions = await self._registry.resolve_actions_by_kind(ActionKind.PROMPT) + prompts: list[Prompt[Any, Any]] = [] + for key in sorted(actions): + block = actions[key].metadata.get('prompt') + block = cast(dict[str, object], block) if isinstance(block, dict) else {} + name = block.get('name') + variant = block.get('variant') + variant = variant if isinstance(variant, str) and variant else None + if isinstance(name, str) and registry_definition_key(name, variant) == key: + prompts.append(self.prompt(name, variant=variant)) + else: + prompts.append(self.prompt(key)) + return prompts + def lookup_value(self, *, kind: str, name: str) -> object | None: """Return the value defined under ``kind`` and ``name``, or None.""" return self._registry.lookup_value(kind, name) diff --git a/packages/genkit/src/genkit/_ai/_prompt.py b/packages/genkit/src/genkit/_ai/_prompt.py index d2ee3c5bb..074d4e952 100644 --- a/packages/genkit/src/genkit/_ai/_prompt.py +++ b/packages/genkit/src/genkit/_ai/_prompt.py @@ -278,6 +278,21 @@ def with_overrides(self, opts: PromptSettings) -> Self: return self.model_copy(update=set_by_call) +@dataclass(frozen=True, kw_only=True) +class PromptDescription: + """What a registered prompt says about itself, from ``await prompt.describe()``. + + Attributes: + name: Registered name, with the variant and folder: ``'greet.formal'``, ``'myns/a'``. + description: The prompt's description, or None if it has none. + input_schema: JSON schema of the prompt's input, or None if it declares none. + """ + + name: str + description: str | None + input_schema: dict[str, object] | None + + class Prompt(Generic[InputT, OutputT]): """A callable prompt with typed input/output that generates AI responses.""" @@ -358,10 +373,50 @@ def __init__( def ref(self) -> dict[str, Any]: """Reference object with prompt name and metadata.""" return { - 'name': registry_definition_key(self._name, self._variant, self._ns) if self._name else None, + 'name': self.name, 'metadata': self._def.metadata, } + @property + def name(self) -> str | None: + """Registered name, with the variant and folder (``'greet.formal'``, ``'myns/a'``); None if unnamed.""" + return registry_definition_key(self._name, self._variant, self._ns) if self._name else None + + async def describe(self) -> PromptDescription: + """Return the registered prompt's name, description, and input JSON schema. + + A ``.prompt`` file is loaded first if nothing has run it yet, so the + answer is the same on every handle for the same prompt. + + Raises: + GenkitError: ``NOT_FOUND`` if no prompt is registered under this + name, as calling it would. ``FAILED_PRECONDITION`` for a prompt + defined without a name, since nothing is registered to describe. + + Example: + ```python + ai.define_prompt(name='greet', description='Say hello.', input_schema=Guest, prompt='Hi {{name}}') + + info = await ai.prompt('greet').describe() + # => PromptDescription(name='greet', description='Say hello.', input_schema={...}) + ``` + """ + name = self.name + if name is None or self._name is None: + raise GenkitError( + status='FAILED_PRECONDITION', + message='This prompt was defined without a name, so it is not registered; pass name= to describe it.', + ) + registered = await lookup_prompt(self._ai._registry, self._name, self._variant) + schema = registered._def.input_schema + if isinstance(schema, str): + input_schema = self._ai._registry.lookup_schema(schema) + elif schema is not None: + input_schema = cast(dict[str, object], to_json_schema(schema)) + else: + input_schema = None + return PromptDescription(name=name, description=registered._description, input_schema=input_schema) + async def _ensure_resolved(self) -> None: if self._prompt_action or not self._name: return diff --git a/packages/genkit/tests/genkit/veneer/lookup_test.py b/packages/genkit/tests/genkit/veneer/lookup_test.py index e1048f2dd..4977c8d7b 100644 --- a/packages/genkit/tests/genkit/veneer/lookup_test.py +++ b/packages/genkit/tests/genkit/veneer/lookup_test.py @@ -3,18 +3,33 @@ # Copyright 2026 Google LLC # SPDX-License-Identifier: Apache-2.0 -"""What app code and middleware get back from lookup_model, lookup_tool, lookup_value, and define_value.""" +"""What app code and middleware get back from lookups, listings, lookup_value, and define_value.""" import re from collections.abc import Awaitable, Callable +from pathlib import Path import pytest - -from genkit import FinishReason, Genkit, Message, ModelResponse, Operation, Part, Role, Tool +from pydantic import BaseModel + +from genkit import ( + FinishReason, + Genkit, + GenkitError, + Message, + ModelResponse, + Operation, + Part, + Prompt, + PromptDescription, + Role, + Tool, +) from genkit._core._typing import MiddlewareRef from genkit.middleware import Middleware, MiddlewareContext, ModelHookParams from genkit.model import GenerateActionOptions, Model, ModelContext, ModelRequest from genkit.plugin_api import Action, ActionKind, Plugin +from genkit.testing import define_echo_model NextModel = Callable[[ModelHookParams, MiddlewareContext], Awaitable[ModelResponse]] @@ -164,6 +179,166 @@ async def table_status(table_id: str) -> str: assert Tool.from_action(found) is found +class Guest(BaseModel): + name: str + + +def _prompt_names(prompts: list[Prompt]) -> list[str | None]: + return [prompt.name for prompt in prompts] + + +@pytest.mark.asyncio +async def test_list_prompts_returns_prompt_handles_sorted_by_name() -> None: + """`await ai.list_prompts()` gives one Prompt handle per registered prompt, sorted by registered name.""" + ai = Genkit() + ai.define_prompt(name='welcome', prompt='Welcome {{name}}') + ai.define_prompt(name='greet', prompt='Hello {{name}}') + + prompts = await ai.list_prompts() + + assert _prompt_names(prompts) == ['greet', 'welcome'] + assert all(isinstance(prompt, Prompt) for prompt in prompts) + + +@pytest.mark.asyncio +async def test_list_prompts_on_an_app_without_prompts_is_empty() -> None: + """An app that defines no prompts lists none.""" + assert await Genkit().list_prompts() == [] + + +@pytest.mark.asyncio +async def test_list_prompts_lists_each_variant_as_its_own_prompt() -> None: + """A variant is listed as its own entry named `name.variant`, next to the base prompt.""" + ai = Genkit() + ai.define_prompt(name='greet', variant='formal', prompt='Good day {{name}}') + ai.define_prompt(name='greet', prompt='Hello {{name}}') + + prompts = await ai.list_prompts() + + assert _prompt_names(prompts) == ['greet', 'greet.formal'] + + +@pytest.mark.asyncio +async def test_list_prompts_lists_prompt_files_without_partials(tmp_path: Path) -> None: + """`.prompt` files are listed by file name, a subfolder file keeps its folder, and partials are not listed.""" + (tmp_path / 'greet.prompt').write_text('{{> header}}Hello {{name}}\n') + (tmp_path / 'greet.formal.prompt').write_text('Good day {{name}}\n') + (tmp_path / '_header.prompt').write_text('Menu: ') + (tmp_path / 'myns').mkdir() + (tmp_path / 'myns' / 'a.prompt').write_text('From a folder\n') + ai = Genkit(prompt_dir=tmp_path) + + prompts = await ai.list_prompts() + + assert _prompt_names(prompts) == ['greet', 'greet.formal', 'myns/a'] + + +@pytest.mark.asyncio +async def test_listed_prompt_generates_like_ai_prompt() -> None: + """Calling a listed prompt sends the same request and gets the same answer as `ai.prompt(name)`.""" + ai = Genkit(model='echoModel') + define_echo_model(ai) + ai.define_prompt(name='greet', variant='formal', prompt='Good day {{name}}') + + [listed] = await ai.list_prompts() + listed_response = await listed({'name': 'Ada'}) + looked_up_response = await ai.prompt('greet', variant='formal')({'name': 'Ada'}) + + assert listed_response.text == '[ECHO] user: "Good day Ada"' + assert listed_response.text == looked_up_response.text + + +@pytest.mark.asyncio +async def test_listed_prompt_renders_without_calling_the_model() -> None: + """`await listed.render(input)` returns the messages the model would get, and the model never runs.""" + ai = Genkit(model='echoModel') + echo, _ = define_echo_model(ai) + ai.define_prompt(name='greet', system='Be brief.', prompt='Hello {{name}}') + + [listed] = await ai.list_prompts() + rendered = await listed.render({'name': 'Ada'}) + + assert [(message.role, message.text) for message in rendered.messages] == [ + (Role.SYSTEM, 'Be brief.'), + (Role.USER, 'Hello Ada'), + ] + assert echo.last_request is None + + +@pytest.mark.asyncio +async def test_prompt_name_includes_variant_and_namespace(tmp_path: Path) -> None: + """`prompt.name` is `greet.formal` for a variant, `myns/a` for a subfolder file, and None for an unnamed prompt.""" + (tmp_path / 'myns').mkdir() + (tmp_path / 'myns' / 'a.prompt').write_text('From a folder\n') + ai = Genkit(prompt_dir=tmp_path) + + defined = ai.define_prompt(name='greet', variant='formal', prompt='Good day {{name}}') + unnamed = ai.define_prompt(prompt='Hi') + + assert defined.name == 'greet.formal' + assert ai.prompt('greet', variant='formal').name == 'greet.formal' + assert ai.prompt('myns/a').name == 'myns/a' + assert unnamed.name is None + + +@pytest.mark.asyncio +async def test_prompt_describe_gives_description_and_input_schema() -> None: + """`await prompt.describe()` gives the name, description, and input JSON schema, or None for what's not set.""" + ai = Genkit() + greet = ai.define_prompt(name='greet', description='Say hello.', input_schema=Guest, prompt='Hello {{name}}') + ai.define_prompt(name='plain', prompt='Hi') + + assert await greet.describe() == PromptDescription( + name='greet', description='Say hello.', input_schema=Guest.model_json_schema() + ) + assert [await prompt.describe() for prompt in await ai.list_prompts()] == [ + PromptDescription(name='greet', description='Say hello.', input_schema=Guest.model_json_schema()), + PromptDescription(name='plain', description=None, input_schema=None), + ] + + +@pytest.mark.asyncio +async def test_prompt_describe_loads_a_prompt_file_never_run_before(tmp_path: Path) -> None: + """`describe()` on a `.prompt` file nothing has run gives its frontmatter description and input schema.""" + (tmp_path / 'greet.prompt').write_text( + '---\ndescription: Greets a guest.\ninput:\n schema:\n name: string\n---\nHello {{name}}\n' + ) + ai = Genkit(prompt_dir=tmp_path) + + description = await ai.prompt('greet').describe() + + assert description.name == 'greet' + assert description.description == 'Greets a guest.' + assert description.input_schema is not None + assert description.input_schema['properties'] == {'name': {'type': 'string'}} + + +@pytest.mark.asyncio +async def test_prompt_describe_works_on_an_ai_prompt_handle_never_run() -> None: + """`ai.prompt('greet').describe()` on a fresh handle gives what the prompt was defined with.""" + ai = Genkit() + ai.define_prompt(name='greet', description='Say hello.', input_schema=Guest, prompt='Hello {{name}}') + + assert await ai.prompt('greet').describe() == PromptDescription( + name='greet', description='Say hello.', input_schema=Guest.model_json_schema() + ) + + +@pytest.mark.asyncio +async def test_prompt_describe_raises_not_found_for_an_unknown_prompt() -> None: + """`ai.prompt('nope').describe()` raises the same NOT_FOUND GenkitError that calling the prompt raises.""" + ai = Genkit(model='echoModel') + define_echo_model(ai) + + with pytest.raises(GenkitError) as described: + await ai.prompt('nope').describe() + with pytest.raises(GenkitError) as called: + await ai.prompt('nope')() + + assert described.value.status == 'NOT_FOUND' + assert str(described.value) == str(called.value) + + def test_define_value_then_lookup_value_returns_it() -> None: """A value stored with `ai.define_value(...)` comes back from `ai.lookup_value(...)` for the same kind and name.""" ai = Genkit() From c119bd42eec8bddd83709c1706f0bd4717e2fa93 Mon Sep 17 00:00:00 2001 From: Jeff Huang Date: Thu, 19 Nov 2026 09:59:02 -0600 Subject: [PATCH 2/3] refactor(py): extract prompt_name_and_variant helper for list_prompts --- packages/genkit/src/genkit/_ai/_aio.py | 13 +++---------- packages/genkit/src/genkit/_ai/_prompt.py | 14 ++++++++++++++ 2 files changed, 17 insertions(+), 10 deletions(-) diff --git a/packages/genkit/src/genkit/_ai/_aio.py b/packages/genkit/src/genkit/_ai/_aio.py index 6f945fc4c..73c938300 100644 --- a/packages/genkit/src/genkit/_ai/_aio.py +++ b/packages/genkit/src/genkit/_ai/_aio.py @@ -79,8 +79,8 @@ define_schema, load_prompt_folder, parts_from_prompt, + prompt_name_and_variant, register_prompt_actions, - registry_definition_key, to_generate_options, ) from genkit._ai._tools import define_interrupt @@ -769,15 +769,8 @@ async def list_prompts(self) -> list[Prompt[Any, Any]]: actions = await self._registry.resolve_actions_by_kind(ActionKind.PROMPT) prompts: list[Prompt[Any, Any]] = [] for key in sorted(actions): - block = actions[key].metadata.get('prompt') - block = cast(dict[str, object], block) if isinstance(block, dict) else {} - name = block.get('name') - variant = block.get('variant') - variant = variant if isinstance(variant, str) and variant else None - if isinstance(name, str) and registry_definition_key(name, variant) == key: - prompts.append(self.prompt(name, variant=variant)) - else: - prompts.append(self.prompt(key)) + name, variant = prompt_name_and_variant(key, actions[key].metadata) + prompts.append(self.prompt(name, variant=variant)) return prompts def lookup_value(self, *, kind: str, name: str) -> object | None: diff --git a/packages/genkit/src/genkit/_ai/_prompt.py b/packages/genkit/src/genkit/_ai/_prompt.py index 074d4e952..afc4d16f0 100644 --- a/packages/genkit/src/genkit/_ai/_prompt.py +++ b/packages/genkit/src/genkit/_ai/_prompt.py @@ -1400,6 +1400,20 @@ def registry_definition_key(name: str, variant: str | None = None, ns: str | Non return '/'.join(parts) +def prompt_name_and_variant(key: str, metadata: Mapping[str, object]) -> tuple[str, str | None]: + """Recover ``(name, variant)`` for ``ai.prompt(...)`` from a prompt action's metadata.""" + raw = metadata.get('prompt') + if not isinstance(raw, dict): + return key, None + block: dict[str, object] = cast(dict[str, object], raw) + name = block.get('name') + raw_variant = block.get('variant') + variant = raw_variant if isinstance(raw_variant, str) and raw_variant else None + if isinstance(name, str) and registry_definition_key(name, variant) == key: + return name, variant + return key, None + + def registry_lookup_key(name: str, variant: str | None = None, ns: str | None = None) -> str: """Generate a registry lookup key for a prompt. From 92d87c2f7c136401eef065112cabc53fd3e4b178 Mon Sep 17 00:00:00 2001 From: Jeff Huang Date: Thu, 3 Dec 2026 18:22:14 +0000 Subject: [PATCH 3/3] refactor(py): don't promise an order from list_prompts() The registry is a dict, so registration order is already stable. Leave ordering unspecified rather than make sorted-by-name part of the API, matching the ask on list_tools() in #92. --- packages/genkit/src/genkit/_ai/_aio.py | 6 ++--- .../genkit/tests/genkit/veneer/lookup_test.py | 25 +++++++++++-------- 2 files changed, 17 insertions(+), 14 deletions(-) diff --git a/packages/genkit/src/genkit/_ai/_aio.py b/packages/genkit/src/genkit/_ai/_aio.py index 73c938300..3ec262758 100644 --- a/packages/genkit/src/genkit/_ai/_aio.py +++ b/packages/genkit/src/genkit/_ai/_aio.py @@ -747,7 +747,7 @@ async def menu_price(dish: str) -> float: return Tool.from_action(action) async def list_prompts(self) -> list[Prompt[Any, Any]]: - """Return every prompt registered on this app, sorted by registered name. + """Return every prompt registered on this app. Each entry is the handle ``ai.prompt(name, variant=...)`` returns: calling it generates, and ``render()`` builds the request without @@ -768,8 +768,8 @@ async def list_prompts(self) -> list[Prompt[Any, Any]]: await self._registry.initialize_all_plugins() actions = await self._registry.resolve_actions_by_kind(ActionKind.PROMPT) prompts: list[Prompt[Any, Any]] = [] - for key in sorted(actions): - name, variant = prompt_name_and_variant(key, actions[key].metadata) + for key, action in actions.items(): + name, variant = prompt_name_and_variant(key, action.metadata) prompts.append(self.prompt(name, variant=variant)) return prompts diff --git a/packages/genkit/tests/genkit/veneer/lookup_test.py b/packages/genkit/tests/genkit/veneer/lookup_test.py index 4977c8d7b..e2ee40d9f 100644 --- a/packages/genkit/tests/genkit/veneer/lookup_test.py +++ b/packages/genkit/tests/genkit/veneer/lookup_test.py @@ -183,20 +183,22 @@ class Guest(BaseModel): name: str -def _prompt_names(prompts: list[Prompt]) -> list[str | None]: - return [prompt.name for prompt in prompts] +def _prompt_names(prompts: list[Prompt]) -> set[str | None]: + """The listed names, as a set: `list_prompts()` makes no promise about order.""" + return {prompt.name for prompt in prompts} @pytest.mark.asyncio -async def test_list_prompts_returns_prompt_handles_sorted_by_name() -> None: - """`await ai.list_prompts()` gives one Prompt handle per registered prompt, sorted by registered name.""" +async def test_list_prompts_returns_one_prompt_handle_per_prompt() -> None: + """`await ai.list_prompts()` gives one Prompt handle per registered prompt.""" ai = Genkit() ai.define_prompt(name='welcome', prompt='Welcome {{name}}') ai.define_prompt(name='greet', prompt='Hello {{name}}') prompts = await ai.list_prompts() - assert _prompt_names(prompts) == ['greet', 'welcome'] + assert len(prompts) == 2 + assert _prompt_names(prompts) == {'greet', 'welcome'} assert all(isinstance(prompt, Prompt) for prompt in prompts) @@ -215,7 +217,7 @@ async def test_list_prompts_lists_each_variant_as_its_own_prompt() -> None: prompts = await ai.list_prompts() - assert _prompt_names(prompts) == ['greet', 'greet.formal'] + assert _prompt_names(prompts) == {'greet', 'greet.formal'} @pytest.mark.asyncio @@ -230,7 +232,7 @@ async def test_list_prompts_lists_prompt_files_without_partials(tmp_path: Path) prompts = await ai.list_prompts() - assert _prompt_names(prompts) == ['greet', 'greet.formal', 'myns/a'] + assert _prompt_names(prompts) == {'greet', 'greet.formal', 'myns/a'} @pytest.mark.asyncio @@ -291,10 +293,11 @@ async def test_prompt_describe_gives_description_and_input_schema() -> None: assert await greet.describe() == PromptDescription( name='greet', description='Say hello.', input_schema=Guest.model_json_schema() ) - assert [await prompt.describe() for prompt in await ai.list_prompts()] == [ - PromptDescription(name='greet', description='Say hello.', input_schema=Guest.model_json_schema()), - PromptDescription(name='plain', description=None, input_schema=None), - ] + described = {prompt.name: await prompt.describe() for prompt in await ai.list_prompts()} + assert described == { + 'greet': PromptDescription(name='greet', description='Say hello.', input_schema=Guest.model_json_schema()), + 'plain': PromptDescription(name='plain', description=None, input_schema=None), + } @pytest.mark.asyncio