diff --git a/packages/genkit/src/genkit/__init__.py b/packages/genkit/src/genkit/__init__.py index c500d1d9..8ef1e6e2 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 46924c46..3ec26275 100644 --- a/packages/genkit/src/genkit/_ai/_aio.py +++ b/packages/genkit/src/genkit/_ai/_aio.py @@ -79,6 +79,7 @@ define_schema, load_prompt_folder, parts_from_prompt, + prompt_name_and_variant, register_prompt_actions, to_generate_options, ) @@ -745,6 +746,33 @@ 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. + + 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, action in actions.items(): + name, variant = prompt_name_and_variant(key, action.metadata) + prompts.append(self.prompt(name, variant=variant)) + 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 d2ee3c5b..afc4d16f 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 @@ -1345,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. diff --git a/packages/genkit/tests/genkit/veneer/lookup_test.py b/packages/genkit/tests/genkit/veneer/lookup_test.py index e1048f2d..e2ee40d9 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,169 @@ 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]) -> 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_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 len(prompts) == 2 + 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() + ) + 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 +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()