DEV Community

Abhishek Gupta
Abhishek Gupta

Posted on

πŸš€ Sarvam AI Complete Guide for Beginners (JavaScript + Python)

What is Sarvam AI?

Sarvam AI is an Indian Generative AI platform that provides Large Language Models (LLMs), speech AI, translation, voice agents, and AI APIs for developers.

Think of Sarvam AI as India's version of services like:

  • OpenAI
  • Anthropic
  • Google Gemini

Using Sarvam APIs, developers can:

  • Build AI chatbots
  • Generate text
  • Summarize documents
  • Translate Indian languages
  • Create voice assistants
  • Build customer support systems
  • Integrate AI into websites and mobile apps

Why Use Sarvam AI?

Benefits

βœ… Indian Language Support

βœ… Simple API Integration

βœ… Fast Response

βœ… Production Ready

βœ… Multiple AI Models

βœ… Voice and Speech Capabilities

βœ… Developer Friendly SDKs


Architecture Overview

User β†’ Your Application β†’ Sarvam API β†’ AI Model β†’ Response

Example:

User asks:

"Explain Artificial Intelligence"

Your backend sends request to Sarvam.

Sarvam processes the request using an LLM.

The AI generates an answer.

The answer is returned to your application.


Step 1: Create a Sarvam Account

Visit:

Sarvam AI Platform

Create an account using:

  • Google Login
  • Email Login

After verification, access the developer dashboard.


Step 2: Generate an API Key

After login:

  1. Open Dashboard
  2. Go to API Keys
  3. Click Create API Key
  4. Copy the generated key

Example:

sk_xxxxxxxxxxxxxxxxxxxxx
Enter fullscreen mode Exit fullscreen mode

⚠️ Never expose your API key publicly.

Bad:

const apiKey = "sk_xxxxxxxxx";
Enter fullscreen mode Exit fullscreen mode

Good:

SARVAM_API_KEY=sk_xxxxxxxxx
Enter fullscreen mode Exit fullscreen mode

Step 3: Install SDK

JavaScript / Node.js

npm install sarvamai
Enter fullscreen mode Exit fullscreen mode

or

yarn add sarvamai
Enter fullscreen mode Exit fullscreen mode

Python

pip install sarvamai
Enter fullscreen mode Exit fullscreen mode

Understanding Chat Completions

A Chat Completion API allows you to send messages to an AI model and receive a response.

Example:

User:
What is Machine Learning?

AI:
Machine Learning is a branch of AI...
Enter fullscreen mode Exit fullscreen mode

JavaScript Example

Basic Setup

import { SarvamAIClient } from "sarvamai";

const client = new SarvamAIClient({
  apiSubscriptionKey: process.env.SARVAM_API_KEY,
});
Enter fullscreen mode Exit fullscreen mode

Complete Example

import { SarvamAIClient } from "sarvamai";
import dotenv from "dotenv";

dotenv.config();

const client = new SarvamAIClient({
  apiSubscriptionKey: process.env.SARVAM_API_KEY,
});

async function main() {
  try {
    const response = await client.chat.completions({
      model: "sarvam-30b",
      messages: [
        {
          role: "user",
          content: "Explain the significance of the Indian monsoon season.",
        },
      ],
      temperature: 0.5,
      top_p: 1,
      max_tokens: 1000,
    });

    console.log(response.choices[0].message.content);
  } catch (error) {
    console.error(error);
  }
}

main();
Enter fullscreen mode Exit fullscreen mode

Understanding Every Parameter

model

model: "sarvam-30b"
Enter fullscreen mode Exit fullscreen mode

Specifies which AI model to use.

Think of it as selecting the AI brain.


messages

messages: [
  {
    role: "user",
    content: "Hello"
  }
]
Enter fullscreen mode Exit fullscreen mode

Conversation history sent to the AI.


role

Three common roles:

user

Question from user.

{
  role: "user",
  content: "What is AI?"
}
Enter fullscreen mode Exit fullscreen mode

assistant

Previous AI response.

{
  role: "assistant",
  content: "AI stands for Artificial Intelligence."
}
Enter fullscreen mode Exit fullscreen mode

system

Instructions for AI behavior.

{
  role: "system",
  content: "You are a helpful teacher."
}
Enter fullscreen mode Exit fullscreen mode

temperature

temperature: 0.5
Enter fullscreen mode Exit fullscreen mode

Controls creativity.

Low Temperature

temperature: 0.1
Enter fullscreen mode Exit fullscreen mode

More factual and predictable.


Medium Temperature

temperature: 0.5
Enter fullscreen mode Exit fullscreen mode

Balanced output.


High Temperature

temperature: 1
Enter fullscreen mode Exit fullscreen mode

More creative responses.


top_p

top_p: 1
Enter fullscreen mode Exit fullscreen mode

Controls how many probable words can be selected.

Example

Predictions:

Coffee = 40%
Tea = 30%
Milk = 20%
Water = 10%
Enter fullscreen mode Exit fullscreen mode

If:

top_p = 0.8
Enter fullscreen mode Exit fullscreen mode

AI may only consider:

Coffee
Tea
Milk
Enter fullscreen mode Exit fullscreen mode

max_tokens

max_tokens: 1000
Enter fullscreen mode Exit fullscreen mode

Maximum response length.

Higher value:

  • Longer answers
  • Higher cost
  • More tokens consumed

Multi-Turn Conversation

const response = await client.chat.completions({
  model: "sarvam-30b",
  messages: [
    {
      role: "system",
      content: "You are a helpful coding mentor.",
    },
    {
      role: "user",
      content: "What is JavaScript?",
    },
    {
      role: "assistant",
      content: "JavaScript is a programming language.",
    },
    {
      role: "user",
      content: "Give me an example.",
    },
  ],
});
Enter fullscreen mode Exit fullscreen mode

The AI remembers previous messages in the conversation.


Python Example

Basic Setup

from sarvamai import SarvamAIClient
import os

client = SarvamAIClient(
    api_subscription_key=os.getenv("SARVAM_API_KEY")
)
Enter fullscreen mode Exit fullscreen mode

Complete Python Example

from sarvamai import SarvamAIClient
import os

client = SarvamAIClient(
    api_subscription_key=os.getenv("SARVAM_API_KEY")
)

response = client.chat.completions(
    model="sarvam-30b",
    messages=[
        {
            "role": "user",
            "content": "Explain Artificial Intelligence"
        }
    ],
    temperature=0.5,
    top_p=1,
    max_tokens=500
)

print(response.choices[0].message.content)
Enter fullscreen mode Exit fullscreen mode

Express.js API Example

Create your own AI endpoint.

import express from "express";
import dotenv from "dotenv";
import { SarvamAIClient } from "sarvamai";

dotenv.config();

const app = express();

app.use(express.json());

const client = new SarvamAIClient({
  apiSubscriptionKey: process.env.SARVAM_API_KEY,
});

app.post("/chat", async (req, res) => {
  try {
    const { message } = req.body;

    const response = await client.chat.completions({
      model: "sarvam-30b",
      messages: [
        {
          role: "user",
          content: message,
        },
      ],
    });

    return res.json({
      success: true,
      response: response.choices[0].message.content,
    });
  } catch (error) {
    return res.status(500).json({
      success: false,
      error: error.message,
    });
  }
});

app.listen(3000);
Enter fullscreen mode Exit fullscreen mode

Error Handling

Always use try-catch.

try {
  const response = await client.chat.completions({
    model: "sarvam-30b",
    messages,
  });
} catch (error) {
  console.error(error);
}
Enter fullscreen mode Exit fullscreen mode

Common errors:

Invalid API Key

401 Unauthorized
Enter fullscreen mode Exit fullscreen mode

Rate Limit

429 Too Many Requests
Enter fullscreen mode Exit fullscreen mode

Server Error

500 Internal Server Error
Enter fullscreen mode Exit fullscreen mode

Best Practices

Use Environment Variables

SARVAM_API_KEY=your_key
Enter fullscreen mode Exit fullscreen mode

Validate Input

if (!message) {
  return res.status(400).json({
    error: "Message required",
  });
}
Enter fullscreen mode Exit fullscreen mode

Limit Token Usage

max_tokens: 300
Enter fullscreen mode Exit fullscreen mode

Prevents unnecessary cost.


Add Logging

console.log("Request received");
Enter fullscreen mode Exit fullscreen mode

Useful for debugging.


Real-World Use Cases

Customer Support Bot

User β†’ Question
AI β†’ Answer
Enter fullscreen mode Exit fullscreen mode

Internal Company Assistant

Employees β†’ Ask Questions
AI β†’ Company Knowledge
Enter fullscreen mode Exit fullscreen mode

FAQ Generator

Document β†’ AI
AI β†’ FAQ List
Enter fullscreen mode Exit fullscreen mode

Content Generation

Topic β†’ AI
AI β†’ Blog Post
Enter fullscreen mode Exit fullscreen mode

Education Platform

Student Question β†’ AI
AI β†’ Explanation
Enter fullscreen mode Exit fullscreen mode

Top comments (0)