QVAC Logo

completion( )

Generates completion from a language model based on conversation history.

function completion(params): {
  tokenStream: AsyncGenerator<string>;
  toolCallStream: AsyncGenerator<ToolCallEvent>;
  text: Promise<string>;
  toolCalls: Promise<ToolCallWithCall[]>;
  stats: Promise<CompletionStats | undefined>;
};

Parameters

NameTypeRequired?Description
paramsCompletionParamsThe completion parameters

CompletionParams

FieldTypeRequired?DefaultDescription
modelIdstringThe identifier of the model to use for completion
historyHistoryMessage[]Array of conversation messages
streambooleantrueWhether to stream tokens or return complete response
toolsTool[] | ToolInput[]Optional array of tools (Zod-schema ToolInput or full Tool objects)
mcpMcpClientInput[]Optional array of MCP client inputs for tool integration
kvCacheboolean | stringKV cache configuration — see kvCache

HistoryMessage

FieldTypeRequired?Description
rolestringMessage role (e.g., "user", "assistant", "system")
contentstringMessage content
attachmentsAttachment[]Optional file attachments for multimodal models
Attachment
FieldTypeRequired?Description
pathstringFile path to the attachment

Tool

Full tool definition in JSON Schema format (sent to the model):

FieldTypeRequired?Description
type"function"Always "function"
namestringTool name
descriptionstringWhat the tool does
parametersobjectJSON Schema object describing the tool's input
parameters.type"object"Always "object"
parameters.propertiesRecord<string, { type, description?, enum? }>Parameter definitions
parameters.requiredstring[]Required parameter names

ToolInput

Simplified tool definition using Zod schemas (auto-converted to Tool internally):

FieldTypeRequired?Description
namestringTool name
descriptionstringWhat the tool does
parametersZodObjectZod schema describing the tool's input
handler(args: Record<string, unknown>) => Promise<unknown>Handler function — when provided, returned ToolCallWithCall objects include an invoke() method

McpClientInput

MCP (Model Context Protocol) client input for tool integration:

FieldTypeRequired?Description
clientMcpClientAn MCP client instance
includeResourcesbooleanWhether to include MCP resources
McpClient

Duck-typed MCP client interface:

MethodSignatureRequired?Description
listTools() => Promise<{ tools: McpTool[] }>Lists available tools
callTool(params: { name, arguments }) => Promise<McpToolCallResult>Calls a tool by name
listResources() => Promise<{ resources: McpResource[] }>Lists available resources
readResource(params: { uri }) => Promise<{ contents: unknown[] }>Reads a resource by URI

kvCache

Cache files are organized hierarchically: {kvCacheKey}/{modelId}/{configHash}.bin

The configHash includes model config + system prompt to ensure cache isolation.

ValueBehavior
trueAuto-generate cache key based on conversation history
"custom-key"Use provided string as cache key for manual session management
false / undefinedNo caching

When cache exists, only the last message is sent to the model (includes multimodal attachments). Use deleteCache() to remove cached sessions.

Returns

object — Object with the following fields:

FieldTypeDescription
tokenStreamAsyncGenerator<string>Stream of generated tokens
toolCallStreamAsyncGenerator<ToolCallEvent>Stream of tool call events
textPromise<string>Complete generated text (resolves after stream ends)
toolCallsPromise<ToolCallWithCall[]>Tool calls made during completion (may include invoke() when handler is available)
statsPromise<CompletionStats | undefined>Performance statistics

CompletionStats

FieldTypeDescription
timeToFirstTokennumberTime to first token in milliseconds
tokensPerSecondnumberTokens generated per second
cacheTokensnumberNumber of cached tokens

ToolCallEvent

Discriminated union on type. One of:

Tool call:

FieldTypeDescription
type"toolCall"Event type
call.idstringCall identifier
call.namestringTool name
call.argumentsRecord<string, unknown>Tool arguments
call.rawstringRaw call text (optional)

Tool call error:

FieldTypeDescription
type"toolCallError"Event type
error.code"PARSE_ERROR" | "VALIDATION_ERROR" | "UNKNOWN_TOOL"Error code
error.messagestringError message
error.rawstringRaw text (optional)

ToolCallWithCall

Extends ToolCall with an optional invoke() method:

FieldTypeDescription
idstringCall identifier
namestringTool name
argumentsRecord<string, unknown>Tool arguments
rawstringRaw call text (optional)
invoke() => Promise<unknown>Executes the tool handler (present when a matching handler was provided)

Throws

ErrorWhen
INVALID_TOOLS_ARRAYInvalid tools array provided
INVALID_TOOL_SCHEMAA tool has an invalid schema

Example

import { z } from "zod";

const result = completion({
  modelId: "llama-2",
  history: [
    { role: "user", content: "What's the weather in Tokyo?" }
  ],
  stream: true,
  tools: [{
    name: "get_weather",
    description: "Get current weather",
    parameters: z.object({
      city: z.string().describe("City name"),
    }),
    handler: async (args) => {
      return { temperature: 22, condition: "sunny" };
    }
  }]
});

for await (const token of result.tokenStream) {
  process.stdout.write(token);
}

for (const toolCall of await result.toolCalls) {
  if (toolCall.invoke) {
    const toolResult = await toolCall.invoke();
    console.log(toolResult);
  }
}

On this page