Documentation/Utilities
v2.0.0-beta.1Snapshot bebdcd1Markdown ↗

Utilities

Utilities

Helper functions and utilities

MessageBuilder class

📍 src/utils/messageBuilder.ts:12

Methods

addUserMessage()

Add a user text message

typescript
addUserMessage(text: string): this

Parameters:

  • text: string

Returns: this

addUserMessageWithImages()

Add a user message with text and images

typescript
addUserMessageWithImages(text: string, imageUrls: string[]): this

Parameters:

  • text: string
  • imageUrls: string[]

Returns: this

addAssistantMessage()

Add an assistant message (for conversation history)

typescript
addAssistantMessage(text: string): this

Parameters:

  • text: string

Returns: this

addDeveloperMessage()

Add a system/developer message

typescript
addDeveloperMessage(text: string): this

Parameters:

  • text: string

Returns: this

build()

Build and return the messages array

typescript
build(): InputItem[]

Returns: InputItem[]

clear()

Clear all messages

typescript
clear(): this

Returns: this

count()

Get the current message count

typescript
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

📍 src/utils/jsonRepair.ts:32

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

typescript
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
typescript
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:

  1. JSON inside markdown code blocks (json ... or ...)
  2. First complete JSON object/array found in text
  3. Raw string as JSON
typescript
export function extractJSON<T = unknown>(text: string): JSONExtractionResult<T>

Example:

typescript
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

typescript
export function extractJSONField&lt;T&gt;(
  text: string,
  field: string,
  defaultValue: T
): T

Example:

typescript
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

typescript
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:

typescript
const score = extractNumber(llmResponse, [/(\d{1,3})%?\s*complete/i], 50);

parseJsonPermissive function

📍 src/utils/jsonRepair.ts:51

Parse JSON from an LLM response with multiple repair strategies.

typescript
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.

typescript
export async function readDocumentAsContent(
  source: DocumentSource | string,
  options: DocumentReadOptions & DocumentToContentOptions = {}
): Promise&lt;Content[]&gt;

Example:

typescript
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,
]);

Documentation snapshot · 2026-11-02Suggest a correction ↗

Search documentation

Type to search the v2 documentation.