Build with Sarvam AI in the Vercel AI SDK

View as Markdown

Overview

The Vercel AI SDK is a TypeScript toolkit for building AI-powered applications, giving you a single set of functions (generateText, streamText, generateObject, and more) that work the same way across different model providers. Instead of learning each provider’s own API, you write your app logic once against the AI SDK and swap providers by changing the model you pass in.

sarvam-ai-sdk is a community provider for the Vercel AI SDK that wraps Sarvam’s chat completion, text-to-speech, speech-to-text, translation, transliteration, and language identification APIs behind the AI SDK’s standard functions: generateText, generateObject, generateSpeech, and transcribe.

If you already build with the AI SDK, this lets you swap in Sarvam models without changing how you call generateText or stream responses, and it works alongside tool calling and structured output the same way any other AI SDK provider does.

sarvam-ai-sdk versions track a specific major version of ai. Install matching versions or you will hit type and runtime mismatches.

Sarvam AI SDK versionVercel AI SDK version
0.5.x (beta)8.x.x (beta)
0.4.x (current)7.x.x (current)
0.3.x6.x.x
0.2.x5.x.x
0.1.x4.x.x

Quick start

1. Install

$npm install sarvam-ai-sdk ai@7

sarvam-ai-sdk currently tracks AI SDK v7; installing ai@latest can silently pull in an incompatible future major version, so pin the major version shown in the compatibility table above.

2. Set your API key

Get an API key from dashboard.sarvam.ai and add it to your environment:

.env
$SARVAM_API_KEY="your_api_key"

3. Create a provider instance

1import { sarvam } from "sarvam-ai-sdk";

sarvam reads SARVAM_API_KEY from the environment automatically, so no explicit client setup is needed.

4. Generate text

1import { sarvam } from "sarvam-ai-sdk";
2import { generateText } from "ai";
3
4try {
5 const { text } = await generateText({
6 model: sarvam("sarvam-30b"),
7 prompt: "Translate this to malayalam: 'Keep cooking, guys'",
8 });
9
10 console.log(text); // പാചകം തുടരൂ, സുഹൃത്തുക്കളേ
11} catch (error) {
12 console.error("generateText failed:", error);
13}

If longer completions come back truncated mid-sentence, the model is hitting its output token limit. Raise the limit and check the finish reason to confirm when a response was truncated. Through the AI SDK this is maxOutputTokens / finishReason; calling Sarvam directly (Python or REST) it’s the underlying max_tokens / finish_reason:

1const result = await generateText({
2 model: sarvam("sarvam-30b"),
3 prompt: "Write a detailed explanation of...",
4 maxOutputTokens: 4096,
5});
6
7if (result.finishReason === "length") {
8 console.warn("Response was truncated; consider raising maxOutputTokens further.");
9}

Text-to-speech

Use generateSpeech with sarvam.speech(model, targetLanguage):

1import { sarvam } from "sarvam-ai-sdk";
2import { generateSpeech } from "ai";
3import { writeFile } from "fs/promises";
4
5try {
6 const { audio } = await generateSpeech({
7 model: sarvam.speech("bulbul:v3", "ml-IN"),
8 text: "പാചകം തുടരൂ, സുഹൃത്തുക്കളേ",
9 });
10
11 const audioBuffer = Buffer.from(audio.base64, "base64");
12 await writeFile("./output.wav", audioBuffer);
13} catch (error) {
14 console.error("generateSpeech failed:", error);
15}

See Text to Speech for supported languages, speakers, and audio options available on the underlying API.

Speech-to-text

Use transcribe with sarvam.transcription(model, language):

1import { sarvam } from "sarvam-ai-sdk";
2import { transcribe } from "ai";
3import { readFile } from "fs/promises";
4
5try {
6 const { text } = await transcribe({
7 model: sarvam.transcription("saaras:v3", "en-IN"),
8 audio: await readFile("./input.wav"),
9 });
10
11 console.log(text); // Pachakam thudaroo, suhruthukkale.
12} catch (error) {
13 console.error("transcribe failed:", error);
14}

See Saaras and Saarika (Legacy) for model details.

Translation

1import { sarvam } from "sarvam-ai-sdk";
2import { generateText } from "ai";
3
4try {
5 const result = await generateText({
6 model: sarvam.translation("mayura:v1", {
7 from: "ml-IN",
8 to: "en-IN",
9 }),
10 prompt: "ഇതൊക്കെ ശ്രദ്ധിക്കണ്ടേ അംബാനെ?",
11 });
12
13 console.log(result.text); // Shouldn't we be careful about this, Ambane?
14} catch (error) {
15 console.error("Translation failed:", error);
16}

Only prompt and role: user messages are translated; system and assistant messages pass through unchanged.

Transliteration

1import { sarvam } from "sarvam-ai-sdk";
2import { generateText } from "ai";
3
4try {
5 const result = await generateText({
6 model: sarvam.transliterate({
7 to: "ml-IN",
8 from: "en-IN", // optional
9 }),
10 prompt: "eda mone, happy alle?",
11 });
12
13 console.log(result.text); // എടാ മോനെ, ഹാപ്പി അല്ലേ?
14} catch (error) {
15 console.error("Transliteration failed:", error);
16}

Language identification

1import { sarvam } from "sarvam-ai-sdk";
2import { generateText } from "ai";
3
4try {
5 const result = await generateText({
6 model: sarvam.languageIdentification(),
7 prompt: "ബുദ്ധിയാണ് സാറേ ഇവൻ്റെ മെയിൻ",
8 });
9
10 console.log(result.text); // ml-IN
11} catch (error) {
12 console.error("Language identification failed:", error);
13}

Tool calling

Sarvam chat models support the AI SDK’s standard tool() interface:

1import { z } from "zod";
2import { generateText, tool } from "ai";
3import { sarvam } from "sarvam-ai-sdk";
4
5try {
6 const result = await generateText({
7 model: sarvam("sarvam-30b"),
8 tools: {
9 weather: tool({
10 description: "Get the weather in a location",
11 inputSchema: z.object({
12 location: z.string(),
13 }),
14 execute: async ({ location }) => ({
15 location,
16 temperature: 72 + Math.floor(Math.random() * 21) - 10,
17 }),
18 }),
19 },
20 instructions: "You are a helpful AI",
21 prompt: "കൊച്ചിയിലെ കാലാവസ്ഥ എന്താണ്?",
22 });
23
24 console.log(result.toolResults);
25} catch (error) {
26 console.error("Tool call failed:", error);
27}

Structured output

Prefer generateText with Output.object; generateObject still works but is deprecated in the AI SDK:

1import { z } from "zod";
2import { sarvam } from "sarvam-ai-sdk";
3import { generateText, Output } from "ai";
4
5try {
6 const { output } = await generateText({
7 model: sarvam("sarvam-105b"),
8 output: Output.object({
9 name: "Recipe",
10 description: "A recipe with a name, ingredients and steps",
11 schema: z.object({
12 recipe: z.object({
13 name: z.string(),
14 ingredients: z.array(z.string()),
15 steps: z.array(z.string()),
16 }),
17 }),
18 }),
19 prompt: "Generate a South Indian recipe, in Malayalam",
20 });
21
22 console.log(output);
23} catch (error) {
24 console.error("Structured output generation failed:", error);
25}

All APIs at a glance

1import { sarvam } from "sarvam-ai-sdk";
2
3// Chat completion
4sarvam("sarvam-105b");
5sarvam.languageModel("sarvam-30b");
6
7// Transliteration
8sarvam.transliterate({ to: "ml-IN", from: "en-IN" });
9
10// Translation
11sarvam.translation("mayura:v1", { from: "en-IN", to: "ml-IN" });
12
13// Language identification
14sarvam.languageIdentification();
15
16// Text-to-speech
17sarvam.speech("bulbul:v3", "ml-IN");
18
19// Speech-to-text
20sarvam.transcription("saaras:v3");
FunctionAI SDK entry pointUnderlying Sarvam capability
sarvam("sarvam-105b") / sarvam.languageModel(...)generateText, generateObject, streamTextChat completion
sarvam.translation(model, { from, to })generateTextTranslation
sarvam.transliterate({ from, to })generateTextTransliteration
sarvam.languageIdentification()generateTextLanguage identification
sarvam.speech(model, targetLanguage)generateSpeechText to Speech
sarvam.transcription(model, language)transcribeSpeech to Text

Troubleshooting

Type or runtime errors after install: Your sarvam-ai-sdk and ai versions are mismatched. Check the version table above and pin ai to the major version your sarvam-ai-sdk version expects (for example ai@6 with sarvam-ai-sdk@0.3.x).

401/403 from Sarvam: Confirm SARVAM_API_KEY is set in the environment the process actually reads (.env loaded, no stray whitespace in the key). Sarvam’s REST API returns 403 (not 401) for auth failures; see Errors & Troubleshooting.

Translation/transliteration/LID returns the input unchanged: These wrappers only act on prompt and role: user messages; system and assistant messages are passed through as-is by design.

generateObject deprecation warnings: Migrate to generateText with Output.object(...) as shown above; generateObject still works but is deprecated upstream in the AI SDK.

Responses get cut off partway through: Output length is capped by default (maxOutputTokens in the AI SDK, max_tokens when calling Sarvam directly from Python or REST), so long completions can stop mid-sentence. Raise the limit and check the finish reason (finishReason / finish_reason equals "length") to confirm when a response was truncated; see the Generate text section above for examples in JavaScript, Python, and cURL.


Additional resources


Need help?