@oh-my-pi-zen/pi-ai
Unified LLM API with automatic model discovery, provider configuration, token and cost tracking, and simple context persistence and hand-off to other models mid-session.
Note: This library only includes models that support tool calling (function calling), as this is essential for agentic workflows.
Table of Contents
- Supported Providers
- Installation
- Quick Start
- Tools
- Defining Tools
- Handling Tool Calls
- Streaming Tool Calls with Partial JSON
- Validating Tool Arguments
- Complete Event Reference
- Image Input
- Thinking/Reasoning
- Unified Interface
- Provider-Specific Options
- Streaming Thinking Content
- Stop Reasons
- Error Handling
- Aborting Requests
- Continuing After Abort
- APIs, Models, and Providers
- Providers and Models
- Querying Providers and Models
- Custom Models
- OpenAI Compatibility Settings
- Type Safety
- Cross-Provider Handoffs
- Context Serialization
- Browser Usage
- Environment Variables
- Checking Environment Variables
- OAuth Providers
- Vertex AI (ADC)
- CLI Login
- Programmatic OAuth
- Login Flow Example
- Using OAuth Tokens
- Provider Notes
- License
Supported Providers
- OpenAI
- OpenAI Codex (ChatGPT Plus/Pro subscription, requires OAuth, see below)
- Anthropic
- Google
- Vertex AI (Gemini via Vertex AI)
- Mistral
- Groq
- Cerebras
- Together
- Moonshot (requires
MOONSHOT_API_KEY)
- Qianfan (requires
QIANFAN_API_KEY)
- NVIDIA (requires
NVIDIA_API_KEY)
- NanoGPT (requires
NANO_GPT_API_KEY)
- Novita (requires
NOVITA_API_KEY)
- DeepInfra (requires
DEEPINFRA_API_KEY)
- Hugging Face Inference
- xAI
- Venice (requires
VENICE_API_KEY)
- Wafer Serverless (requires
WAFER_SERVERLESS_API_KEY; pay-as-you-go)
- OpenRouter
- Kilo Gateway (supports OAuth
/login kilo or KILO_API_KEY)
- LiteLLM (requires
LITELLM_API_KEY)
- zAI (requires
ZAI_API_KEY)
- Umans AI Coding Plan (supports
/login umans or UMANS_AI_CODING_PLAN_API_KEY)
- MiniMax Token Plan (requires
MINIMAX_CODE_API_KEY or MINIMAX_CODE_CN_API_KEY)
- Xiaomi MiMo (requires
XIAOMI_API_KEY)
- ZenMux (requires
ZENMUX_API_KEY)
- Qwen Portal (supports
QWEN_OAUTH_TOKEN or QWEN_PORTAL_API_KEY)
- QwenCloud Token Plan (supports
/login alibaba-token-plan, ALIBABA_TOKEN_PLAN_API_KEY, or BAILIAN_TOKEN_PLAN_API_KEY; interactive login first selects a region — International (Singapore, default), China (Beijing) for 百炼 Token Plan keys, or a custom base URL — since region keys are non-interchangeable, then optionally stores a home.qwencloud.com Cookie request header for best-effort 5-hour and 7-day quota reporting)
To enable quota reporting, sign in to the Token Plan dashboard, copy the Cookie request-header value from a home.qwencloud.com request in browser developer tools, and paste it at the second login prompt. Press Enter to skip; the Cookie is sensitive and session-lived, so rerun login when it expires.
- Cloudflare AI Gateway (supports
/login cloudflare-ai-gateway, or CLOUDFLARE_AI_GATEWAY_API_KEY with CLOUDFLARE_ACCOUNT_ID and CLOUDFLARE_GATEWAY_ID)
- Snowflake Cortex (browser
/login snowflake, or SNOWFLAKE_ACCOUNT + SNOWFLAKE_PAT; account-billed Cortex REST API)
- Ollama (local OpenAI-compatible runtime; optional
OLLAMA_API_KEY)
- Ollama Cloud (hosted native Ollama API; requires
OLLAMA_CLOUD_API_KEY)
- llama.cpp (local OpenAI and Anthropic compatible inference server)
- vLLM (OpenAI-compatible server;
VLLM_API_KEY for secured deployments)
- GitHub Copilot (requires OAuth, see below)
- Google Gemini CLI (requires OAuth, see below)
- Google Antigravity (requires OAuth, see below)
- Any OpenAI-compatible API: LM Studio, custom proxies, etc.
Installation
npm install @oh-my-pi-zen/pi-ai
Quick Start
import { getModel, stream, complete, Context, Tool, type } from "@oh-my-pi-zen/pi-ai";
// Fully typed with auto-complete support for both providers and models
const model = getModel("openai", "gpt-4o-mini");
// Define tools with omptype schemas for type safety and validation
const tools: Tool[] = [
{
name: "get_time",
description: "Get the current time",
parameters: type({
"timezone?": type("string").describe("Optional timezone (e.g., America/New_York)"),
}),
},
];
// Build a conversation context (easily serializable and transferable between models)
const context: Context = {
systemPrompt: ["You are a helpful assistant."],
messages: [{ role: "user", content: "What time is it?" }],
tools,
};
// Option 1: Streaming with all event types
const s = stream(model, context);
for await (const event of s) {
switch (event.type) {
case "start":
console.log(`Starting with ${event.partial.model}`);
break;
case "text_start":
console.log("\n[Text started]");
break;
case "text_delta":
process.stdout.write(event.delta);
break;
case "text_end":
console.log("\n[Text ended]");
break;
case "thinking_start":
console.log("[Model is thinking...]");
break;
case "thinking_delta":
process.stdout.write(event.delta);
break;
case "thinking_end":
console.log("[Thinking complete]");
break;
case "toolcall_start":
console.log(`\n[Tool call started: index ${event.contentIndex}]`);
break;
case "toolcall_delta":
// Partial tool arguments are being streamed
const partialCall = event.partial.content[event.contentIndex];
if (partialCall.type === "toolCall") {
console.log(`[Streaming args for ${partialCall.name}]`);
}
break;
case "toolcall_end":
console.log(`\nTool called: ${event.toolCall.name}`);
console.log(`Arguments: ${JSON.stringify(event.toolCall.arguments)}`);
break;
case "done":
console.log(`\nFinished: ${event.reason}`);
break;
case "error":
console.error(`Error: ${event.error}`);
break;
}
}
// Get the final message after streaming, add it to the context
const finalMessage = await s.result();
context.messages.push(finalMessage);
// Handle tool calls if any
const toolCalls = finalMessage.content.filter(b => b.type === "toolCall");
for (const call of toolCalls) {
// Execute the tool
const result =
call.name === "get_time"
? new Date().toLocaleString("en-US", {
timeZone: call.arguments.timezone || "UTC",
dateStyle: "full",
timeStyle: "long",
})
: "Unknown tool";
// Add tool result to context (supports text and images)
context.messages.push({
role: "toolResult",
toolCallId: call.id,
toolName: call.name,
content: [{ type: "text", text: result }],
isError: false,
timestamp: Date.now(),
});
}
// Continue if there were tool calls
if (toolCalls.length > 0) {
const continuation = await complete(model, context);
context.messages.push(continuation);
console.log("After tool execution:", continuation.content);
}
console.log(`Total tokens: ${finalMessage.usage.input} in, ${finalMessage.usage.output} out`);
console.log(`Cost: $${finalMessage.usage.cost.total.toFixed(4)}`);
// Option 2: Get complete response without streaming
const response = await complete(model, context);
for (const block of response.content) {
if (block.type === "text") {
console.log(block.text);
} else if (block.type === "toolCall") {
console.log(`Tool: ${block.name}(${JSON.stringify(block.arguments)})`);
}
}
Tools
Tools enable LLMs to interact with external systems. Omptype schemas provide type-safe definitions, runtime validation, and JSON Schema conversion for providers.
Defining Tools
import { type Tool, type } from "@oh-my-pi-zen/pi-ai";
const weatherTool: Tool = {
name: "get_weather",
description: "Get current weather for a location",
parameters: type({
location: type("string").describe("City name or coordinates"),
units: type.enumerated("celsius", "fahrenheit").default("celsius"),
}),
};
const bookMeetingTool: Tool = {
name: "book_meeting",
description: "Schedule a meeting",
parameters: type({
title: type("string").atLeastLength(1),
startTime: type("string").describe("ISO 8601 date-time"),
endTime: type("string").describe("ISO 8601 date-time"),
attendees: type("string.email").array().atLeastLength(1),
}),
};
Handling Tool Calls
Tool results use content blocks and can include both text and images:
import * as fs from "node:fs";
const context: Context = {
messages: [{ role: "user", content: "What is the weather in London?" }],
tools: [weatherTool],
};
const response = await complete(model, context);
// Check for tool calls in the response
for (const block of response.content) {
if (block.type === "toolCall") {
// Execute your tool with the arguments
// See "Validating Tool Arguments" section for validation
const result = await executeWeatherApi(block.arguments);
// Add tool result with text content
context.messages.push({
role: "toolResult",
toolCallId: block.id,
toolName: block.name,
content: [{ type: "text", text: JSON.stringify(result) }],
isError: false,
timestamp: Date.now(),
});
}
}
// Tool results can also include images (for vision-capable models)
const imageBuffer = fs.readFileSync("chart.png");
context.messages.push({
role: "toolResult",
toolCallId: "tool_xyz",
toolName: "generate_chart",
content: [
{ type: "text", text: "Generated chart showing temperature trends" },
{ type: "image", data: imageBuffer.toBase64(), mimeType: "image/png" },
],
isError: false,
timestamp: Date.now(),
});
Streaming Tool Calls with Partial JSON
During streaming, tool call arguments are progressively parsed as they arrive. This enables real-time UI updates before the complete arguments are available:
const s = stream(model, context);
for await (const event of s) {
if (event.type === "toolcall_delta") {
const toolCall = event.partial.content[event.contentIndex];
// toolCall.arguments contains partially parsed JSON during streaming
// This allows for progressive UI updates
if (toolCall.type === "toolCall" && toolCall.arguments) {
// BE DEFENSIVE: arguments may be incomplete
// Example: Show file path being written even before content is complete
if (toolCall.name === "write_file" && toolCall.arguments.path) {
console.log(`Writing to: ${toolCall.arguments.path}`);
// Content might be partial or missing
if (toolCall.arguments.content) {
console.log(`Content preview: ${toolCall.arguments.content.substring(0, 100)}...`);
}
}
}
}
if (event.type === "toolcall_end") {
// Here toolCall.arguments is complete (but not yet validated)
const toolCall = event.toolCall;
console.log(`Tool completed: ${toolCall.name}`, toolCall.arguments);
}
}
Important notes about partial tool arguments:
- During
toolcall_delta events, arguments contains the best-effort parse of partial JSON
- Fields may be missing or incomplete - always check for existence before use
- String values may be truncated mid-word
- Arrays may be incomplete
- Nested objects may be partially populated
- At minimum,
arguments will be an empty object {}, never undefined
- The Google provider does not support function call streaming. Instead, you will receive a single
toolcall_delta event with the full arguments.
Validating Tool Arguments
When using agentLoop, tool arguments are automatically validated against their omptype schemas before execution. Validation failures are returned to the model as tool results so it can retry.
When implementing your own tool execution loop with stream() or complete(), use validateToolCall to validate arguments before passing them to your tools:
import { stream, validateToolCall, Tool } from "@oh-my-pi-zen/pi-ai";
const tools: Tool[] = [weatherTool, calculatorTool];
const s = stream(model, { messages, tools });
for await (const event of s) {
if (event.type === "toolcall_end") {
const toolCall = event.toolCall;
try {
// Validate arguments against the tool's schema (throws on invalid args)
const validatedArgs = validateToolCall(tools, toolCall);
const result = await executeMyTool(toolCall.name, validatedArgs);
// ... add tool result to context
} catch (error) {
// Validation failed - return error as tool result so model can retry
context.messages.push({
role: "toolResult",
toolCallId: toolCall.id,
toolName: toolCall.name,
content: [{ type: "text", text: error.message }],
isError: true,
timestamp: Date.now(),
});
}
}
}
Complete Event Reference
All streaming events emitted during assistant message generation:
| Event Type |
Description |
Key Properties |
start |
Stream begins |
partial: Initial assistant message structure |
text_start |
Text block starts |
contentIndex: Position in content array |
text_delta |
Text chunk received |
delta: New text, contentIndex: Position |
text_end |
Text block complete |
content: Full text, contentIndex: Position |
thinking_start |
Thinking block starts |
contentIndex: Position in content array |
thinking_delta |
Thinking chunk received |
delta: New text, contentIndex: Position |
thinking_end |
Thinking block complete |
content: Full thinking, contentIndex: Position |
toolcall_start |
Tool call begins |
contentIndex: Position in content array |
toolcall_delta |
Tool arguments streaming |
delta: JSON chunk, partial.content[contentIndex].arguments: Partial parsed args |
toolcall_end |
Tool call complete |
toolCall: Complete validated tool call with id, name, arguments |
done |
Stream complete |
reason: Stop reason ("stop", "length", "toolUse"), message: Final assistant message |
error |
Error occurred |
reason: Error type ("error" or "aborted"), error: AssistantMessage with partial content |
Image Input
Models with vision capabilities can process images. You can check if a model supports images via the input property. If you pass images to a non-vision model, they are silently ignored.
import * as fs from "node:fs";
import { getModel, complete } from "@oh-my-pi-zen/pi-ai";
const model = getModel("openai", "gpt-4o-mini");
// Check if model supports images
if (model.input.includes("image")) {
console.log("Model supports vision");
}
const imageBuffer = fs.readFileSync("image.png");
const base64Image = imageBuffer.toBase64();
const response = await complete(model, {
messages: [
{
role: "user",
content: [
{ type: "text", text: "What is in this image?" },
{ type: "image", data: base64Image, mimeType: "image/png" },
],
},
],
});
// Access the response
for (const block of response.content) {
if (block.type === "text") {
console.log(block.text);
}
}
Thinking/Reasoning
Many models support thinking/reasoning capabilities where they can show their internal thought process. You can check if a model supports reasoning via the reasoning property. If you pass reasoning options to a non-reasoning model, they are silently ignored.
Unified Interface (streamSimple/completeSimple)