Utilities
Utilities
Helper functions and utilities
MessageBuilder class
📍 src/utils/messageBuilder.ts:12
Methods
addUserMessage()
Add a user text message
addUserMessage(text: string): this
Parameters:
text:string
Returns: this
addUserMessageWithImages()
Add a user message with text and images
addUserMessageWithImages(text: string, imageUrls: string[]): this
Parameters:
text:stringimageUrls:string[]
Returns: this
addAssistantMessage()
Add an assistant message (for conversation history)
addAssistantMessage(text: string): this
Parameters:
text:string
Returns: this
addDeveloperMessage()
Add a system/developer message
addDeveloperMessage(text: string): this
Parameters:
text:string
Returns: this
build()
Build and return the messages array
build(): InputItem[]
Returns: InputItem[]
clear()
Clear all messages
clear(): this
Returns: this
count()
Get the current message count
count(): number
Returns: number
JSONExtractionResult interface
📍 src/utils/jsonExtractor.ts:11
JSON Extractor Utilities
Extracts JSON from LLM responses that may contain markdown formatting, code blocks, or other text mixed with JSON data.
Properties
| Property | Type | Description |
|---|---|---|
success |
success: boolean; |
Whether extraction was successful |
data? |
data?: T; |
Extracted and parsed data (if successful) |
rawJson? |
rawJson?: string; |
Raw JSON string that was parsed (if found) |
error? |
error?: string; |
Error message (if failed) |
method? |
`method?: 'code_block' | 'inline' |
ParseJsonPermissiveOptions interface
Properties
| Property | Type | Description |
|---|---|---|
stripFieldsAsLastResort? |
stripFieldsAsLastResort?: string[]; |
Field names that may contain verbatim text (quotes, newlines, unescaped |
| chars) which breaks JSON parsing. If all repair strategies fail, the | ||
parser replaces each named field's value with null and retries. |
Defaults to ['details', 'body', 'quote', 'sourceQuote', 'excerpt', 'narrative', 'rawText'] — the usual suspects across LLM schemas.
Pass [] to disable the field-strip fallback entirely. |
createTextMessage function
📍 src/utils/messageBuilder.ts:124
Helper function to create a simple text message
export function createTextMessage(text: string, role: MessageRole = MessageRole.USER): InputItem
documentToContent function
📍 src/utils/documentContentBridge.ts:26
Convert a DocumentResult to Content[] for LLM input.
- Text pieces → InputTextContent
- Image pieces → InputImageContent (with data URI)
- Adjacent text pieces merged by default
- Additional image filtering applied
export function documentToContent(
result: DocumentResult,
options: DocumentToContentOptions = {}
): Content[]
extractJSON function
📍 src/utils/jsonExtractor.ts:49
Extract JSON from a string that may contain markdown code blocks or other formatting.
Tries multiple extraction strategies in order:
- JSON inside markdown code blocks (
json ...or...) - First complete JSON object/array found in text
- Raw string as JSON
export function extractJSON<T = unknown>(text: string): JSONExtractionResult<T>
Example:
const response = `Here's the result:
\`\`\`json
{"score": 85, "valid": true}
\`\`\`
That's the answer.`;
const result = extractJSON<{score: number, valid: boolean}>(response);
if (result.success) {
console.log(result.data.score); // 85
}
extractJSONField function
📍 src/utils/jsonExtractor.ts:258
Safely extract a specific field from JSON embedded in text
export function extractJSONField<T>(
text: string,
field: string,
defaultValue: T
): T
Example:
const score = extractJSONField<number>(llmResponse, 'completionScore', 50);
extractNumber function
📍 src/utils/jsonExtractor.ts:283
Extract a number from text, trying JSON first, then regex patterns
export function extractNumber(
text: string,
patterns: RegExp[] = [
/(\d{1,3})%?\s*(?:complete|score|percent)/i,
/(?:score|completion|rating)[:\s]+(\d{1,3})/i,
/(\d{1,3})\s*(?:out of|\/)\s*100/i,
],
defaultValue: number = 0
): number
Example:
const score = extractNumber(llmResponse, [/(\d{1,3})%?\s*complete/i], 50);
parseJsonPermissive function
Parse JSON from an LLM response with multiple repair strategies.
export function parseJsonPermissive(
text: string,
opts?: ParseJsonPermissiveOptions,
): unknown
readDocumentAsContent function
📍 src/utils/documentContentBridge.ts:116
One-call convenience: read a document and convert to Content[] for LLM input.
export async function readDocumentAsContent(
source: DocumentSource | string,
options: DocumentReadOptions & DocumentToContentOptions = {}
): Promise<Content[]>
Example:
const content = await readDocumentAsContent('/path/to/doc.pdf', {
imageFilter: { minWidth: 100, minHeight: 100 },
imageDetail: 'auto',
});
agent.run([
{ type: 'input_text', text: 'Analyze this document:' },
...content,
]);