MessageBuilder
The MessageBuilder
class simplifies the creation of messages with text, images, and file contents. This builder pattern makes it easy to construct complex messages with a fluent interface.
Usage Examples
Simple Image Analysis
This example shows how to analyze a single image using a multimodal LLM:
from mojentic.llm import LLMBroker
from mojentic.llm import MessageBuilder
from pathlib import Path
# Create an LLM broker with a multimodal model
llm = LLMBroker(model="gemma3:27b")
# Build a message with a single image
message = MessageBuilder("Please analyze this image and describe what you see:") \
.add_image(Path.cwd() / "images" / "flash_rom.jpg") \
.build()
# Generate a response
result = llm.generate(messages=[message])
print(result)
Comparing Two Images
This example demonstrates how to compare two images:
from mojentic.llm import LLMBroker
from mojentic.llm import MessageBuilder
from pathlib import Path
# Create an LLM broker
llm = LLMBroker(model="gemma3:27b")
# Build a message with two images for comparison
message = MessageBuilder("Compare these two images and tell me the differences:") \
.add_image(Path.cwd() / "images" / "image1.jpg") \
.add_image(Path.cwd() / "images" / "image2.jpg") \
.build()
# Generate a response
result = llm.generate(messages=[message])
print(result)
Converting Java to Kotlin
This example shows how to use an LLM to convert a Java file to Kotlin:
from mojentic.llm import LLMBroker
from mojentic.llm import MessageBuilder
from pathlib import Path
# Create an LLM broker
llm = LLMBroker(model="gemma3:27b")
# Build a message with a Java file
message = MessageBuilder("Convert this Java code to Kotlin, maintaining the same functionality:") \
.add_file(Path.cwd() / "src" / "example.java") \
.build()
# Generate a response
result = llm.generate(messages=[message])
print(result)
Processing Multiple Markdown Documents
This example demonstrates how to summarize the contents of multiple markdown documents in a folder:
from mojentic.llm import LLMBroker
from mojentic.llm import MessageBuilder
from pathlib import Path
# Create an LLM broker
llm = LLMBroker(model="gemma3:27b")
# Build a message with multiple markdown files from a folder
message = MessageBuilder("Summarize the key points from these markdown documents:") \
.add_files(Path.cwd() / "docs" / "*.md") \
.build()
# Generate a response
result = llm.generate(messages=[message])
print(result)
Loading Prompt Content from a File
This example shows how to load a prompt from a file instead of hardcoding it in your code:
from mojentic.llm import LLMBroker
from mojentic.llm import MessageBuilder
from pathlib import Path
# Create an LLM broker
llm = LLMBroker(model="gemma3:27b")
# Load prompt content from a file
message = MessageBuilder() \
.load_content(Path.cwd() / "prompts" / "code_review_prompt.txt") \
.add_file(Path.cwd() / "src" / "main.py") \
.build()
# Generate a response
result = llm.generate(messages=[message])
print(result)
Using Template Substitution in Prompts
This example demonstrates how to use template substitution when loading prompt content from a file:
from mojentic.llm import LLMBroker
from mojentic.llm import MessageBuilder
from pathlib import Path
# Create an LLM broker
llm = LLMBroker(model="gemma3:27b")
# Assume prompt_template.txt contains:
# "Please review this {language} code for {aspect} issues:"
# Load prompt content with template substitution
message = MessageBuilder() \
.load_content(
Path.cwd() / "prompts" / "prompt_template.txt",
template_values={"language": "Python", "aspect": "security"}
) \
.add_file(Path.cwd() / "src" / "main.py") \
.build()
# The prompt will become: "Please review this Python code for security issues:"
# Generate a response
result = llm.generate(messages=[message])
print(result)
Using File References as Template Values
This example shows how to use file references as template values, where the content of the referenced file is used for substitution:
from mojentic.llm import LLMBroker
from mojentic.llm import MessageBuilder
from pathlib import Path
# Create an LLM broker
llm = LLMBroker(model="gemma3:27b")
# Assume prompt_template.txt contains:
# "Please analyze this code according to these {guidelines}:"
# Assume guidelines.txt contains detailed code review guidelines
# Load prompt content with file reference as template value
message = MessageBuilder() \
.load_content(
Path.cwd() / "prompts" / "prompt_template.txt",
template_values={"guidelines": Path.cwd() / "prompts" / "guidelines.txt"}
) \
.add_file(Path.cwd() / "src" / "main.py") \
.build()
# The {guidelines} placeholder will be replaced with the entire content of guidelines.txt
# Generate a response
result = llm.generate(messages=[message])
print(result)
Important Considerations
LLM Context Size Limitations
When adding multiple files or large images to a message, be aware of LLM context size limitations:
- Context Window Limits: Each LLM has a maximum context window size (e.g., 8K, 16K, 32K tokens).
- Performance Impact: Adding too much data to messages will slow down the LLM's processing time.
- Request Failures: Exceeding the context limit will cause the request to fail with an error.
- Selective Content: Only include the most relevant files and images in your messages.
- File Size: Large files may need to be split or summarized before processing.
For large datasets: - Consider chunking files into smaller segments - Process files sequentially rather than all at once - Use specialized document processing tools for very large documents
Key Features
- Fluent Interface: Chain method calls for a clean, readable syntax
- Multiple Content Types: Add text, images, and files to a single message
- File Content Formatting: Automatically formats file contents with appropriate syntax highlighting
- Type Detection: Detects file types and applies appropriate language tags for code blocks
- Path Flexibility: Accepts both string paths and Path objects
Important Methods
- add_image(): Add a single image to the message
- add_images(): Add multiple images at once, with support for glob patterns
- add_file(): Add a single file's content to the message
- add_files(): Add multiple files at once, with support for glob patterns
- load_content(): Load content from a file into the message, replacing any existing content, with optional template value substitution
- build(): Create the final LLMMessage object to send to the LLM
API Reference
mojentic.llm.MessageBuilder
A builder class for creating LLM messages with text content, images, and files.
This class provides a fluent interface for constructing messages to be sent to an LLM, with support for adding text content, images, and file contents. It handles file reading, language detection for syntax highlighting, and proper formatting of the message.
Source code in src/mojentic/llm/message_composers.py
78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 |
|
__init__(content=None)
Initialize a new MessageBuilder with optional text content.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
content
|
str
|
Optional text content for the message. If None, the message will only contain added files and images. |
None
|
Source code in src/mojentic/llm/message_composers.py
add_file(file_path)
Add a single file to the message.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
file_path
|
Union[str, Path]
|
Path to the file. Can be a string or Path object. |
required |
Returns:
Type | Description |
---|---|
MessageBuilder
|
The MessageBuilder instance for method chaining. |
Raises:
Type | Description |
---|---|
FileNotFoundError
|
If the specified file does not exist. |
Source code in src/mojentic/llm/message_composers.py
add_files(*file_paths)
Add multiple text files to the message, ignoring binary files.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
*file_paths
|
Union[str, Path]
|
Variable number of file paths. Can be strings or Path objects. Can include glob patterns like '*.txt' to include all text files in a directory. If a directory is provided, all text files in the directory will be added. |
()
|
Returns:
Type | Description |
---|---|
MessageBuilder
|
The MessageBuilder instance for method chaining. |
Source code in src/mojentic/llm/message_composers.py
add_image(image_path)
Add a single image to the message.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
image_path
|
Union[str, Path]
|
Path to the image file. Can be a string or Path object. |
required |
Returns:
Type | Description |
---|---|
MessageBuilder
|
The MessageBuilder instance for method chaining. |
Raises:
Type | Description |
---|---|
FileNotFoundError
|
If the specified image file does not exist. |
Source code in src/mojentic/llm/message_composers.py
add_images(*image_paths)
Add multiple images to the message.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
*image_paths
|
Union[str, Path]
|
Variable number of image paths. Can be strings or Path objects. Can include glob patterns like '*.jpg' to include all JPG and PNG images in a directory. |
()
|
Returns:
Type | Description |
---|---|
MessageBuilder
|
The MessageBuilder instance for method chaining. |
Source code in src/mojentic/llm/message_composers.py
build()
Build the final LLMMessage from the accumulated content, images, and files.
This method combines all the content, file contents, and image paths into a single LLMMessage object that can be sent to an LLM. If files have been added, their contents will be formatted and included in the message content.
Returns:
Type | Description |
---|---|
LLMMessage
|
An LLMMessage object containing the message content and image paths. |
Source code in src/mojentic/llm/message_composers.py
load_content(file_path, template_values=None)
Load content from a file into the content field of the MessageBuilder.
This method reads the content of the specified file and sets it as the content of the MessageBuilder, replacing any existing content. If template_values is provided, placeholders in the content will be replaced with the corresponding values.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
file_path
|
Union[str, Path]
|
Path to the file to load content from. Can be a string or Path object. |
required |
template_values
|
Optional[Dict[str, Union[str, Path]]]
|
Dictionary of values used to replace placeholders in the content. For example, if the content contains "{greeting}" and template_values is {"greeting": "Hello, World!"}, then "{greeting}" will be replaced with "Hello, World!". If a value is a Path object, it will be treated as a file reference and the content of that file will be used to replace the placeholder. Default is None. |
None
|
Returns:
Type | Description |
---|---|
MessageBuilder
|
The MessageBuilder instance for method chaining. |
Raises:
Type | Description |
---|---|
FileNotFoundError
|
If the specified file does not exist. |