prompt_builder#

Class prompt builder for LightRAG system prompt.

Classes

Prompt([template, prompt_kwargs])

Renders a text string(prompt) from a Jinja2 template string.

class Prompt(template: str | None = None, prompt_kwargs: Dict[str, Parameter] | None = {})[source]#

Bases: Component

Renders a text string(prompt) from a Jinja2 template string.

In default, we use the DEFAULT_LIGHTRAG_SYSTEM_PROMPT as the template.

Parameters:
  • template (str, optional) – The Jinja2 template string. Defaults to DEFAULT_LIGHTRAG_SYSTEM_PROMPT.

  • preset_prompt_kwargs (Optional[Dict], optional) – The preset prompt kwargs to fill in the variables in the prompt. Defaults to {}.

Examples

>>> from core.prompt_builder import Prompt
>>> prompt = Prompt(prompt_kwargs={"task_desc_str": "You are a helpful assistant."})
>>> print(prompt)
>>> prompt.print_prompt_template()
>>> prompt.print_prompt(context_str="This is a context string.")
>>> prompt.call(context_str="This is a context string.")

When examples_str itself is another template with variables, You can use another Prompt to render it.

>>> EXAMPLES_TEMPLATE = r'''
>>> {% if examples %}
>>> {% for example in examples %}
>>> {{loop.index}}. {{example}}
>>> {% endfor %}
>>> {% endif %}
>>> '''
>>> examples_prompt = Prompt(template=EXAMPLES_TEMPLATE)
>>> examples_str = examples_prompt.call(examples=["Example 1", "Example 2"])
>>> # pass it to the main prompt
>>> prompt.print_prompt(examples_str=examples_str)
update_prompt_kwargs(**kwargs)[source]#

Update the initial prompt kwargs after Prompt is initialized.

get_prompt_variables() List[str][source]#

Get the prompt kwargs.

is_key_in_template(key: str) bool[source]#

Check if the key exists in the template.

compose_prompt_kwargs(**kwargs) Dict[source]#

Compose the final prompt kwargs by combining the initial and the provided kwargs at runtime.

print_prompt_template()[source]#

Print the template string.

print_prompt(**kwargs) str[source]#

Print the rendered prompt string using the preset_prompt_kwargs and the provided kwargs.

call(**kwargs) str[source]#

Renders the prompt template with keyword arguments. Allow None values.

classmethod from_dict(data: Dict[str, Any]) T[source]#

Create an instance from previously serialized data using to_dict() method.

to_dict() Dict[str, Any][source]#

Get the dictionary representation of all the Prompt object’s attributes, with sorting applied to dictionary keys and list elements to ensure consistent ordering.

get_jinja2_environment()[source]#

Helper function for Prompt component to get the Jinja2 environment with the default settings.