ahvn.ukf.templates.basic.prompt module

class ahvn.ukf.templates.basic.prompt.PromptUKFT(*, name, notes='', short_description='', description='', type='general', version='v0.1.0', version_notes='', variant='default', variant_notes='', content='', content_resources=<factory>, content_composers=<factory>, source='unknown', parents=<factory>, creator='unknown', owner='unknown', workspace='unknown', collection='general', tags=<factory>, synonyms=<factory>, triggers=<factory>, priority=0, related=<factory>, auths=<factory>, timefluid=False, timestamp=<factory>, last_verified=<factory>, expiration=-1, inactive_mark=False, metadata=<factory>, profile=<factory>)[源代码]

基类:ResourceUKFT

Prompt class for storing and rendering Jinja2 template folders.

This is a specialized ResourceUKFT type designed for working with Jinja2 template folders that follow AgentHeaven's prompt structure (with templates, filters, and locale for i18n). It provides convenient methods for rendering templates with specified inputs and language settings.

UKF Type: prompt Recommended Components of content_resources:

  • path (str): The original prompt folder path.

  • data (Dict[str, Optional[str]]): Serialized folder structure from serialize_path.

  • annotations (Dict[str, str]): File-level annotations for context.

  • lang (str): Default language for rendering templates (defaults to config).

Recommended Composers:
prompt_list:

Lists all available .jinja templates in the prompt folder. Examples: ` Available templates in 'autocode': - default.jinja `

示例

>>> # Create from path
>>> prompt = PromptUKFT.from_path("& prompts/autocode")
>>>
>>> # Render a template
>>> result = prompt.render(
...     template="default.jinja",
...     code="def add(a, b): ...",
...     examples=[],
...     inputs={"a": 1, "b": 2}
... )
>>> # Render with language specification
>>> result_zh = prompt.render(
...     template="default.jinja",
...     lang="zh",
...     code="def add(a, b): ...",
...     examples=[]
... )
参数:
type_default: ClassVar[str] = 'prompt'
classmethod from_path(path, default_entry='default.jinja', name=None, lang=None, keep_path=True, binds=None, **updates)[源代码]

Create a PromptUKFT instance from a Jinja2 template folder path.

Serializes the prompt folder contents and configures the resource with appropriate metadata and composers for prompt rendering.

参数:
  • path (str) -- Path to the prompt folder containing .jinja templates.

  • default_entry (str) -- The default template entry to use for prompt composer. Notice that entry does not limit the resource to only that template; other templates in the folder can still be accessed, but this will be the default used by prompt_composer. Defaults to "default.jinja".

  • name (str, optional) -- PromptUKFT resource name. If None, generates name from the basename of the path. Required if path is a file.

  • lang (str, optional) -- Default language for rendering. If None, uses the language from config ("prompts.lang").

  • keep_path (bool) -- Whether to keep the original path in content_resources. Defaults to True.

  • binds (Dict[str, Any], optional) -- Default template variables to bind.

  • **updates -- Additional keyword arguments to update the PromptUKFT instance attributes.

返回:

New PromptUKFT instance with pre-configured composers:
  • prompt (default): Renders with entry template

  • list: Lists files (with ext parameter support, defaults to "jinja")

  • diagram: Shows folder structure

返回类型:

PromptUKFT

示例

>>> prompt = PromptUKFT.from_path("& prompts/autocode")
>>> prompt.name
"autocode"
>>> # Use as default composer (calls prompt_composer)
>>> prompt.text(code="...", examples=[])
classmethod from_jinja(content, jinja_kwargs=None, name=None, lang=None, binds=None, **updates)[源代码]

Create a new PromptUKFT instance from provided jinja content).

参数:
  • content (str) -- Jinja2 template content string.

  • name (str, optional) -- PromptUKFT resource name. If None, use default as name.

  • jinja_kwargs (Dict[str, Any], optional) --

    Additional arguments for Jinja2 template creation. Defaults to None, which uses an empty dictionary. These can include:

    • autojinja (bool): Whether to auto-convert content to a standard Jinja2 template.

    • autoi18n (bool): Whether to initialize Babel localization files.

  • **updates -- Additional keyword arguments to update the PromptUKFT.

  • lang (str | None)

  • binds (Dict[str, Any] | None)

返回:

New PromptUKFT instance created from the provided content.

返回类型:

PromptUKFT

示例

>>> prompt = PromptUKFT.from_jinja(
...     content='''            ... You are a helpful assistant.
... {% trans %}Here is the code:{% endtrans %}
...
... ```python
... {{ code }}
... ```
... {% trans %}Help me write tests.{% endtrans %}''',
...     name="simple_prompt",
...     lang="zh",
...     jinja_kwargs={
...         "autoi18n": True,
...     },
... )
... prompt.text(code="def add(a, b): return a + b")
>>> '''            You are a helpful assistant.
以下是代码:
```python
def add(a, b): return a + b
```
帮我编写测试。'''
bind(**binds)[源代码]

An inplace operation to add default template variables to bind during rendering.

参数:

**binds -- Template variables to bind as a dictionary of key-values.

返回:

The PromptUKFT instance (for chaining).

返回类型:

self

unbind(*keys)[源代码]

An inplace operation to remove default template variables from binding during rendering.

参数:

*keys (str) -- Template variable keys to unbind.

返回:

The PromptUKFT instance (for chaining).

返回类型:

self

to_env(path=None, lang=None)[源代码]

Load the Jinja2 environment for this prompt resource. Notice that when path is not provided, the prompt folder is unzipped to a temporary location. This could result in missing files if the temporary folder is cleaned up, use with caution. TODO: Add locking mechanism to avoid cleanup during usage.

参数:
  • path (str, optional) -- Path to the prompt folder containing .jinja templates.

  • lang (str, optional) -- Language code for this rendering. If None, uses the default language from content_resources or config.

返回:

Jinja2 Environment object for rendering templates.

返回类型:

Environment

render(path=None, entry=None, lang=None, **kwargs)[源代码]

Render a template from this prompt resource with the given inputs.

This is the main method for using PromptUKFT resources. It loads the appropriate Jinja2 environment, retrieves the specified template, and renders it with the provided keyword arguments.

参数:
  • path (str, optional) -- Path to the prompt folder containing .jinja templates.

  • entry (str) -- Default template to use for prompt composer. Defaults to None, which falls back to the "default_entry" in content_resources.

  • name (str, optional) -- PromptUKFT resource name. If None and path is a directory, generates name from the basename of the path. Required if path is a file.

  • lang (str, optional) -- Language code for this rendering. If None, uses the default language from content_resources or config.

  • **kwargs -- Template variables passed to the Jinja2 template for rendering.

返回:

Rendered template string.

返回类型:

str

抛出:
  • ValueError -- If the prompt resource has no path specified.

  • TemplateNotFound -- If the specified template entry file doesn't exist.

示例

>>> prompt = PromptUKFT.from_path("& prompts/autocode")
>>> result = prompt.render(
...     code="def add(a, b): return a + b",
...     examples=[{"inputs": {"a": 1, "b": 2}, "output": 3}],
...     hints=["Use simple arithmetic"]
... )
format(composer='default', **kwargs)[源代码]
返回类型:

str

参数:

composer (str | Callable | None)

list_templates()[源代码]

List all available .jinja template files in this prompt resource.

返回:

Sorted list of template filenames (excluding files starting with '_').

返回类型:

List[str]

示例

>>> prompt = PromptUKFT.from_path("& prompts/autocode")
>>> prompt.list_templates()
['default.jinja']
model_config = {'validate_assignment': True, 'validate_default': True}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

model_post_init(context, /)

This function is meant to behave like a BaseModel method to initialise private attributes.

It takes context as an argument since that's what pydantic-core passes when calling it.

参数:
  • self (BaseModel) -- The BaseModel instance.

  • context (Any) -- The context.

返回类型:

None

ahvn.ukf.templates.basic.prompt.prompt_composer(kl, **kwargs)[源代码]

Compose a prompt by rendering the default entry template with provided inputs.

This composer allows a Prompt UKF instance to be called as a composer, automatically rendering the default entry template with the provided kwargs. This makes Prompt behave like a function.

To incorporate custom logic in prompt generation, consider creating a new composer function instead of manually rendering the prompt each time.

Recommended Knowledge Types:

PromptUKFT

参数:
  • kl (BaseUKF) -- Knowledge object containing prompt resource data.

  • **kwargs -- Template variables passed to the Jinja2 template for rendering.

返回:

Rendered prompt string.

返回类型:

str

示例

>>> kl.content_resources = {
...     "path": "prompts/autocode",
...     "entry": "default.jinja"
... }
>>> prompt_composer(kl, code="def add(a, b): ...", examples=[])
"You are a skillful Python expert..."
ahvn.ukf.templates.basic.prompt.prompt_list_composer(kl, ext='jinja;jinja2;j2;txt', **kwargs)[源代码]
参数:

ext (None | str | List[str])