metrioai-js-sdk
v1.0.60
Published
The Metrio AI SDK for JavaScript and Typescript
Downloads
192
Readme
MetrioAI JavaScript SDK
The official JavaScript SDK for MetrioAI, providing a convenient way to interact with the MetrioAI API from JavaScript and TypeScript applications.
Installation
# Using npm
npm install metrioai-js-sdk
# Using yarn
yarn add metrioai-js-sdk
# Using pnpm
pnpm add metrioai-js-sdkQuick Start
import { MetrioAI } from 'metrioai-js-sdk';
// Initialize the SDK with your API key
const metrioai = new MetrioAI({
apiKey: 'your-api-key',
// Optional: customize configuration
baseUrl: 'https://api.metrio.ai', // Default API endpoint
maxRetries: 3, // Number of retry attempts for failed requests
retryDelay: 500 // Delay between retries (milliseconds)
});
// You can also set your API key via environment variable
// METRIOAI_API_KEY=your-api-key
// METRIOAI_BASE_URL=https://api.metrio.ai (optional)Features
The SDK provides the following main functionalities:
Get Available Providers
const providers = await metrioai.providers();
console.log(providers.providers); // ['openai', 'claude', 'gemini', 'xai', ...]Get Available Models for a Provider
const models = await metrioai.models('openai');
console.log(models.models); // ['gpt-3.5-turbo', 'gpt-4', ...]Chat Completion
Send a conversation to the API:
const messages = [
{
role: 'user',
content: {
type: 'text',
text: 'What is the capital of France?'
}
}
];
const response = await metrioai.chatCompletion({
projectId: 1,
promptId: 1,
messages: messages,
// Optional parameters
variables: [{ name: 'customVar', value: 'customValue' }],
tag: 'custom-tag'
});
console.log(response.response); // The AI-generated response
console.log(response.input_tokens); // Number of input tokens
console.log(response.output_tokens); // Number of output tokens
console.log(response.elapsed_time); // Time taken to generate the responseEvaluate a Prompt
Test a prompt with specific model settings:
const evalResponse = await metrioai.evaluate({
projectId: 1,
promptId: 1,
modelProvider: 'openai',
modelName: 'gpt-3.5-turbo',
modelSettings: {
temperature: 0.7,
maxTokens: 1000,
topP: 0.9,
topK: 40,
frequencyPenalty: 0,
presencePenalty: 0
},
messages: [
{
role: 'user',
content: {
type: 'text',
text: 'What is the capital of France?'
}
}
],
// Optional: specify output format
outputFormat: 'json'
});System Messages
Include system messages for context:
const messages = [
{
role: 'system',
content: {
type: 'text',
text: 'You are a helpful assistant.'
}
},
{
role: 'user',
content: {
type: 'text',
text: 'What is the capital of France?'
}
}
];
const completion = await metrioai.chatCompletion({
projectId: 1,
promptId: 1,
messages: messages,
// Optional parameters
tag: 'geography-questions'
});Streaming Responses
The SDK supports streaming responses for chat completions:
// Enable streaming with a callback function
const completion = await metrioai.chatCompletion({
projectId: 1,
promptId: 1,
messages: messages,
stream: true // Enable streaming
}, (chunk) => {
// This callback is called for each chunk of the response
console.log('Received chunk:', chunk.chunk);
});
// The completion variable will contain the complete response when streaming is done
console.log('Final response:', completion.response);The SDK handles both SSE-formatted responses (starting with data:) and plain text responses. This provides flexibility to work with different server implementations:
- SSE-formatted chunks are parsed as JSON and provide full metadata (tokens, timing)
- Plain text lines are treated as response chunks with just the text content
- The final response combines all chunks into a complete response
Multimodal Support
The SDK supports multimodal inputs (text, images, PDFs):
Text Input
// Standard text input is shown in the examples aboveImage Input
// Using an image in chat messages
const completion = await metrioai.chatCompletion({
projectId: 1,
promptId: 1,
messages: [
{
role: 'user',
content: {
type: 'image',
mime: 'image/jpeg',
data: 'base64encodedimagedata...'
}
}
]
});PDF Input
// Using PDF in messages
const completion = await metrioai.chatCompletion({
projectId: 1,
promptId: 1,
messages: [
{
role: 'user',
content: {
type: 'pdf',
mime: 'application/pdf',
data: 'base64encodedpdfdata...'
}
}
]
});Advanced Error Handling
The SDK provides robust error handling with detailed error information:
try {
const response = await metrioai.chatCompletion({
projectId: 1,
promptId: 1,
messages: [{
role: 'user',
content: {
type: 'text',
text: 'Hello'
}
}]
});
} catch (error) {
if (error instanceof MetrioApiError) {
console.error('API Error:', error.message);
console.error('Status Code:', error.statusCode);
console.error('Response Data:', error.responseData);
console.error('Request Data:', error.requestData);
} else {
console.error('Unexpected error:', error);
}
}Automatic Retries
The SDK automatically retries failed requests that are considered retryable (network errors, timeouts, or 5xx server errors):
// Configure retry behavior when creating the client
const metrioai = new MetrioAI({
apiKey: 'your-api-key',
maxRetries: 5, // Maximum retry attempts (default: 3)
retryDelay: 1000 // Base delay between retries in ms (default: 500)
});TypeScript Support
This SDK is fully written in TypeScript and provides comprehensive type definitions for all its functions, parameters, and responses:
import { MetrioAI, MetrioApiError, RunParams, RunResponse, Message, MessageContent } from 'metrioai-js-sdk';
// Type-safe usage example
const params: RunParams = {
projectId: 1,
promptId: 1,
messages: [{
role: 'user',
content: {
type: 'text',
text: 'Hello'
}
}]
};
try {
const response: RunResponse = await metrioai.chatCompletion(params);
} catch (error) {
if (error instanceof MetrioApiError) {
// Handle API error with typed properties
}
}License
This SDK is licensed under the BSD 3-Clause License.
Support
For any questions or issues, please contact [email protected].
