Skip to main content

Configuration

All Toolpack SDK configuration is passed directly to Toolpack.init(). There is no file-based config discovery — settings are explicit code.

Toolpack.init() Options​

OptionTypeDefaultDescription
providerstring—Single provider shorthand ('openai', 'anthropic', 'gemini', etc.)
apiKeystring—API key override (defaults to env var)
modelstring—Default model name
providersRecord<string, ProviderOptions>noneSeveral providers at once, keyed by name. See Providers
defaultProviderstringfirst configuredProvider used when a request does not name one
customProvidersProviderAdapter[] or Record<string, ProviderAdapter>noneYour own provider adapters. See Custom Providers
projectIdstringenv varVertex AI and Anthropic on Vertex: GCP project ID
locationstring'us-central1'Vertex AI: GCP region
googleAuthOptions{ keyFilename?, credentials? }ADCVertex AI: service account auth
thinkingBudgetnumbernoneVertex AI: thinking token budget for Gemini 2.5+ models (0 turns thinking off)
regionstring'us-east5'Anthropic on Vertex: GCP region
toolsbooleanfalseEnable built-in tools
toolsConfigPartial<ToolsConfig>{}Tool behavior overrides
toolOverridesToolProject[]—Projects loaded after built-ins; same name replaces the built-in
customModesModeConfig[][]Additional modes to register
defaultModestring'chat'Mode to activate on init
loggingLoggingConfig—File logging settings
hitlHitlConfig—Human-in-the-loop confirmation
onToolConfirmcallback—Confirmation handler (also enables HITL)
contextWindowContextWindowConfig—Automatic conversation pruning/summarization
mcpMcpToolsConfignoneConnect to MCP servers and register their tools. See MCP
knowledgeKnowledge or Knowledge[]noneKnowledge bases added as a knowledge_search tool. See Knowledge
confirmationMode'off' | 'high-only' | 'all''all' with onToolConfirm, else 'off'Which tools ask for confirmation. See HITL
conversationIdstringnoneConversation ID passed to onToolConfirm for tracking
interceptorsToolpackInterceptor[][]Wrap every generate() call. See Request interceptors
disableBaseContextbooleanfalseDo not add the base agent context to the system prompt (for tests or fully custom prompts)
actorToolActor or () => ToolActor | null | undefined—Who tool calls act for. Passed to every tool as ctx.actor; the model never sees or sets it. Use a function when one instance serves several people
disableToolGuidancebooleanfalseTurn off the automatic tool usage guidance added to the system prompt

Tools Configuration​

Pass toolsConfig to Toolpack.init():

const toolpack = await Toolpack.init({
provider: 'openai',
tools: true,
toolsConfig: {
enabled: true,
autoExecute: true,
maxToolRounds: 10,
toolChoicePolicy: 'auto',
enabledTools: [],
enabledToolCategories: [],
toolSearch: {
enabled: false,
alwaysLoadedTools: [],
alwaysLoadedCategories: [],
searchResultLimit: 5,
cacheDiscoveredTools: true,
},
additionalConfigurations: {
MY_CUSTOM_API_KEY: process.env.MY_CUSTOM_API_KEY,
},
},
});

Tools Options​

OptionTypeDefaultDescription
enabledbooleantrueEnable tool system
autoExecutebooleantrueAutomatically execute tool calls
maxToolRoundsnumber5Max tool execution rounds per request. When the cap is hit with tools still pending, the model gets one final text-only round to wrap up
toolChoicePolicystring"auto""auto", "required", or "required_for_actions"
resultMaxCharsnumber20000Longest tool result (in characters) sent to the model; longer results are cut
enabledToolsstring[][]Specific tools to enable (empty = all)
enabledToolCategoriesstring[][]Categories to enable (empty = all)
additionalConfigurationsobjectKey-value config passed dynamically to custom tools via ToolContext

Tool Categories​

CategoryDescription
filesystemFile system operations
executionCommand execution
systemSystem information
httpHTTP request tools
webWeb search, fetch, scrape, and related tools
githubGitHub GraphQL/REST tools
slackSlack Web API tools
codingCode analysis tools
version-controlGit operations
diffDiff and patch tools
databaseDatabase operations
cloudCloud deployment

For large tool sets, enable on-demand tool discovery:

toolsConfig: {
toolSearch: {
enabled: true,
alwaysLoadedTools: ['fs.read_file', 'exec.run'],
alwaysLoadedCategories: ['filesystem'],
searchResultLimit: 5,
cacheDiscoveredTools: true,
},
}

Logging Configuration​

Pass logging to Toolpack.init():

const toolpack = await Toolpack.init({
provider: 'openai',
logging: {
enabled: true,
filePath: './toolpack-sdk.log',
level: 'debug',
console: false,
},
});
OptionTypeDefaultDescription
enabledbooleanfalseEnable file logging
filePathstringtoolpack-sdk.logLog file path (relative to CWD)
levelstringinfoLog level (error, warn, info, debug, trace)
consolebooleanfalseMirror log output to console

Environment variables override programmatic config (highest precedence):

export TOOLPACK_SDK_LOG_FILE="./toolpack-sdk.log"   # also enables logging
export TOOLPACK_SDK_LOG_LEVEL="debug"
export TOOLPACK_SDK_LOG_ENABLED="true"
export TOOLPACK_SDK_LOG_CONSOLE="true"

Environment Variables​

VariableDescription
OPENAI_API_KEYOpenAI API key
ANTHROPIC_API_KEYAnthropic API key
GEMINI_API_KEYGoogle Gemini API key
TOOLPACK_OPENAI_KEYAlternative OpenAI key
TOOLPACK_ANTHROPIC_KEYAlternative Anthropic key
TOOLPACK_GEMINI_KEYAlternative Gemini key
OPENROUTER_API_KEY / TOOLPACK_OPENROUTER_KEYOpenRouter API key
GOOGLE_CLOUD_PROJECTGCP project for Vertex AI and Anthropic on Vertex
TOOLPACK_VERTEXAI_PROJECT / VERTEX_AI_PROJECTVertex AI project (before GOOGLE_CLOUD_PROJECT)
TOOLPACK_VERTEXAI_LOCATION / VERTEX_AI_LOCATIONVertex AI region
ANTHROPIC_VERTEX_PROJECT_ID / ANTHROPIC_VERTEX_REGIONAnthropic on Vertex project and region
TOOLPACK_SDK_LOG_FILELog file path (enables logging)
TOOLPACK_SDK_LOG_LEVELLog level override (error, warn, info, debug, trace)
NETLIFY_AUTH_TOKENNetlify deployment token

Request interceptors​

interceptors wraps every generate() call. Each interceptor gets the full CompletionRequest and a next() function. Call next() (optionally with a changed request) to continue, or return a response without calling it to answer directly. They run in order: the first in the array runs outermost.

import type { ToolpackInterceptor } from 'toolpack-sdk';

const logTimes: ToolpackInterceptor = async (request, next) => {
const start = Date.now();
const response = await next();
console.log(`${request.model}: ${Date.now() - start} ms`);
return response;
};

const toolpack = await Toolpack.init({ provider: 'openai', interceptors: [logTimes] });

An interceptor can also have an init() method. Toolpack.init() calls it once at startup, so it can check its setup and fail early.

  • They apply to generate() only, not stream()
  • They do not run when the mode uses a planning workflow
  • To stop or change single tool calls, use interceptTool instead
  • These are not the same as agent interceptors, which handle incoming messages

Context Window Management​

The contextWindow init option controls automatic conversation pruning and summarization. When the accumulated message history approaches the model's context limit, the SDK either prunes old messages or summarizes them before the next request.

const toolpack = await Toolpack.init({
provider: 'openai',
contextWindow: {
enabled: true, // default: true
strategy: 'prune', // 'prune' | 'summarize' | 'fail'
pruneThreshold: 85, // trigger at 85% of context window
maxMessageHistoryLength: 100, // optional hard cap on message count
summarizerModel: 'gpt-4.1-mini', // only used when strategy = 'summarize'
retainSystemMessages: true, // never prune system messages (default: true)
outputTokenBuffer: 1.15, // 15% safety buffer above maxOutputTokens
},
});

ContextWindowConfig fields​

FieldTypeDefaultDescription
enabledbooleantrueMaster switch for context window management
strategy'prune' | 'summarize' | 'fail''prune'What to do when the threshold is reached
pruneThresholdnumber85Percentage of the context window that triggers cleanup
maxMessageHistoryLengthnumber—Optional cap on total message count, independent of token counting
summarizerModelstring(current model)Model to use for summarization — set to a faster/cheaper model to reduce cost
retainSystemMessagesbooleantrueWhether system messages are exempt from pruning
outputTokenBuffernumber1.15Safety multiplier applied to maxOutputTokens before computing available input space

Strategies:

  • 'prune' — removes the oldest non-system messages until the history fits.
  • 'summarize' — calls the LLM to produce a summary of removed messages and inserts it as a system message before continuing.
  • 'fail' — throws an error instead of modifying the history.

maxToolRounds in AgentRunOptions​

AgentRunOptions.maxToolRounds sets a per-run hard cap on the number of tool-call rounds the agent may execute. It overrides the toolsConfig.maxToolRounds value from Toolpack.init() and bypasses the query-classifier adjustment for that specific run.

// In your BaseAgent subclass:
const result = await this.run(prompt, {
maxToolRounds: 1, // single-shot: the LLM may call at most one tool round
});
interface AgentRunOptions {
/** One-off workflow override for this specific run */
workflow?: Record<string, unknown>;

/**
* Hard cap on tool-call rounds for this specific run.
* Overrides ToolsConfig.maxToolRounds and bypasses the query-classifier
* adjustment. Use for agents that should only make one tool call per
* invocation (e.g. single-shot routers using delegate_to_agent).
*/
maxToolRounds?: number;

/** Hard cap on output tokens for this run. Mapped directly to max_tokens on the provider request. */
maxTokens?: number;

/** Optional abort signal propagated to the underlying AIClient stream/generate call. */
signal?: AbortSignal;

/** Called with each text delta as it is generated. When set, the run uses streaming. */
onChunk?: (delta: string) => void;

/** Wraps every tool call of this run: it can stop a call or change its result (v3.6.0). Passed to the request as interceptTool. */
interceptTool?: ToolInterceptor;
}

maxToolRounds can also be set at the CompletionRequest level when calling toolpack.generate() directly:

await toolpack.generate({
messages: [{ role: 'user', content: 'Which agent should handle this?' }],
model: 'gpt-4o',
maxToolRounds: 1,
});

Full Example​

const toolpack = await Toolpack.init({
provider: 'openai',
apiKey: process.env.OPENAI_API_KEY,
model: 'gpt-4o',
tools: true,
toolsConfig: {
maxToolRounds: 10,
additionalConfigurations: { MY_API_KEY: process.env.MY_API_KEY },
},
logging: { enabled: true, filePath: './toolpack.log', level: 'debug' },
hitl: { enabled: true, confirmationMode: 'all' },
onToolConfirm: async (tool) => askUser(`Allow ${tool.displayName}?`),
customModes: [...],
defaultMode: 'agent',
});

See ToolpackInitConfig for all options.