Skip to content

API Reference - Core ​

Core types and utilities for Mojentic.

Error Module ​

Result Type ​

typescript
type Result<T, E extends Error> = Ok<T> | Err<E>;

A discriminated union representing either success (Ok) or failure (Err).

Ok ​

typescript
interface Ok<T> {
  ok: true;
  value: T;
}

Represents a successful result.

Creating:

typescript
import { Ok } from 'mojentic';

const result = Ok(42);
const result2 = Ok({ name: "Alice", age: 30 });

Err ​

typescript
interface Err<E extends Error> {
  ok: false;
  error: E;
}

Represents a failed result.

Creating:

typescript
import { Err } from 'mojentic';

const result = Err(new Error("Something went wrong"));
const result2 = Err(new ValidationError("Invalid input"));

Type Guards ​

isOk ​

typescript
function isOk<T, E extends Error>(result: Result<T, E>): result is Ok<T>

Type guard to check if result is Ok.

Example:

typescript
const result = await broker.generate(messages);

if (isOk(result)) {
  console.log(result.value); // Type: string
}

isErr ​

typescript
function isErr<T, E extends Error>(result: Result<T, E>): result is Err<E>

Type guard to check if result is Err.

Example:

typescript
const result = await broker.generate(messages);

if (isErr(result)) {
  console.error(result.error); // Type: Error
}

Utility Functions ​

unwrap ​

typescript
function unwrap<T, E extends Error>(result: Result<T, E>): T

Extracts the value from Ok result or throws the error from Err result.

Example:

typescript
const result = Ok(42);
const value = unwrap(result); // 42

const errorResult = Err(new Error("Failed"));
unwrap(errorResult); // Throws Error

unwrapOr ​

typescript
function unwrapOr<T, E extends Error>(result: Result<T, E>, defaultValue: T): T

Returns the value from Ok or a default value if Err.

Example:

typescript
const result = Err(new Error("Failed"));
const value = unwrapOr(result, 0); // 0

mapResult ​

typescript
function mapResult<T, U, E extends Error>(
  result: Result<T, E>,
  fn: (value: T) => U
): Result<U, E>

Transforms the Ok value while preserving Err.

Example:

typescript
const result = Ok(5);
const doubled = mapResult(result, x => x * 2); // Ok(10)

mapError ​

typescript
function mapError<T, E extends Error, F extends Error>(
  result: Result<T, E>,
  fn: (error: E) => F
): Result<T, F>

Transforms the Err value while preserving Ok.

Example:

typescript
const result = Err(new Error("Failed"));
const mapped = mapError(result, e => new ValidationError(e.message));

Error Classes ​

MojenticError ​

Base error class for all Mojentic errors.

typescript
class MojenticError extends Error {
  constructor(message: string)
}

GatewayError ​

Errors from LLM gateway operations.

typescript
class GatewayError extends MojenticError {
  constructor(
    message: string,
    public readonly gateway: string,
    public readonly statusCode?: number
  )
}

Properties:

  • gateway: Name of the gateway that threw the error
  • statusCode: Optional HTTP status code

ToolError ​

Errors from tool execution.

typescript
class ToolError extends MojenticError {
  constructor(
    message: string,
    public readonly toolName: string
  )
}

Properties:

  • toolName: Name of the tool that threw the error

ValidationError ​

Schema validation errors.

typescript
class ValidationError extends MojenticError {
  constructor(message: string)
}

ParseError ​

JSON parsing errors.

typescript
class ParseError extends MojenticError {
  constructor(message: string)
}

TimeoutError ​

Timeout errors.

typescript
class TimeoutError extends MojenticError {
  constructor(
    message: string,
    public readonly timeoutMs: number
  )
}

Properties:

  • timeoutMs: The timeout duration in milliseconds

Message Module ​

MessageRole ​

typescript
enum MessageRole {
  System = 'system',
  User = 'user',
  Assistant = 'assistant',
  Tool = 'tool'
}

Role identifier for messages in conversation.

LlmMessage ​

typescript
interface LlmMessage {
  role: MessageRole;
  content: string | ContentItem[];
  thinking?: string;
  name?: string;
  tool_calls?: ToolCall[];
  tool_call_id?: string;
}

Message in a conversation.

Properties:

  • role: Who sent the message
  • content: Visible message text or content items
  • thinking: Optional native assistant reasoning, separate from visible content
  • name: Optional name/identifier
  • tool_calls: Optional tool calls (for assistant messages)
  • tool_call_id: Optional tool call ID (for tool result messages)

Message Helpers ​

typescript
class Message {
  static system(content: string): LlmMessage
  static user(content: string, name?: string): LlmMessage
  static assistant(content: string, toolCalls?: ToolCall[], thinking?: string): LlmMessage
  static tool(content: string, toolCallId: string, name: string): LlmMessage
}

Helper class for creating messages.

Examples:

typescript
const system = Message.system('You are a helpful assistant');
const user = Message.user('Hello!');
const assistant = Message.assistant('Hi there!');
const tool = Message.tool('{"result": 42}', 'call_123', 'calculator');

Tool Module ​

ToolCall ​

typescript
interface ToolCall {
  id: string;
  type: 'function';
  function: {
    name: string;
    arguments: string;  // JSON string
  };
}

Represents a tool call request from the LLM.

ToolArgs ​

typescript
type ToolArgs = Record<string, any>;

Arguments passed to a tool (parsed from JSON).

ToolResult ​

typescript
type ToolResult = Record<string, any>;

Result returned by a tool.

ToolDescriptor ​

typescript
interface ToolDescriptor {
  type: 'function';
  function: {
    name: string;
    description: string;
    parameters: Record<string, any>;  // JSON Schema
  };
}

JSON schema describing a tool for the LLM.

LlmTool Interface ​

typescript
interface LlmTool {
  run(args: ToolArgs): Promise<Result<ToolResult, Error>>;
  descriptor(): ToolDescriptor;
}

Interface for implementing tools.

Methods:

  • run: Execute the tool with given arguments
  • descriptor: Return the tool's schema

BaseTool Class ​

typescript
abstract class BaseTool implements LlmTool {
  abstract run(args: ToolArgs): Promise<Result<ToolResult, Error>>;
  abstract descriptor(): ToolDescriptor;
}

Abstract base class for tools.

Configuration ​

CompletionConfig ​

typescript
interface CompletionConfig {
  temperature?: number;
  maxTokens?: number;
  topP?: number;
  topK?: number;
  numCtx?: number;
  frequencyPenalty?: number;
  presencePenalty?: number;
  stop?: string[];
  stream?: boolean;
  responseFormat?: {
    type: 'json_object' | 'text';
    schema?: Record<string, unknown>;
  };
  retainReasoning?: boolean;
  reasoningEffort?: 'disabled' | 'enabled' | 'low' | 'medium' | 'high' | 'xhigh';
}

Configuration for LLM generation.

Properties:

  • temperature: Optional randomness (0.0-2.0). Omit to use provider/model settings; no gateway default is sent. Explicit values retain OpenAI model registry adaptation.
  • maxTokens: Optional output token limit. Omit to use provider/model limits; no library default is sent. Ollama receives options.num_predict, OpenAI chat and oMLX receive max_tokens, and OpenAI reasoning receives max_completion_tokens.
  • topP: Nucleus sampling threshold (0.0-1.0)
  • topK: Top-K sampling parameter (limits token selection to top K choices)
  • numCtx: Optional Ollama context size in tokens. Omit to use model/server settings. OpenAI and oMLX do not send this field.
  • frequencyPenalty: Penalty for token frequency (reduces repetition)
  • presencePenalty: Penalty for token presence (encourages diversity)
  • stop: Array of strings that will stop generation
  • stream: Whether to stream responses
  • responseFormat: Structured output configuration for JSON responses
  • retainReasoning: Opt in to completed native tool-turn history on Ollama/oMLX; defaults off. Selected profiles validate history support. OpenAI rejects true before HTTP. See migration.
  • reasoningEffort: Native reasoning control: disabled/enabled or low/medium/high/xhigh. Omission preserves provider defaults. See provider mappings; OpenAI rejects disabled/enabled/xhigh before HTTP in 3.0.0, including recovery.
    • Ollama: Sends think: false for disabled, think: true for enabled, and the exact string for low, medium, high or xhigh. Omission sends no think field.
    • OpenAI: Sends reasoning_effort for low, medium or high on reasoning models; warns and drops these levels on other models. Rejects disabled, enabled and xhigh before HTTP, including recovery.
    • oMLX: Sends top-level enable_thinking: false for disabled and enable_thinking: true for enabled; named levels use top-level reasoning_effort with the exact string. These fields are mutually exclusive; omission sends neither and preserves provider defaults.

Gateway Types ​

GatewayResponse ​

typescript
interface GatewayResponse {
  content: string;
  toolCalls?: ToolCall[];
  finishReason?: FinishReason;
  usage?: CompletionUsage;
  model?: string;
  thinking?: string;
  metadata?: Record<string, unknown>;
}

Response from LLM gateway.

Properties:

  • content: Generated text
  • toolCalls: Tool calls requested by LLM
  • finishReason: Why generation stopped (stop, length, tool_calls, content_filter, or a different value from the provider)
  • usage: Token counts that the provider reported (promptTokens, completionTokens, totalTokens). The gateway never estimates them.
  • model: Model name that the provider reported. It is not always the requested model.
  • thinking: Model's reasoning trace (Ollama and oMLX only)
  • metadata: Other fields that the provider reported, for example response ids or timings

StreamChunk ​

typescript
interface StreamChunk {
  content?: string;
  toolCalls?: ToolCall[];
  finishReason?: FinishReason;
  done: boolean;
}

Chunk in a streaming response from LlmGateway.generateStream.

Properties:

  • content: Text in this chunk. Some chunks have no text.
  • toolCalls: Tool calls (only in the last chunk)
  • finishReason: Why generation stopped (only in the last chunk)
  • done: True for the last chunk

See Also ​

Released under the MIT License.