npmai-client
v1.0.2
Published
A lightweight Node.js client for the OpenRouter API
Maintainers
Readme
NPM AI Client for OpenRouter
A lightweight, easy-to-use Node.js client for the OpenRouter API that simplifies sending chat completion requests to various AI models and handling structured JSON responses.
Installation
```bash npm install npmai-client ```
Basic Usage
```javascript const NpmAiClient = require('npmai-client'); const ai = new NpmAiClient(process.env.OPENROUTER_API_KEY);
// Define chat messages const messages = [ { role: "system", content: "You are a helpful assistant. Output your response in JSON format: { "answer": "string" }" }, { role: "user", content: "What is JavaScript?" } ];
// Send a request to a specific model ai.ask("google/gemini-pro", messages) .then(response => { // Access the parsed JSON response const answer = response.get("answer"); console.log("Answer:", answer); }) .catch(error => { console.error("Error:", error); }); ```
Features
- Simple API for sending chat completion requests
- Automatic JSON parsing of AI responses
- Helper methods for accessing structured data
- Support for all OpenRouter models
- Fallback model routing
- Comprehensive error handling
- Structured Outputs - Enforce JSON Schema validation on model responses
Structured Outputs
For models that support it (like OpenAI's GPT-4o), you can enforce a specific JSON schema:
```javascript // Define your JSON schema const schema = { name: "weather_info", strict: true, schema: { type: "object", properties: { location: { type: "string", description: "City name" }, temperature: { type: "number", description: "Temperature in Celsius" } }, required: ["location", "temperature"] } };
// Use the askForJson method
ai.askForJson("openai/gpt-4o", messages, schema)
.then(response => {
const data = response.getRawJson();
console.log(It's ${data.temperature}°C in ${data.location});
});
```
API Reference
NpmAiClient
```javascript // Initialize with API key const ai = new NpmAiClient(apiKey, options);
// Send a request const response = await ai.ask(modelName, messages, options); // or const response = await ai.chat(modelName, messages, options); // or with structured output const response = await ai.askForJson(modelName, messages, jsonSchema, options); ```
ApiResponse
```javascript // Get a value by key const value = response.get("key");
// Get an array by key const list = response.getList("items");
// Get the full parsed JSON const json = response.getRawJson();
// Get the raw API response const rawResponse = response.getRawResponse();
// Check if JSON was parsed successfully const isParsed = response.isJsonParsed();
// Get the model used const model = response.getModel();
// Get token usage const usage = response.getUsage(); ```
For full documentation, see doc.md.
License
MIT
