> ## Documentation Index
> Fetch the complete documentation index at: https://ai-kb.automationanywhere.com/llms.txt
> Use this file to discover all available pages before exploring further.

# चैट SDK

> EKB Chat SDK का उपयोग करके अपने अनुप्रयोग में संवादी AI इंटरफ़ेस एकीकृत करें।

ChatSDK EKB Content Creator SDK का मूल घटक है जो आपको आसानी से संवादी AI अनुप्रयोग बनाने में सक्षम बनाता है। यह व्यापक चैट प्रबंधन, संदेश हैंडलिंग, स्ट्रीमिंग प्रतिक्रियाओं और ज्ञान आधार एकीकरण प्रदान करता है। इस लेख में आप SDK इंस्टॉल करना और हमारे 'त्वरित आरंभ' उदाहरण के साथ जल्दी शुरू करना सीखेंगे। आप विभिन्न कॉन्फ़िगरेशन विकल्पों का अन्वेषण कर सकते हैं, प्रमाणीकरण के बारे में जान सकते हैं, और इस SDK के साथ उपयोग की जा सकने वाली मूल विधियाँ सीख सकते हैं। आप उपयोग मामले के उदाहरण भी खोजेंगे।

## इंस्टॉलेशन

```bash theme={null}
npm install @odin-ai-staging/sdk
```

## त्वरित आरंभ

```typescript theme={null}
import { ChatSDK } from '@odin-ai-staging/sdk';

// SDK को आरंभ करें
const chatSDK = new ChatSDK({
  baseUrl: 'https://your-api-endpoint.com/',
  projectId: 'your-project-id',
  apiKey: 'your-api-key',
  apiSecret: 'your-api-secret'
});

// चैट बनाएँ और संदेश भेजें
async function quickExample() {
  // एक नई चैट बनाएँ
  const chat = await chatSDK.createChat('मेरी पहली चैट');
  
  // संदेश भेजें
  const response = await chatSDK.sendMessage('नमस्ते, आप मेरी कैसे मदद कर सकते हैं?', {
    chatId: chat.chat_id
  });
  
  console.log('AI प्रतिक्रिया:', response.message);
}
```

## कॉन्फ़िगरेशन

### ChatSDKConfig इंटरफ़ेस

```typescript theme={null}
interface ChatSDKConfig {
  baseUrl: string;          // API एंडपॉइंट URL
  projectId: string;        // आपका परियोजना पहचानकर्ता
  apiKey?: string;          // प्रमाणीकरण के लिए API key
  apiSecret?: string;       // प्रमाणीकरण के लिए API secret
  accessToken?: string;     // वेब ऐप उपयोग के लिए access token
}
```

### कॉन्फ़िगरेशन विकल्प

* **baseUrl**: आपके API एंडपॉइंट का आधार URL
* **projectId**: आपका अद्वितीय परियोजना पहचानकर्ता
* **apiKey** और **apiSecret**: सर्वर-साइड प्रमाणीकरण के लिए
* **accessToken**: क्लाइंट-साइड प्रमाणीकरण के लिए (वेब ऐप्स)

## प्रमाणीकरण

ChatSDK दो प्रमाणीकरण विधियों का समर्थन करता है:

### API Key प्रमाणीकरण (सर्वर-साइड)

```typescript theme={null}
const chatSDK = new ChatSDK({
  baseUrl: 'https://api.example.com/',
  projectId: 'proj_123',
  apiKey: 'your-api-key',
  apiSecret: 'your-api-secret'
});
```

### Access Token प्रमाणीकरण (क्लाइंट-साइड)

```typescript theme={null}
const chatSDK = new ChatSDK({
  baseUrl: 'https://api.example.com/',
  projectId: 'proj_123',
  accessToken: 'your-access-token'
});
```

## मूल विधियाँ

### चैट प्रबंधन

#### `createChat(name?, documentKeys?)`

एक नई चैट वार्तालाप बनाता है।

```typescript theme={null}
async createChat(
  name?: string,           // वैकल्पिक चैट नाम (डिफ़ॉल्ट "Untitled")
  documentKeys?: string[]  // ज्ञान आधार संदर्भ के लिए वैकल्पिक दस्तावेज़ keys
): Promise<CreateChatResponse>
```

**उदाहरण:**

```typescript theme={null}
// एक बुनियादी चैट बनाएँ
const chat = await chatSDK.createChat('ग्राहक सहायता चैट');

// ज्ञान आधार संदर्भ के साथ चैट बनाएँ
const chatWithDocs = await chatSDK.createChat(
  'उत्पाद दस्तावेज़ चैट',
  ['doc_key_1', 'doc_key_2']
);
```

#### `listChats(cursor?, limit?)`

परियोजना में चैट्स की पेजिनेटेड सूची प्राप्त करें।

```typescript theme={null}
async listChats(
  cursor?: number,  // पेजिनेशन के लिए वैकल्पिक कर्सर
  limit?: number    // लौटाने के लिए चैट्स की संख्या (डिफ़ॉल्ट: 30, अधिकतम: 100)
): Promise<ListChatsResponse>
```

**उदाहरण:**

```typescript theme={null}
// पहली 10 चैट्स प्राप्त करें
const chats = await chatSDK.listChats(undefined, 10);

// कर्सर का उपयोग करके अगला पेज प्राप्त करें
if (chats.next_cursor) {
  const nextPage = await chatSDK.listChats(chats.next_cursor, 10);
}
```

#### `getChatHistory(chatId)`

पूर्ण संदेश इतिहास के साथ चैट प्राप्त करें।

```typescript theme={null}
async getChatHistory(chatId: string): Promise<ChatHistoryResponse>
```

**उदाहरण:**

```typescript theme={null}
const chatHistory = await chatSDK.getChatHistory('chat_123');
console.log('संदेश:', chatHistory.messages);
```

#### `deleteChat(chatId)`

एक चैट और उसके सभी संदेशों को स्थायी रूप से हटाएँ।

```typescript theme={null}
async deleteChat(chatId: string): Promise<void>
```

**उदाहरण:**

```typescript theme={null}
await chatSDK.deleteChat('chat_123');
```

#### `updateChatName(chatId, newName)`

मौजूदा चैट का प्रदर्शन नाम अपडेट करें।

```typescript theme={null}
async updateChatName(chatId: string, newName: string): Promise<void>
```

**उदाहरण:**

```typescript theme={null}
await chatSDK.updateChatName('chat_123', 'अपडेटेड चैट नाम');
```

### संदेश हैंडलिंग

#### `sendMessage(message, options?)`

संदेश भेजें और AI प्रतिक्रिया प्राप्त करें।

```typescript theme={null}
async sendMessage(
  message: string,
  options?: SendMessageOptions
): Promise<SendMessageResponse>
```

**SendMessageOptions:**

```typescript theme={null}
interface SendMessageOptions {
  chatId?: string;          // लक्ष्य चैट ID
  agentType?: AgentType;    // उपयोग करने के लिए AI एजेंट प्रकार
  agentId?: string;         // विशिष्ट एजेंट ID
  documentKeys?: string[];  // ज्ञान आधार दस्तावेज़
  images?: File[];          // चित्र अनुलग्नक
  metadata?: Record<string, any>;  // कस्टम metadata
  modelName?: ModelName;    // उपयोग करने के लिए AI मॉडल
  useKnowledgebase?: boolean;      // ज्ञान आधार सक्षम करें
  isTest?: boolean;         // परीक्षण मोड फ़्लैग
  googleSearch?: boolean;   // वेब खोज सक्षम करें
  formatInstructions?: string;     // प्रतिक्रिया प्रारूप मार्गदर्शन
  ignoreChatHistory?: boolean;     // वार्तालाप इतिहास अनदेखा करें
  exampleJson?: string;     // संरचित प्रतिक्रियाओं के लिए उदाहरण JSON
  skipStream?: boolean;     // स्ट्रीमिंग अक्षम करें
}
```

**उदाहरण:**

```typescript theme={null}
// बुनियादी संदेश
const response = await chatSDK.sendMessage('कृत्रिम बुद्धिमत्ता क्या है?', {
  chatId: 'chat_123'
});

// विकल्पों के साथ उन्नत संदेश
const advancedResponse = await chatSDK.sendMessage(
  'इस डेटा का विश्लेषण करें और अंतर्दृष्टि प्रदान करें',
  {
    chatId: 'chat_123',
    modelName: 'gpt-4o',
    useKnowledgebase: true,
    googleSearch: true,
    formatInstructions: 'प्रतिक्रिया बुलेट पॉइंट्स में प्रदान करें'
  }
);
```

#### `sendFeedback(messageId, chatId, feedback)`

AI प्रतिक्रिया पर प्रतिक्रिया प्रदान करें।

```typescript theme={null}
async sendFeedback(
  messageId: string,
  chatId: string,
  feedback: boolean  // true = पसंद, false = नापसंद
): Promise<void>
```

**उदाहरण:**

```typescript theme={null}
// सकारात्मक प्रतिक्रिया
await chatSDK.sendFeedback('msg_123', 'chat_123', true);

// नकारात्मक प्रतिक्रिया
await chatSDK.sendFeedback('msg_123', 'chat_123', false);
```

## स्ट्रीमिंग समर्थन

### `sendMessageStream(message, options)`

वास्तविक समय स्ट्रीमिंग प्रतिक्रिया के साथ संदेश भेजें।

```typescript theme={null}
async sendMessageStream(
  message: string,
  options: SendMessageOptions & StreamCallbacks
): Promise<void>
```

**StreamCallbacks:**

```typescript theme={null}
interface StreamCallbacks {
  onChunk?: (chunk: string) => void;           // टेक्स्ट चंक्स
  onMessageObject?: (messageObject: any) => void;  // संरचित डेटा
  onComplete?: (message: Message) => void;     // अंतिम संदेश
  onError?: (error: Error) => void;           // त्रुटि हैंडलर
  onChatNameUpdate?: (chatName: string) => void;   // चैट नाम परिवर्तन
  onDocumentChunk?: (chunk: string) => void;  // दस्तावेज़ प्रसंस्करण अपडेट
  onMessageEnd?: () => void;                  // स्ट्रीम पूर्णता
}
```

**उदाहरण:**

```typescript theme={null}
await chatSDK.sendMessageStream(
  'मुझे मशीन लर्निंग के बारे में बताएँ',
  {
    chatId: 'chat_123',
    onChunk: (chunk) => {
      console.log('चंक:', chunk);
      updateUI(chunk);
    },
    onComplete: (message) => {
      console.log('पूर्ण संदेश:', message);
      finalizeUI(message);
    },
    onError: (error) => {
      console.error('स्ट्रीम त्रुटि:', error);
      showError(error.message);
    }
  }
);
```

## त्रुटि हैंडलिंग

SDK API-संबंधित विफलताओं के लिए `APIError` ऑब्जेक्ट्स फेंकता है:

```typescript theme={null}
interface APIError {
  message: string;  // त्रुटि विवरण
  status: number;   // HTTP स्थिति कोड
  detail?: string;  // अतिरिक्त त्रुटि विवरण
}
```

**उदाहरण:**

```typescript theme={null}
try {
  const response = await chatSDK.sendMessage('नमस्ते');
} catch (error) {
  if (error instanceof APIError) {
    console.error(`API त्रुटि ${error.status}: ${error.message}`);
    if (error.detail) {
      console.error('विवरण:', error.detail);
    }
  } else {
    console.error('अप्रत्याशित त्रुटि:', error);
  }
}
```

## उदाहरण

### बुनियादी चैट अनुप्रयोग

इस उदाहरण में, आप EKB SDK का उपयोग करके सरल, गैर-स्ट्रीमिंग संदेश विनिमय के साथ एक बुनियादी चैट अनुप्रयोग बनाना सीखेंगे। यह उदाहरण GPT-4o-mini मॉडल का उपयोग करता है और स्ट्रीमिंग कॉलबैक्स की जटिलता के बिना बुनियादी चैटबॉट कार्यक्षमता बनाने के लिए एक सीधी नींव प्रदान करता है।

```typescript theme={null}
import { ChatSDK } from '@odin-ai-staging/sdk';

class SimpleChatApp {
  private chatSDK: ChatSDK;
  private currentChatId?: string;

  constructor() {
    this.chatSDK = new ChatSDK({
      baseUrl: process.env.API_BASE_URL,
      projectId: process.env.PROJECT_ID,
      apiKey: process.env.API_KEY,
      apiSecret: process.env.API_SECRET
    });
  }

  async startNewChat(name: string = 'नई चैट') {
    try {
      const chat = await this.chatSDK.createChat(name);
      this.currentChatId = chat.chat_id;
      console.log(`चैट बनाई: ${chat.name} (${chat.chat_id})`);
      return chat;
    } catch (error) {
      console.error('चैट बनाने में विफल:', error);
      throw error;
    }
  }

  async sendMessage(message: string) {
    if (!this.currentChatId) {
      await this.startNewChat();
    }

    try {
      const response = await this.chatSDK.sendMessage(message, {
        chatId: this.currentChatId,
        modelName: 'gpt-4o-mini'
      });

      console.log('उपयोगकर्ता:', message);
      console.log('AI:', response.message);
      
      return response;
    } catch (error) {
      console.error('संदेश भेजने में विफल:', error);
      throw error;
    }
  }

  async getChatList() {
    try {
      const chats = await this.chatSDK.listChats();
      return chats.chats;
    } catch (error) {
      console.error('चैट सूची प्राप्त करने में विफल:', error);
      throw error;
    }
  }
}

const app = new SimpleChatApp();
await app.sendMessage('नमस्ते, आप कैसे हैं?');
```

### वास्तविक समय अपडेट के साथ स्ट्रीमिंग चैट

इस उदाहरण में, आप एक स्ट्रीमिंग चैट इंटरफ़ेस बनाना सीखेंगे जो EKB API से कनेक्ट होता है और AI प्रतिक्रियाओं को वास्तविक समय में प्रदर्शित करता है।

```typescript theme={null}
import { ChatSDK, StreamCallbacks } from '@odin-ai-staging/sdk';

class StreamingChat {
  private chatSDK: ChatSDK;
  private messageElement: HTMLElement;

  constructor(messageElement: HTMLElement) {
    this.messageElement = messageElement;
    this.chatSDK = new ChatSDK({
      baseUrl: 'https://your-api.com/',
      projectId: 'your-project-id',
      accessToken: 'your-access-token'
    });
  }

  async sendStreamingMessage(message: string, chatId: string) {
    this.messageElement.innerHTML = '';

    const callbacks: StreamCallbacks = {
      onChunk: (chunk: string) => {
        this.messageElement.innerHTML += chunk;
        this.messageElement.scrollIntoView();
      },
      onMessageObject: (messageObj: any) => {
        if (messageObj.image_urls) {
          this.displayImages(messageObj.image_urls);
        }
      },
      onComplete: (message: any) => {
        console.log('संदेश पूर्ण:', message);
        this.finalizeMessage(message);
      },
      onError: (error: Error) => {
        console.error('स्ट्रीमिंग त्रुटि:', error);
        this.messageElement.innerHTML = `त्रुटि: ${error.message}`;
      },
      onChatNameUpdate: (chatName: string) => {
        document.title = chatName;
      }
    };

    try {
      await this.chatSDK.sendMessageStream(message, {
        chatId,
        modelName: 'gpt-4o',
        useKnowledgebase: true,
        ...callbacks
      });
    } catch (error) {
      console.error('स्ट्रीमिंग संदेश भेजने में विफल:', error);
    }
  }

  private displayImages(imageUrls: string[]) {
    imageUrls.forEach(url => {
      const img = document.createElement('img');
      img.src = url;
      img.style.maxWidth = '100%';
      this.messageElement.appendChild(img);
    });
  }

  private finalizeMessage(message: any) {
    const feedbackDiv = document.createElement('div');
    feedbackDiv.innerHTML = `
      <button onclick="this.provideFeedback('${message.id}', true)">👍</button>
      <button onclick="this.provideFeedback('${message.id}', false)">👎</button>
    `;
    this.messageElement.appendChild(feedbackDiv);
  }

  async provideFeedback(messageId: string, isPositive: boolean) {
    try {
      await this.chatSDK.sendFeedback(messageId, 'chat_id', isPositive);
      console.log('प्रतिक्रिया सफलतापूर्वक भेजी गई');
    } catch (error) {
      console.error('प्रतिक्रिया भेजने में विफल:', error);
    }
  }
}
```

### ज्ञान आधार एकीकरण

इस उदाहरण में, आप एक ज्ञान आधार-संचालित चैट अनुप्रयोग बनाना सीखेंगे जो उन प्रश्नों के उत्तर दे सकता है जो आपके ज्ञान आधार में अपलोड किए गए विशिष्ट दस्तावेज़ों पर आधारित होते हैं।

```typescript theme={null}
import { ChatSDK } from '@odin-ai-staging/sdk';

class KnowledgeBasedChat {
  private chatSDK: ChatSDK;

  constructor() {
    this.chatSDK = new ChatSDK({
      baseUrl: process.env.API_BASE_URL,
      projectId: process.env.PROJECT_ID,
      apiKey: process.env.API_KEY,
      apiSecret: process.env.API_SECRET
    });
  }

  async createDocumentChat(documentKeys: string[], chatName?: string) {
    try {
      const chat = await this.chatSDK.createChat(
        chatName || 'दस्तावेज़ Q&A',
        documentKeys
      );
      
      console.log(`${documentKeys.length} दस्तावेज़ों के साथ दस्तावेज़ चैट बनाई`);
      return chat;
    } catch (error) {
      console.error('दस्तावेज़ चैट बनाने में विफल:', error);
      throw error;
    }
  }

  async askDocumentQuestion(question: string, chatId: string, documentKeys?: string[]) {
    try {
      const response = await this.chatSDK.sendMessage(question, {
        chatId,
        documentKeys,
        useKnowledgebase: true,
        agentType: 'document_agent',
        formatInstructions: 'अपने स्रोतों के लिए उद्धरण प्रदान करें'
      });

      if (response.message.sources) {
        console.log('स्रोत:', response.message.sources);
      }

      return response;
    } catch (error) {
      console.error('दस्तावेज़ प्रश्न पूछने में विफल:', error);
      throw error;
    }
  }
}

const kbChat = new KnowledgeBasedChat();
const chat = await kbChat.createDocumentChat(['doc_1', 'doc_2'], 'उत्पाद FAQ');
const answer = await kbChat.askDocumentQuestion(
  'उत्पाद की प्रमुख विशेषताएँ क्या हैं?',
  chat.chat_id
);
```

## सर्वोत्तम प्रथाएँ

### त्रुटि हैंडलिंग

हमेशा सभी SDK विधियों के लिए उचित त्रुटि हैंडलिंग लागू करें:

```typescript theme={null}
try {
  const response = await chatSDK.sendMessage(message, options);
} catch (error) {
  if (error instanceof APIError) {
    console.error(`API त्रुटि: ${error.message}`);
  } else {
    console.error('अप्रत्याशित त्रुटि:', error);
  }
}
```

### बेहतर UX के लिए स्ट्रीमिंग

वास्तविक समय प्रतिक्रिया प्रदान करने के लिए लंबी प्रतिक्रियाओं के लिए स्ट्रीमिंग का उपयोग करें:

```typescript theme={null}
await chatSDK.sendMessageStream(longQuery, {
  onChunk: (chunk) => updateUI(chunk),
  onComplete: (message) => finalizeUI(message)
});
```

### API कॉल्स को अनुकूलित करें

* प्रत्येक संदेश के लिए नई चैट बनाने के बजाय chat IDs का पुन: उपयोग करें
* चैट सूचियों के लिए पेजिनेशन का उपयोग करें
* बार-बार एक्सेस किए जाने वाले डेटा के लिए कैशिंग लागू करें

```typescript theme={null}
class OptimizedChatManager {
  private chatCache = new Map<string, any>();
  private currentChatId?: string;

  async getOrCreateChat(name?: string) {
    if (this.currentChatId) {
      return this.currentChatId;
    }
    const chat = await this.chatSDK.createChat(name);
    this.currentChatId = chat.chat_id;
    return this.currentChatId;
  }

  async getCachedChatHistory(chatId: string) {
    if (this.chatCache.has(chatId)) {
      return this.chatCache.get(chatId);
    }
    const history = await this.chatSDK.getChatHistory(chatId);
    this.chatCache.set(chatId, history);
    return history;
  }
}
```

### कॉन्फ़िगरेशन प्रबंधन

कॉन्फ़िगरेशन को सुरक्षित रूप से स्टोर करें और एनवायरनमेंट वेरिएबल्स का उपयोग करें:

```typescript theme={null}
// अच्छा: एनवायरनमेंट वेरिएबल्स का उपयोग करें
const chatSDK = new ChatSDK({
  baseUrl: process.env.ODIN_API_BASE_URL,
  projectId: process.env.ODIN_PROJECT_ID,
  apiKey: process.env.ODIN_API_KEY,
  apiSecret: process.env.ODIN_API_SECRET
});

// बुरा: क्रेडेंशियल्स हार्डकोड करें
const chatSDK = new ChatSDK({
  baseUrl: 'https://api.example.com',
  projectId: 'hardcoded-project-id',
  apiKey: 'hardcoded-api-key',
  apiSecret: 'hardcoded-secret'
});
```

### मेमोरी प्रबंधन

संसाधनों को साफ़ करें और मेमोरी लीक से बचें:

```typescript theme={null}
class ChatApplication {
  private activeStreams = new Set<AbortController>();

  async sendStreamingMessage(message: string, options: any) {
    const controller = new AbortController();
    this.activeStreams.add(controller);
    try {
      await this.chatSDK.sendMessageStream(message, {
        ...options,
        signal: controller.signal
      });
    } finally {
      this.activeStreams.delete(controller);
    }
  }

  cleanup() {
    this.activeStreams.forEach(controller => controller.abort());
    this.activeStreams.clear();
  }
}
```
