Struct LlmPrompt

Source
pub struct LlmPrompt {
    pub local_prompt: Option<LocalPrompt>,
    pub api_prompt: Option<ApiPrompt>,
    pub messages: PromptMessages,
    pub concatenator: TextConcatenator,
    pub built_prompt_messages: Mutex<Option<Vec<HashMap<String, String>>>>,
}
Expand description

A prompt management system that supports both API-based LLMs (like OpenAI) and local LLMs.

LlmPrompt provides a unified interface for building and managing prompts in different formats, with support for both API-style messaging (system/user/assistant) and local LLM chat templates. It handles token counting, message validation, and proper prompt formatting.

Fields§

§local_prompt: Option<LocalPrompt>§api_prompt: Option<ApiPrompt>§messages: PromptMessages§concatenator: TextConcatenator§built_prompt_messages: Mutex<Option<Vec<HashMap<String, String>>>>

Implementations§

Source§

impl LlmPrompt

Source

pub fn new_local_prompt( tokenizer: Arc<dyn PromptTokenizer>, chat_template: &str, bos_token: Option<&str>, eos_token: &str, unk_token: Option<&str>, base_generation_prefix: Option<&str>, ) -> LlmPrompt

Creates a new prompt instance configured for local LLMs using chat templates.

§Arguments
  • tokenizer - A tokenizer implementation for counting tokens
  • chat_template - The chat template string used to format messages
  • bos_token - Optional beginning of sequence token
  • eos_token - End of sequence token
  • unk_token - Optional unknown token
  • base_generation_prefix - Optional prefix to add before generation
§Returns

A new LlmPrompt instance configured for local LLM usage.

Source

pub fn new_api_prompt( tokenizer: Arc<dyn PromptTokenizer>, tokens_per_message: Option<u32>, tokens_per_name: Option<i32>, ) -> LlmPrompt

Creates a new prompt instance configured for API-based LLMs like OpenAI.

§Arguments
  • tokenizer - A tokenizer implementation for counting tokens
  • tokens_per_message - Optional number of tokens to add per message (model-specific)
  • tokens_per_name - Optional number of tokens to add for names (model-specific)
§Returns

A new LlmPrompt instance configured for API usage.

Source

pub fn add_system_message(&self) -> Result<Arc<PromptMessage>, Error>

Adds a system message to the prompt.

System messages must be the first message in the sequence. Returns an error if attempting to add a system message after other messages.

§Returns

A reference to the newly created message for setting content, or an error if validation fails.

Source

pub fn add_user_message(&self) -> Result<Arc<PromptMessage>, Error>

Adds a user message to the prompt.

Cannot add a user message directly after another user message. Returns an error if attempting to add consecutive user messages.

§Returns

A reference to the newly created message for setting content, or an error if validation fails.

Source

pub fn add_assistant_message(&self) -> Result<Arc<PromptMessage>, Error>

Adds an assistant message to the prompt.

Cannot be the first message or follow another assistant message. Returns an error if attempting to add as first message or after another assistant message.

§Returns

A reference to the newly created message for setting content, or an error if validation fails.

Source

pub fn set_generation_prefix<T>(&self, generation_prefix: T)
where T: AsRef<str>,

Sets a prefix to be added before generation for local LLMs.

This is typically used to prime the model’s response. Only applies to local LLM prompts, has no effect on API prompts.

§Arguments
  • generation_prefix - The text to add before generation
Source

pub fn clear_generation_prefix(&self)

Clears any previously set generation prefix.

Source

pub fn reset_prompt(&self)

Resets the prompt, clearing all messages and built state.

Source

pub fn clear_built_prompt(&self)

Clears any built prompt state, forcing a rebuild on next access.

Source

pub fn local_prompt(&self) -> Result<&LocalPrompt, Error>

Gets and builds the local prompt if this is prompt has one. This method is required to unwrap the prompt and build it.

§Returns

A reference to the LocalPrompt if present, otherwise returns an error

Source

pub fn api_prompt(&self) -> Result<&ApiPrompt, Error>

Gets and builds the API prompt if this is prompt has one. This method is required to unwrap the prompt and build it.

§Returns

A reference to the ApiPrompt if present, otherwise returns an error

Source

pub fn get_built_prompt_messages( &self, ) -> Result<Vec<HashMap<String, String>>, Error>

Retrieves the prompt messages in a standardized format compatible with API calls.

This method returns messages in the same format as ApiPrompt::get_built_prompt(), making it useful for consistent message handling across different LLM implementations. The method handles lazy building of the prompt - if the messages haven’t been built yet, it will trigger the build process automatically.

§Returns

Returns Ok(Vec<HashMap<String, String>>) containing the formatted messages on success.

§Errors

Returns an error if:

  • The current message sequence violates prompt rules (e.g., assistant message first)
  • The build process fails
  • The built messages are unexpectedly None after building

Trait Implementations§

Source§

impl Clone for LlmPrompt

Source§

fn clone(&self) -> LlmPrompt

Returns a copy of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Default for LlmPrompt

Source§

fn default() -> LlmPrompt

Returns the “default value” for a type. Read more
Source§

impl Display for LlmPrompt

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>

Formats the value using the given formatter. Read more
Source§

impl Serialize for LlmPrompt

Source§

fn serialize<__S>( &self, __serializer: __S, ) -> Result<<__S as Serializer>::Ok, <__S as Serializer>::Error>
where __S: Serializer,

Serialize this value into the given Serde serializer. Read more
Source§

impl TextConcatenatorTrait for LlmPrompt

Source§

fn concatenator_mut(&mut self) -> &mut TextConcatenator

Provides mutable access to the concatenator.
Source§

fn clear_built(&self)

Clears any built content when concatenation rules change.
Source§

fn concate_deol(&mut self) -> &mut Self

Sets double newline concatenation (“\n\n”). Read more
Source§

fn concate_seol(&mut self) -> &mut Self

Sets single newline concatenation (“\n”). Read more
Source§

fn concate_space(&mut self) -> &mut Self

Sets space concatenation (“ “). Read more
Source§

fn concate_comma(&mut self) -> &mut Self

Sets comma concatenation (“, “). Read more
Source§

fn concate_custom<T>(&mut self, custom: T) -> &mut Self
where T: AsRef<str>,

Sets custom concatenation with the provided separator. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

impl<T> Pointable for T

Source§

const ALIGN: usize

The alignment of pointer.
Source§

type Init = T

The type for initializers.
Source§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
Source§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
Source§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
Source§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T> ToString for T
where T: Display + ?Sized,

Source§

fn to_string(&self) -> String

Converts the given value to a String. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V

Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

impl<T> ErasedDestructor for T
where T: 'static,