# sarvam-ai-react-native

A production-ready React Native toolkit for Sarvam AI, built on top of the official [`sarvamai`](https://www.npmjs.com/package/sarvamai) TypeScript SDK.

## Features

- Speech to text from audio files
- Text to speech with playback
- Voice assistant orchestration (record -> transcribe -> chat -> synthesize -> play)
- Audio recording utilities
- Audio playback utilities
- Chat helpers with streaming support
- React hooks for chat and voice assistant UX

## Installation

```bash
npm install sarvam-ai-react-native sarvamai react-native-permissions react-native-audio-recorder-player
```

Peer dependencies:

```bash
npm install react react-native
```

## React Native Setup (CLI)

### iOS

Add microphone permission in `Info.plist`:

```xml
<key>NSMicrophoneUsageDescription</key>
<string>App requires microphone access for voice input.</string>
```

Then run:

```bash
cd ios && pod install
```

### Android

Add permissions in `android/app/src/main/AndroidManifest.xml`:

```xml
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<uses-permission android:name="android.permission.READ_MEDIA_AUDIO" />
```

For Android 12 and below, also include:

```xml
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
```

## Basic Usage

```ts
import { SarvamRNClient } from 'sarvam-ai-react-native';

const client = new SarvamRNClient({ apiKey: process.env.SARVAM_API_KEY! });

const translated = await client.translateText('Hello', 'hi-IN');
const text = translated.translatedText;

const stt = await client.speechToTextFromFile('/path/to/audio.wav');
const transcript = stt.transcript;

const tts = await client.textToSpeech('Welcome to Sarvam AI');
await client.playSpeech('Welcome to Sarvam AI');

const chat = await client.chat([
  { role: 'user', content: 'Give me a short weather summary.' }
]);
```

## Streaming Chat

```ts
const result = await client.chat(
  [{ role: 'user', content: 'Explain quantum tunneling simply.' }],
  {
    stream: true,
    onToken: (token) => {
      console.log('token:', token);
    }
  }
);

console.log('final:', result.message);
```

## Audio Utilities

```ts
import { startRecording, stopRecording, playAudio, stopAudio } from 'sarvam-ai-react-native';

await startRecording();
const recording = await stopRecording();

await playAudio(recording.filePath);
await stopAudio();
```

## Voice Assistant Class

```ts
import { SarvamRNClient, VoiceAssistant } from 'sarvam-ai-react-native';

const client = new SarvamRNClient({ apiKey: '<API_KEY>' });

const assistant = new VoiceAssistant(client, {
  autoPlay: true,
  chatOptions: { model: 'sarvam-m' },
  textToSpeechOptions: { targetLanguageCode: 'en-IN', format: 'wav' }
});

assistant.onTranscript((text) => console.log('Transcript:', text));
assistant.onResponse((text) => console.log('Response:', text));
assistant.onAudio((audio) => console.log('Audio base64 length:', audio.length));

await assistant.startListening();
// user speaks...
const result = await assistant.stopListening();
console.log(result.response);
```

## React Hooks

### `useSarvamChat`

```tsx
import React, { useMemo, useState } from 'react';
import { Button, TextInput, View } from 'react-native';
import { SarvamRNClient, useSarvamChat } from 'sarvam-ai-react-native';

export function ChatScreen() {
  const [text, setText] = useState('');
  const client = useMemo(() => new SarvamRNClient({ apiKey: '<API_KEY>' }), []);
  const { messages, sendMessage, loading } = useSarvamChat(client, { stream: true });

  return (
    <View>
      <TextInput value={text} onChangeText={setText} />
      <Button
        title={loading ? 'Sending...' : 'Send'}
        onPress={async () => {
          await sendMessage(text);
          setText('');
        }}
      />
    </View>
  );
}
```

### `useVoiceAssistant`

```tsx
import React, { useMemo } from 'react';
import { Button, Text, View } from 'react-native';
import { SarvamRNClient, useVoiceAssistant } from 'sarvam-ai-react-native';

export function VoiceScreen() {
  const client = useMemo(() => new SarvamRNClient({ apiKey: '<API_KEY>' }), []);
  const { isListening, transcript, response, startListening, stopListening, processing } =
    useVoiceAssistant(client, { autoPlay: true });

  return (
    <View>
      <Button
        title={isListening ? 'Stop Listening' : 'Start Listening'}
        disabled={processing}
        onPress={isListening ? stopListening : startListening}
      />
      <Text>Transcript: {transcript}</Text>
      <Text>Response: {response}</Text>
    </View>
  );
}
```

## API Overview

### `SarvamRNClient`

- `translateText(input, targetLanguage)`
- `speechToTextFromFile(filePath)`
- `recordAndTranscribe()`
- `textToSpeech(text)`
- `playSpeech(text)`
- `chat(messages)`

### Voice Assistant

`VoiceAssistant` provides:

- `startListening()`
- `stopListening()`
- `onTranscript(listener)`
- `onResponse(listener)`
- `onAudio(listener)`

## Example

See [`example/App.tsx`](./example/App.tsx) for a full chat + voice flow.

## License

MIT
