
Security News
npm Adopts OIDC for Trusted Publishing in CI/CD Workflows
npm now supports Trusted Publishing with OIDC, enabling secure package publishing directly from CI/CD workflows without relying on long-lived tokens.
A lightweight library for making AI API calls with streaming support.
npm install call-ai
# or
yarn add call-ai
# or
pnpm add call-ai
import { callAi } from 'call-ai';
// Basic usage with string prompt (non-streaming by default)
const response = await callAi('Explain quantum computing in simple terms', {
apiKey: 'your-api-key',
model: 'gpt-4'
});
// The response is the complete text
console.log(response);
// With streaming enabled (returns an AsyncGenerator)
const generator = callAi('Tell me a story', {
apiKey: 'your-api-key',
model: 'gpt-4',
stream: true
});
// Process streaming updates
for await (const chunk of generator) {
console.log(chunk); // Streaming updates as they arrive
}
// Using message array for more control
const messages = [
{ role: 'system', content: 'You are a helpful assistant.' },
{ role: 'user', content: 'Explain quantum computing in simple terms' }
];
const response = await callAi(messages, {
apiKey: 'your-api-key',
model: 'gpt-4'
});
console.log(response);
// Using schema for structured output
const schema = {
name: "exercise_summary",
properties: {
title: { type: 'string' },
summary: { type: 'string' },
points: { type: 'array', items: { type: 'string' } }
},
required: ['title', 'summary']
};
const response = await callAi('Summarize the benefits of exercise', {
apiKey: 'your-api-key',
schema: schema
});
const structuredOutput = JSON.parse(response);
console.log(structuredOutput.title);
// Streaming with schema for OpenRouter structured JSON output
const schema = {
properties: {
title: { type: 'string' },
items: {
type: 'array',
items: {
type: 'object',
properties: {
name: { type: 'string' },
description: { type: 'string' }
}
}
}
}
};
const generator = callAi('Create a list of sci-fi books', {
apiKey: 'your-api-key',
stream: true,
schema: schema
});
for await (const chunk of generator) {
console.log(chunk); // Shows the partial JSON as it's being generated
}
stream: true
Call-AI supports all models available through OpenRouter, including:
Different LLMs have different strengths when working with structured data. Based on our testing, here's a guide to help you choose the right model for your schema needs:
Model Family | Grade | Simple Flat Schema | Complex Flat Schema | Nested Schema | Best For |
---|---|---|---|---|---|
OpenAI | A | ✅ Excellent | ✅ Excellent | ✅ Excellent | Most reliable for all schema types |
Gemini | A | ✅ Excellent | ✅ Excellent | ✅ Good | Good all-around performance, especially with flat schemas |
Claude | B | ✅ Excellent | ⚠️ Good (occasional JSON errors) | ✅ Good | Simple schemas, robust handling of complex prompts |
Llama 3 | C | ✅ Good | ✅ Good | ❌ Poor | Simpler flat schemas, may struggle with nested structures |
Deepseek | C | ✅ Good | ✅ Good | ❌ Poor | Basic flat schemas only |
Flat schemas perform better across all models. If you need maximum compatibility, avoid deeply nested structures.
Field names matter. Some models have preferences for certain property naming patterns:
name
, type
, items
, price
Model-specific considerations:
For mission-critical applications requiring schema adherence, use OpenAI models or implement fallback mechanisms.
You can provide your API key in three ways:
const response = await callAi('Hello', { apiKey: 'your-api-key' });
window.CALLAI_API_KEY = 'your-api-key';
const response = await callAi('Hello');
// Example of environment variable integration
import { callAi } from 'call-ai';
const apiKey = process.env.OPENAI_API_KEY || process.env.OPENROUTER_API_KEY;
const response = await callAi('Hello', { apiKey });
// Main function
function callAi(
prompt: string | Message[],
options?: CallAIOptions
): Promise<string> | AsyncGenerator<string, string, unknown>
// Types
type Message = {
role: 'user' | 'system' | 'assistant';
content: string;
};
interface Schema {
/**
* Optional schema name that will be sent to the model provider if supported
*/
name?: string;
properties: Record<string, any>;
required?: string[];
additionalProperties?: boolean;
}
interface CallAIOptions {
apiKey?: string;
model?: string;
endpoint?: string;
stream?: boolean;
schema?: Schema | null;
[key: string]: any;
}
apiKey
: Your API key (can also be set via window.CALLAI_API_KEY)model
: Model identifier (default: 'openrouter/auto')endpoint
: API endpoint (default: 'https://openrouter.ai/api/v1/chat/completions')stream
: Enable streaming responses (default: false)schema
: Optional JSON schema for structured outputMIT or Apache-2.0, at your option
npm test
npm run typecheck
The project includes integration tests that make real API calls to verify functionality with actual LLM models:
.env.example
to .env
and add your OpenRouter API keynpm run test:integration
Note: Integration tests are excluded from the normal test suite to avoid making API calls during CI/CD. They require a valid API key to execute and will be skipped if no key is provided.
This library uses GitHub Actions to automate the release process:
package.json
(follow semver)CHANGELOG.md
with details of changesgit commit -am "Release vX.Y.Z"
git tag -a vX.Y.Z -m "Version X.Y.Z"
git push origin main vX.Y.Z
The GitHub workflow in .github/workflows/publish.yml
will:
When making significant changes, remember to:
FAQs
Lightweight library for making AI API calls with streaming support
The npm package call-ai receives a total of 66 weekly downloads. As such, call-ai popularity was classified as not popular.
We found that call-ai demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 1 open source maintainer collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
npm now supports Trusted Publishing with OIDC, enabling secure package publishing directly from CI/CD workflows without relying on long-lived tokens.
Research
/Security News
A RubyGems malware campaign used 60 malicious packages posing as automation tools to steal credentials from social media and marketing tool users.
Security News
The CNA Scorecard ranks CVE issuers by data completeness, revealing major gaps in patch info and software identifiers across thousands of vulnerabilities.