Module: Prompt

class diskurs.prompt.BasePrompt

Bases: Prompt

__init__(agent_description, system_template, user_template, prompt_argument_class, return_json=True, json_formatting_template=None, is_valid=None, is_final=None)
Parameters:
  • agent_description (str)

  • system_template (Template)

  • user_template (Template)

  • prompt_argument_class (Type[PromptArg])

  • return_json (bool)

  • json_formatting_template (Template | None)

  • is_valid (Callable[[Any], bool] | None)

  • is_final (Callable[[Any], bool] | None)

agent_description: str
classmethod create(location, **kwargs)
Parameters:

location (Path)

Return type:

Self

classmethod create_default_is_final(**kwargs)
Return type:

Callable[[PromptArg], bool]

classmethod create_default_is_valid(**kwargs)
Return type:

Callable[[PromptArg], bool]

create_prompt_argument(**prompt_args)

Creates an instance of the prompt argument dataclass.

This method instantiates a prompt argument dataclass with the provided keyword arguments, which will be used to render templates and structure conversation data.

Parameters:

prompt_args (dict) – Keyword arguments used to initialize the prompt argument.

Returns:

An instance of the prompt argument dataclass.

Return type:

PromptArg

initialize_prompt(agent_name, conversation, locked_fields=None, init_from_longterm_memory=True, reset_prompt=True, message_type=MessageType.CONVERSATION, render_system_prompt=True)

Initialize prompt arguments from global longterm memory and set up the conversation.

This method handles initialization for all agent types: - Regular agents with system and user prompts (default) - Conductor agents (using MessageType.CONDUCTOR) - Heuristic agents (without system prompts)

Parameters:
  • agent_name (str) – The name of the agent

  • conversation (Conversation) – The conversation to initialize

  • locked_fields (dict[str, Any] | None) – Dictionary of fields that should be locked to specific values

  • init_from_longterm_memory (bool) – Whether to initialize from longterm memory

  • reset_prompt (bool) – Whether to reset the prompt or use conversation’s existing prompt

  • message_type (MessageType) – The message type to use (CONVERSATION or CONDUCTOR)

  • render_system_prompt (bool) – Whether to render a system prompt

Returns:

Initialized conversation

Return type:

Conversation

is_final(prompt_argument)

Determines if the prompt argument represents the final state of a conversation.

This method evaluates whether the current prompt argument indicates that the conversation has reached its conclusion and no further processing is needed.

Parameters:

prompt_argument (PromptArgument) – The prompt argument to evaluate.

Returns:

True if the conversation should be considered complete, False otherwise.

Return type:

bool

is_valid(prompt_argument)

Validates the prompt argument against expected criteria.

This method checks if the prompt argument contains all required fields with appropriate values. It may raise a PromptValidationError if validation fails.

Parameters:

prompt_argument (PromptArgument) – The prompt argument to validate.

Returns:

True if the prompt argument is valid, False otherwise.

Return type:

bool

json_formatting_template: Template | None
classmethod load_additional_resources(module, kwargs)

Load additional resources specific to subclasses. Override in subclasses if needed.

Parameters:
  • module (Any)

  • kwargs (dict)

Return type:

dict

classmethod load_templates(location, system_template_filename, user_template_filename, kwargs)

Load templates with default fallback options. Override in subclasses if needed.

Parameters:
  • location (Path)

  • system_template_filename (str)

  • user_template_filename (str)

  • kwargs (dict)

Return type:

tuple[Template, Template]

parse_user_prompt(name, llm_response, old_prompt_argument, message_type=MessageType.CONDUCTOR)

Parse the text returned from the LLM into a structured prompt argument. First validate the text, then parse it into the prompt argument. If the text is not valid, raise a PromptValidationError, and generate a user prompt with the error message, for the LLM to correct its output.

Parameters:
  • name (str) – Name of the agent.

  • llm_response (str) – Response from the LLM.

  • old_prompt_argument (PromptArgument) – The previous user prompt argument.

  • message_type (MessageType) – Type of message to be created.

Returns:

Validated prompt argument or a ChatMessage with an error message.

Raises:

PromptValidationError – If the text is not valid.

Return type:

PromptArgument | ChatMessage

prompt_argument: Type[PromptArgument]
render_json_formatting_prompt(prompt_argument)

Render the JSON formatting template with included fields.

This method analyzes the structure of the prompt_argument class and generates a representative JSON example that shows the expected structure, including nested dataclasses and lists of dataclasses.

Parameters:
  • prompt_args – Dictionary of prompt arguments to be filtered and rendered.

  • prompt_argument (PromptArgument)

Returns:

The rendered JSON formatting template.

Raises:

ValueError: If json_formatting_template is not set.

Return type:

str

render_system_template(name, prompt_argument, return_json=True)

Renders the system template with the provided prompt arguments.

This method generates a system message that provides context and instructions to guide the language model’s responses. It can optionally append JSON formatting instructions to help the model produce structured outputs.

Parameters:
  • name (str) – The name of the agent for which the template is being rendered.

  • prompt_argument (PromptArgument) – The prompt arguments to use for rendering.

  • return_json (bool) – Whether to include JSON formatting instructions.

Returns:

A ChatMessage object containing the rendered system prompt.

Return type:

ChatMessage

render_user_template(name, prompt_args, message_type=MessageType.CONVERSATION)

Renders the user template with the provided prompt arguments.

This method generates a ChatMessage using prompt arguments to populate the user template. The rendered template becomes part of the conversation flow, representing either a system instruction or user input.

Parameters:
  • name (str) – The name of the agent for which the template is being rendered.

  • prompt_args (PromptArgument) – The prompt arguments to use for rendering.

  • message_type (MessageType) – The type of message to generate (defaults to CONVERSATION).

Returns:

A ChatMessage object containing the rendered content.

Return type:

ChatMessage

classmethod safe_load_predicates(is_final_name, is_valid_name, module, **kwargs)
system_template: Template
user_template: Template
class diskurs.prompt.ConductorPrompt

Bases: BasePrompt, ConductorPrompt

__init__(agent_description, system_template, user_template, prompt_argument_class, json_formatting_template=None, is_valid=None, is_final=None, can_finalize=None, finalize=None, fail=None)
Parameters:
  • agent_description (str)

  • system_template (Template)

  • user_template (Template)

  • prompt_argument_class (Type[PromptArg])

  • json_formatting_template (Template | None)

  • is_valid (Callable[[Any], bool] | None)

  • is_final (Callable[[Any], bool] | None)

  • can_finalize (Callable[[Any], bool])

  • finalize (Callable[[Any], Any])

  • fail (Callable[[Any], Any])

agent_description: str
can_finalize(longterm_memory)

Determines if the conductor can finalize based on the long-term memory.

This method evaluates the provided long-term memory to decide whether the conversation can be concluded. It checks if the necessary conditions are met for finalizing the conversation.

Parameters:

longterm_memory (LongtermMemory) – The long-term memory to be evaluated.

Returns:

True if the conversation can be finalized, False otherwise.

Return type:

bool

classmethod create(location, **kwargs)

Override BasePrompt.create to use default conductor prompt argument classes when needed.

Parameters:

location (Path)

Return type:

Self

static create_default_is_final(**kwargs)
Return type:

Callable[[PromptArg], bool]

static create_default_is_valid(**kwargs)
Return type:

Callable[[PromptArg], bool]

create_prompt_argument(**prompt_args)

Creates an instance of the prompt argument dataclass.

This method instantiates a prompt argument dataclass with the provided keyword arguments, which will be used to render templates and structure conversation data.

Parameters:

prompt_args (dict) – Keyword arguments used to initialize the prompt argument.

Returns:

An instance of the prompt argument dataclass.

Return type:

PromptArg

fail(longterm_memory)

Handles the case of failure when the long-term memory does not meet the criteria defined for finalization.

This method processes the provided long-term memory to generate a failure response for the conversation. It is responsible for concluding the conversation in a failure state by utilizing the accumulated long-term memory data.

Parameters:

longterm_memory (LongtermMemory) – The long-term memory to be used for generating the failure response.

Returns:

A dictionary containing the failure response data.

Return type:

LongtermMemory

finalize(longterm_memory)

Finalizes the conversation based on the long-term memory.

This method processes the provided long-term memory to generate a final response for the conversation. It is responsible for concluding the conversation by utilizing the accumulated long-term memory data.

Parameters:

longterm_memory (LongtermMemory) – The long-term memory to be used for finalizing the conversation.

Returns:

A dictionary containing the final response data.

Return type:

LongtermMemory

init_longterm_memory(**kwargs)

Initializes the long-term memory.

This method is responsible for creating and initializing the long-term memory for the conductor agent. It uses the provided keyword arguments to set up the initial state of the long-term memory.

Parameters:

kwargs (Any) – Keyword arguments used to initialize the long-term memory.

Returns:

An instance of the LongtermMemory class.

Return type:

LongtermMemory

initialize_prompt(agent_name, conversation, locked_fields=None, init_from_longterm_memory=True, reset_prompt=True, message_type=MessageType.CONVERSATION, render_system_prompt=True)

Initialize prompt arguments from global longterm memory and set up the conversation.

This method handles initialization for all agent types: - Regular agents with system and user prompts (default) - Conductor agents (using MessageType.CONDUCTOR) - Heuristic agents (without system prompts)

Parameters:
  • agent_name (str) – The name of the agent

  • conversation (Conversation) – The conversation to initialize

  • locked_fields (dict[str, Any] | None) – Dictionary of fields that should be locked to specific values

  • init_from_longterm_memory (bool) – Whether to initialize from longterm memory

  • reset_prompt (bool) – Whether to reset the prompt or use conversation’s existing prompt

  • message_type (MessageType) – The message type to use (CONVERSATION or CONDUCTOR)

  • render_system_prompt (bool) – Whether to render a system prompt

Returns:

Initialized conversation

Return type:

Conversation

is_final(prompt_argument)

Determines if the prompt argument represents the final state of a conversation.

This method evaluates whether the current prompt argument indicates that the conversation has reached its conclusion and no further processing is needed.

Parameters:

prompt_argument (PromptArgument) – The prompt argument to evaluate.

Returns:

True if the conversation should be considered complete, False otherwise.

Return type:

bool

is_valid(prompt_argument)

Validates the prompt argument against expected criteria.

This method checks if the prompt argument contains all required fields with appropriate values. It may raise a PromptValidationError if validation fails.

Parameters:

prompt_argument (PromptArgument) – The prompt argument to validate.

Returns:

True if the prompt argument is valid, False otherwise.

Return type:

bool

json_formatting_template: Template | None
classmethod load_additional_resources(module, kwargs)

Modified to provide default implementations for conductor resources.

Parameters:
  • module (Any)

  • kwargs (dict)

Return type:

dict

classmethod load_templates(location, system_template_filename, user_template_filename, kwargs)

Load templates with default fallback options. Override in subclasses if needed.

Parameters:
  • location (Path)

  • system_template_filename (str)

  • user_template_filename (str)

  • kwargs (dict)

Return type:

tuple[Template, Template]

longterm_memory: Type[LongtermMemory]
parse_user_prompt(name, llm_response, old_prompt_argument, message_type=MessageType.CONDUCTOR)

Parse the text returned from the LLM into a structured prompt argument. First validate the text, then parse it into the prompt argument. If the text is not valid, raise a PromptValidationError, and generate a user prompt with the error message, for the LLM to correct its output.

Parameters:
  • name (str) – Name of the agent.

  • llm_response (str) – Response from the LLM.

  • old_prompt_argument (PromptArgument) – The previous user prompt argument.

  • message_type (MessageType) – Type of message to be created.

Returns:

Validated prompt argument or a ChatMessage with an error message.

Raises:

PromptValidationError – If the text is not valid.

Return type:

PromptArgument | ChatMessage

prompt_argument: Type[PromptArgument]
render_json_formatting_prompt(prompt_argument)

Render the JSON formatting template with included fields.

This method analyzes the structure of the prompt_argument class and generates a representative JSON example that shows the expected structure, including nested dataclasses and lists of dataclasses.

Parameters:
  • prompt_args – Dictionary of prompt arguments to be filtered and rendered.

  • prompt_argument (PromptArgument)

Returns:

The rendered JSON formatting template.

Raises:

ValueError: If json_formatting_template is not set.

Return type:

str

render_system_template(name, prompt_argument, return_json=True)

Renders the system template with the provided prompt arguments.

This method is responsible for rendering the system template using the given prompt arguments. It can optionally append JSON formatting instructions to the rendered template.

Parameters:
  • name (str) – The name of the agent for which the template is being rendered.

  • prompt_argument (PromptArgument) – The prompt arguments to be used for rendering the template.

  • return_json (bool) – Whether to include JSON formatting instructions.

Returns:

A ChatMessage object containing the rendered template.

Return type:

ChatMessage

render_user_template(name, prompt_args, message_type=MessageType.CONVERSATION)

Renders the user template with the provided prompt arguments.

This method generates a ChatMessage using prompt arguments to populate the user template. The rendered template becomes part of the conversation flow, representing either a system instruction or user input.

Parameters:
  • name (str) – The name of the agent for which the template is being rendered.

  • prompt_args (PromptArgument) – The prompt arguments to use for rendering.

  • message_type (MessageType) – The type of message to generate (defaults to CONVERSATION).

Returns:

A ChatMessage object containing the rendered content.

Return type:

ChatMessage

classmethod safe_load_predicates(is_final_name, is_valid_name, module, **kwargs)
system_template: Template
user_template: Template
class diskurs.prompt.DefaultConductorPromptArgument

Bases: PromptArgument

DefaultConductorPromptArgument(agent_descriptions: Annotated[Optional[dict[str, str]], PromptField(access_mode=’locked’)] = None, next_agent: Annotated[str, PromptField(access_mode=’output’)] = ‘’)

__init__(agent_descriptions=None, next_agent='')
Parameters:
  • agent_descriptions (Annotated[dict[str, str] | None, PromptField(access_mode='locked')])

  • next_agent (Annotated[str, PromptField(access_mode='output')])

Return type:

None

agent_descriptions: Annotated[dict[str, str] | None, PromptField(access_mode='locked')] = None
classmethod from_dict(data)
get_output_fields()

Returns a dictionary containing only the fields that should be included in JSON output. This includes fields with OutputField annotation and fields with no specific annotation.

Returns:

Dictionary of field names to values that should be included in output

Return type:

dict[str, Any]

init(source)

Initialize a new instance by reading the fields of another PromptArgument or LongtermMemory. Only fields of type InputField will be copied from the source.

Parameters:

source (PromptArgument | LongtermMemory) – The source object to copy fields from

Returns:

A new instance with InputField values copied from source

Return type:

PromptArgument

next_agent: Annotated[str, PromptField(access_mode='output')] = ''
to_dict()
update(other)

Return a new instance with all non-locked/non-input fields taken from other.

Parameters:

other (PromptArgument)

Return type:

PromptArgument

class diskurs.prompt.HeuristicPrompt

Bases: BasePrompt, HeuristicPrompt

__init__(prompt_argument_class, heuristic_sequence, user_template=None, agent_description='')
Parameters:
agent_description: str
classmethod create(location, **kwargs)
Parameters:

location (Path)

Return type:

Self

classmethod create_default_is_final(**kwargs)
Return type:

Callable[[PromptArg], bool]

classmethod create_default_is_valid(**kwargs)
Return type:

Callable[[PromptArg], bool]

create_prompt_argument(**prompt_args)

Creates an instance of the prompt argument dataclass.

This method instantiates a prompt argument dataclass with the provided keyword arguments, which will be used to render templates and structure conversation data.

Parameters:

prompt_args – Keyword arguments used to initialize the prompt argument.

Returns:

An instance of the prompt argument dataclass.

Return type:

PromptArg

async heuristic_sequence(conversation, call_tool, llm_client)

Executes a heuristic sequence on the given conversation.

This method processes the conversation using a series of heuristic steps, utilizing a tool caller and optionally an LLM client. The heuristic sequence is designed to guide the conversation towards a desired outcome based on predefined rules and logic.

Parameters:
  • conversation (Conversation) – The conversation object to be processed.

  • call_tool (CallTool | None) – A callable tool function that can be used during the heuristic sequence.

  • llm_client (LLMClient) – Optional LLM client that can be used for generating responses within the sequence.

Returns:

The updated conversation object after processing the heuristic sequence.

Return type:

Conversation

initialize_prompt(agent_name, conversation, locked_fields=None, init_from_longterm_memory=True, reset_prompt=True, message_type=MessageType.CONVERSATION, render_system_prompt=True)

Initialize prompt arguments from global longterm memory and set up the conversation.

This method handles initialization for all agent types: - Regular agents with system and user prompts (default) - Conductor agents (using MessageType.CONDUCTOR) - Heuristic agents (without system prompts)

Parameters:
  • agent_name (str) – The name of the agent

  • conversation (Conversation) – The conversation to initialize

  • locked_fields (dict[str, Any] | None) – Dictionary of fields that should be locked to specific values

  • init_from_longterm_memory (bool) – Whether to initialize from longterm memory

  • reset_prompt (bool) – Whether to reset the prompt or use conversation’s existing prompt

  • message_type (MessageType) – The message type to use (CONVERSATION or CONDUCTOR)

  • render_system_prompt (bool) – Whether to render a system prompt

Returns:

Initialized conversation

Return type:

Conversation

is_final(prompt_argument)

Determines if the prompt argument represents the final state of a conversation.

This method evaluates whether the current prompt argument indicates that the conversation has reached its conclusion and no further processing is needed.

Parameters:

prompt_argument (PromptArgument) – The prompt argument to evaluate.

Returns:

True if the conversation should be considered complete, False otherwise.

Return type:

bool

is_valid(prompt_argument)

Validates the prompt argument against expected criteria.

This method checks if the prompt argument contains all required fields with appropriate values. It may raise a PromptValidationError if validation fails.

Parameters:

prompt_argument (PromptArgument) – The prompt argument to validate.

Returns:

True if the prompt argument is valid, False otherwise.

Return type:

bool

json_formatting_template: Template | None
classmethod load_additional_resources(module, kwargs)

Load additional resources specific to subclasses. Override in subclasses if needed.

Parameters:
  • module (Any)

  • kwargs (dict)

Return type:

dict

classmethod load_templates(location, system_template_filename, user_template_filename, kwargs)

Load templates with default fallback options. Override in subclasses if needed.

Parameters:
  • location (Path)

  • system_template_filename (str)

  • user_template_filename (str)

  • kwargs (dict)

Return type:

tuple[Template, Template]

parse_user_prompt(name, llm_response, old_prompt_argument, message_type=MessageType.CONDUCTOR)

Parse the text returned from the LLM into a structured prompt argument. First validate the text, then parse it into the prompt argument. If the text is not valid, raise a PromptValidationError, and generate a user prompt with the error message, for the LLM to correct its output.

Parameters:
  • name (str) – Name of the agent.

  • llm_response (str) – Response from the LLM.

  • old_prompt_argument (PromptArgument) – The previous user prompt argument.

  • message_type (MessageType) – Type of message to be created.

Returns:

Validated prompt argument or a ChatMessage with an error message.

Raises:

PromptValidationError – If the text is not valid.

Return type:

PromptArgument | ChatMessage

prompt_argument: Type[PromptArgument]
render_json_formatting_prompt(prompt_argument)

Render the JSON formatting template with included fields.

This method analyzes the structure of the prompt_argument class and generates a representative JSON example that shows the expected structure, including nested dataclasses and lists of dataclasses.

Parameters:
  • prompt_args – Dictionary of prompt arguments to be filtered and rendered.

  • prompt_argument (PromptArgument)

Returns:

The rendered JSON formatting template.

Raises:

ValueError: If json_formatting_template is not set.

Return type:

str

render_system_template(name, prompt_argument, return_json=True)

Renders the system template with the provided prompt arguments.

This method generates a system message that provides context and instructions to guide the language model’s responses. It can optionally append JSON formatting instructions to help the model produce structured outputs.

Parameters:
  • name (str) – The name of the agent for which the template is being rendered.

  • prompt_argument (PromptArgument) – The prompt arguments to use for rendering.

  • return_json (bool) – Whether to include JSON formatting instructions.

Returns:

A ChatMessage object containing the rendered system prompt.

Return type:

ChatMessage

render_user_template(name, prompt_args, message_type=MessageType.CONVERSATION)

Renders the user template with the provided prompt arguments.

This method generates a ChatMessage using prompt arguments to populate the user template. The rendered template becomes part of the conversation flow, representing either a system instruction or user input.

Parameters:
  • name (str) – The name of the agent for which the template is being rendered.

  • prompt_args (PromptArgument) – The prompt arguments to use for rendering.

  • message_type (MessageType) – The type of message to generate (defaults to CONVERSATION).

Returns:

A ChatMessage object containing the rendered content.

Return type:

ChatMessage

classmethod safe_load_predicates(is_final_name, is_valid_name, module, **kwargs)
system_template: Template
user_template: Template
class diskurs.prompt.MultistepPrompt

Bases: BasePrompt, MultistepPrompt

__init__(agent_description, system_template, user_template, prompt_argument_class, return_json=True, json_formatting_template=None, is_valid=None, is_final=None)
Parameters:
  • agent_description (str)

  • system_template (Template)

  • user_template (Template)

  • prompt_argument_class (Type[PromptArg])

  • return_json (bool)

  • json_formatting_template (Template | None)

  • is_valid (Callable[[Any], bool] | None)

  • is_final (Callable[[Any], bool] | None)

agent_description: str
classmethod create(location, **kwargs)
Parameters:

location (Path)

Return type:

Self

classmethod create_default_is_final(**kwargs)
Return type:

Callable[[PromptArg], bool]

classmethod create_default_is_valid(**kwargs)
Return type:

Callable[[PromptArg], bool]

create_prompt_argument(**prompt_args)

Creates an instance of the prompt argument dataclass.

This method instantiates a prompt argument dataclass with the provided keyword arguments, which will be used to render templates and structure conversation data.

Parameters:

prompt_args (dict) – Keyword arguments used to initialize the prompt argument.

Returns:

An instance of the prompt argument dataclass.

Return type:

PromptArg

initialize_prompt(agent_name, conversation, locked_fields=None, init_from_longterm_memory=True, reset_prompt=True, message_type=MessageType.CONVERSATION, render_system_prompt=True)

Initialize prompt arguments from global longterm memory and set up the conversation.

This method handles initialization for all agent types: - Regular agents with system and user prompts (default) - Conductor agents (using MessageType.CONDUCTOR) - Heuristic agents (without system prompts)

Parameters:
  • agent_name (str) – The name of the agent

  • conversation (Conversation) – The conversation to initialize

  • locked_fields (dict[str, Any] | None) – Dictionary of fields that should be locked to specific values

  • init_from_longterm_memory (bool) – Whether to initialize from longterm memory

  • reset_prompt (bool) – Whether to reset the prompt or use conversation’s existing prompt

  • message_type (MessageType) – The message type to use (CONVERSATION or CONDUCTOR)

  • render_system_prompt (bool) – Whether to render a system prompt

Returns:

Initialized conversation

Return type:

Conversation

is_final(prompt_argument)

Determines if the prompt argument represents the final state of a conversation.

This method evaluates whether the current prompt argument indicates that the conversation has reached its conclusion and no further processing is needed.

Parameters:

prompt_argument (PromptArgument) – The prompt argument to evaluate.

Returns:

True if the conversation should be considered complete, False otherwise.

Return type:

bool

is_valid(prompt_argument)

Validates the prompt argument against expected criteria.

This method checks if the prompt argument contains all required fields with appropriate values. It may raise a PromptValidationError if validation fails.

Parameters:

prompt_argument (PromptArgument) – The prompt argument to validate.

Returns:

True if the prompt argument is valid, False otherwise.

Return type:

bool

json_formatting_template: Template | None
classmethod load_additional_resources(module, kwargs)

Load additional resources specific to subclasses. Override in subclasses if needed.

Parameters:
  • module (Any)

  • kwargs (dict)

Return type:

dict

classmethod load_templates(location, system_template_filename, user_template_filename, kwargs)

Load templates with default fallback options. Override in subclasses if needed.

Parameters:
  • location (Path)

  • system_template_filename (str)

  • user_template_filename (str)

  • kwargs (dict)

Return type:

tuple[Template, Template]

parse_user_prompt(name, llm_response, old_prompt_argument, message_type=MessageType.CONDUCTOR)

Parse the text returned from the LLM into a structured prompt argument. First validate the text, then parse it into the prompt argument. If the text is not valid, raise a PromptValidationError, and generate a user prompt with the error message, for the LLM to correct its output.

Parameters:
  • name (str) – Name of the agent.

  • llm_response (str) – Response from the LLM.

  • old_prompt_argument (PromptArgument) – The previous user prompt argument.

  • message_type (MessageType) – Type of message to be created.

Returns:

Validated prompt argument or a ChatMessage with an error message.

Raises:

PromptValidationError – If the text is not valid.

Return type:

PromptArgument | ChatMessage

prompt_argument: Type[PromptArgument]
render_json_formatting_prompt(prompt_argument)

Render the JSON formatting template with included fields.

This method analyzes the structure of the prompt_argument class and generates a representative JSON example that shows the expected structure, including nested dataclasses and lists of dataclasses.

Parameters:
  • prompt_args – Dictionary of prompt arguments to be filtered and rendered.

  • prompt_argument (PromptArgument)

Returns:

The rendered JSON formatting template.

Raises:

ValueError: If json_formatting_template is not set.

Return type:

str

render_system_template(name, prompt_argument, return_json=True)

Renders the system template with the provided prompt arguments.

This method generates a system message that provides context and instructions to guide the language model’s responses. It can optionally append JSON formatting instructions to help the model produce structured outputs.

Parameters:
  • name (str) – The name of the agent for which the template is being rendered.

  • prompt_argument (PromptArgument) – The prompt arguments to use for rendering the template.

  • return_json (bool) – Whether to include JSON formatting instructions.

Returns:

A ChatMessage object containing the rendered system prompt.

Return type:

ChatMessage

render_user_template(name, prompt_args, message_type=MessageType.CONVERSATION)

Renders the user template with the provided prompt arguments.

This method generates a ChatMessage using prompt arguments to populate the user template. The rendered template becomes part of the conversation flow, representing either a system instruction or user input.

Parameters:
  • name (str) – The name of the agent for which the template is being rendered.

  • prompt_args (PromptArgument) – The prompt arguments to use for rendering.

  • message_type (MessageType) – The type of message to generate (defaults to CONVERSATION).

Returns:

A ChatMessage object containing the rendered content.

Return type:

ChatMessage

classmethod safe_load_predicates(is_final_name, is_valid_name, module, **kwargs)
system_template: Template
user_template: Template
diskurs.prompt.always_false(*args, **kwargs)
Return type:

bool

diskurs.prompt.always_true(*args, **kwargs)
Return type:

bool

diskurs.prompt.clean_json_string(text)

Clean and sanitize a JSON string from common LLM response issues.

The following steps are applied:

  1. Remove triple-backtick code fences (optionally with “json”).

  2. Normalize curly quotes to straight quotes.

  3. Remove trailing commas in objects/arrays.

  4. Remove extraneous text before the first ‘{’ or ‘[’ and after the last ‘}’ or ‘]’.

  5. Remove carriage returns.

  6. Escape literal newlines found within JSON string values.

Parameters:

text (str) – Raw JSON string (possibly wrapped in code fences and containing unescaped newlines).

Returns:

A cleaned JSON string.

Return type:

str

diskurs.prompt.escape_newlines_in_json_string(text)

Iterate through the text and, while inside a JSON string literal, replace literal newline characters with the escape sequence “n”. This prevents JSON from choking on unescaped newline characters that may occur within a string value.

Parameters:

text (str)

Return type:

str

diskurs.prompt.load_template(location)

Loads a Jinja2 template from the provided file path.

Parameters:

location (Path) – Path to the template file.

Returns:

Jinja2 Template object.

Raises:

FileNotFoundError – If the template file does not exist.

Return type:

Template

diskurs.prompt.validate_dataclass(parsed_response, prompt_argument)

Validate and convert a dictionary to a dataclass instance with proper type coercion.

Parameters:
  • parsed_response (dict[str, Any])

  • prompt_argument (Type[GenericDataclass])

Return type:

GenericDataclass

diskurs.prompt.validate_json(llm_response, max_depth=5, max_size=1000000)

Parse and validate the LLM response as JSON, applying several cleaning steps to handle common formatting issues.

If json.loads fails, the function cleans the response and tries parsing again, up to a maximum recursion depth.

Parameters:
  • llm_response (str) – Raw text response from the LLM.

  • max_depth (int) – Maximum recursion depth for nested cleaning/parsing attempts.

  • max_size (int) – Maximum allowed size (in characters) for the JSON string.

Returns:

A parsed Python dictionary or list.

Raises:

PromptValidationError – If the response is too large, too deeply nested, or ultimately invalid.

Return type:

dict | list