hey i am hitting this rate limiting based on ip eve nif i used multiple api keys can you fix this liek by makeing the requests go to the elven labs apu from various endpoint like so that this restriciton is cahnged please make it good and bncie 

"""

import express from 'express';
import cors from 'cors';
import * as dotenv from 'dotenv';
import mongoose from 'mongoose'; 
import aiVoiceRoutes from './routes/aiVoiceRoutes';
import transcriptionRouter from './routes/meetingRoutes';
import path from 'path'; // Import path module

dotenv.config();

const app = express();
const PORT = process.env.PORT || 3000;
const mongoUri = process.env.MONGODB_URI || 'None';

// Connect to MongoDB
mongoose.connect(mongoUri)
  .then(() => console.log('Connected to MongoDB'))
  .catch(err => {
    console.error('MongoDB connection error:', err);
    process.exit(1); // Exit process on connection error
  });

// CORS Configuration (Restrict in production)
const corsOptions = {
  origin: process.env.NODE_ENV === 'production' ? 'https://yourproductiondomain.com' : '*', // or an array of origins
  optionsSuccessStatus: 200, // some legacy browsers (IE11, various SmartTVs) choke on 204
};
app.use(cors(corsOptions));

app.use(express.json());

// Serve static files
app.use(express.static(path.join(__dirname, 'index'))); // Use path.join for cross-platform compatibility

// Routes
app.use('/api/ai', aiVoiceRoutes);
app.use('/api/meeting', transcriptionRouter);

// Centralized Error Handling
app.use((err: any, req: any, res: any, next: any) => {
  console.error(err.stack); // Log the error stack trace
  res.status(500).send('Something went wrong!');
});

// Start server
const server = app.listen(PORT, () => {
  console.log(`Server running on port ${PORT}`);
});

// Handle graceful shutdown
process.on('SIGINT', () => {
  console.info('SIGINT signal received.');
  console.log('Closing http server.');
  server.close(() => {
    console.log('Http server closed.');
    mongoose.connection.close(false);
    console.log('MongoDb connection closed.');
    process.exit(0);

  });
});

"""

"""

import express from 'express';
import AIVoiceStreamService from '../openaiElevenLabs/AIVoiceStreamService';
import { UserMessage } from '../helpers/types';
import Conversation from '../db/schema';

const router = express.Router();
const aiVoiceService = new AIVoiceStreamService();

router.post('/stream', async (req: any, res: any) => {
  try {
    const { data, meetingId, context } = req.body;
    if (!data || !meetingId) {
      return res.status(400).json({ error: 'Invalid message or user ID' });
    }
    const userMessage: UserMessage = { role: 'user', content: data };

    let existingConversation = await Conversation.findOne({ meetingId });

    if (existingConversation) {
      existingConversation.messages.push(userMessage);
      const response = await aiVoiceService.generateVoiceStream(existingConversation.messages, res, context || "");
      existingConversation.messages.push({ role: 'assistant', content: response });
      await existingConversation.save();
      console.log('Conversation saved successfully!');

    } else {
      res.status(401).json({ error: 'Meeting room not Found' });
    }

  } catch (error) {
    console.error('Streaming error:', error);
    if (!res.headersSent) {
      res.status(500).json({ error: error instanceof Error ? error.message : 'Unknown error' });
    }
  }
});

export default router;

"""

"""


import OpenAI from 'openai';
import { Response } from 'express';
import { ChatMessage, AIVoiceStreamOptions } from '../helpers/types';
import WebSocket from 'ws';
import { system_prompt_natural } from '../helpers/constant';

class AIVoiceStreamService {
  private openai: OpenAI;
  private elevenlabsApiKey: string;

  constructor() {
    if (!process.env.OPENAI_API_KEY) {
      throw new Error('Missing OpenAI API Key');
    }
    if (!process.env.ELEVENLABS_API_KEY) {
      throw new Error('Missing ElevenLabs API Key');
    }

    this.openai = new OpenAI({
      apiKey: process.env.OPENAI_API_KEY,
    });
    this.elevenlabsApiKey = process.env.ELEVENLABS_API_KEY;
  }

  async generateVoiceStream(
    messages: ChatMessage[],
    res: Response,
    context: string,
    options: AIVoiceStreamOptions = {}
  ): Promise<void> {
    const {
      openaiModel = 'gpt-4-turbo-preview',
      stability = 0.75,
      similarityBoost = 0.85,
      voiceId = "Xb7hH8MSUJpSbSDYk0k2"
    } = options;

    const system_prompt: ChatMessage = {
      role: "system",
      content: system_prompt_natural(context)
    };

    messages = [system_prompt, ...messages];

    try {
      // Set up headers for audio streaming
      res.setHeader('Content-Type', 'audio/mpeg');
      res.setHeader('Transfer-Encoding', 'chunked');

      // Initialize WebSocket connection to ElevenLabs
      const model = "eleven_flash_v2_5";
      const uri = `wss://api.elevenlabs.io/v1/text-to-speech/${voiceId}/stream-input?model_id=${model}`;
      
      const websocket = new WebSocket(uri, {
        headers: { "xi-api-key": this.elevenlabsApiKey }
      });

      // Buffer to accumulate text chunks for natural sentence breaks
      let textBuffer = '';
      const sentenceEndRegex = /[.!?]\s+/;

      // Generate text stream from OpenAI
      const textStream = await this.openai.beta.chat.completions.stream({
        model: openaiModel,
        messages: messages,
        stream: true,
      });

      return new Promise((resolve, reject) => {
        let isWebSocketReady = false;
        let hasStartedStreaming = false;

        websocket.on('error', (error) => {
          console.error('WebSocket error:', error);
          reject(error);
          if (!res.headersSent) {
            res.status(500).json({ error: `WebSocket error: ${error.message}` });
          }
        });

        websocket.on('open', () => {
          isWebSocketReady = true;
          // Send initial configuration
          websocket.send(JSON.stringify({
            text: " ",
            voice_settings: {
              stability,
              similarity_boost: similarityBoost,
              use_speaker_boost: true,
            }
          }));
          processBuffer();
        });

        websocket.on('error', (error) => {
          console.error('WebSocket error:', error);
        });
        
        websocket.on('close', (code, reason) => {
          console.error(`WebSocket closed. Code: ${code}, Reason: ${reason}`);
        });
        
        websocket.on('message', (event) => {
          console.log('Received message from ElevenLabs:', event.toString());
        });
              

        websocket.on('message', (event) => {
          try {
            const data = JSON.parse(event.toString());
            if (data.audio) {
              const audioBuffer = Buffer.from(data.audio, 'base64');
              res.write(audioBuffer);
            }
          } catch (error) {
            console.error('Error processing audio chunk:', error);
          }
        });

        websocket.on('close', () => {
          res.end();
          resolve();
        });

        // Process and send buffered text at natural breaks
        const processBuffer = () => {
          if (!isWebSocketReady || textBuffer.length === 0) return;

          if (!hasStartedStreaming) {
            hasStartedStreaming = true;
          }

          const sentences = textBuffer.split(sentenceEndRegex);
          
          if (sentences.length > 1) {
            // Send complete sentences
            const completeText = sentences.slice(0, -1).join('. ') + '. ';
            websocket.send(JSON.stringify({ text: completeText }));
            textBuffer = sentences[sentences.length - 1];
          }
        };

        // Handle the OpenAI stream
        (async () => {
          try {
            for await (const chunk of textStream) {
              const content = chunk.choices[0]?.delta?.content || '';
              if (content) {
                textBuffer += content;
                processBuffer();
              }
            }

            // Send any remaining text
            if (textBuffer) {
              websocket.send(JSON.stringify({ text: textBuffer }));
            }

            // Signal end of text stream
            websocket.send(JSON.stringify({ text: "" }));
          } catch (error) {
            console.error('Error processing OpenAI stream:', error);
            reject(error);
          }
        })();
      });

    } catch (error: any) {
      console.error('Voice stream generation error:', error);
      if (!res.headersSent) {
        res.status(500).json({ 
          error: `Failed to generate voice stream: ${error.message}` 
        });
      }
      throw error;
    }
  }
}

export default AIVoiceStreamService;



`
import OpenAI from 'openai';
import { Response } from 'express';
import { ChatMessage, AIVoiceStreamOptions } from '../helpers/types';
import { ElevenLabsClient } from "elevenlabs";
import { system_prompt_natural } from '../helpers/constant';
class AIVoiceStreamService {
  private openai: OpenAI;
  private client: ElevenLabsClient;

  constructor() {
    // Validate API keys on initialization
    if (!process.env.OPENAI_API_KEY) {
      throw new Error('Missing OpenAI API Key');
    }
    if (!process.env.ELEVENLABS_API_KEY) {
      throw new Error('Missing ElevenLabs API Key');
    }

    this.openai = new OpenAI({
      apiKey: process.env.OPENAI_API_KEY,
    });
    this.client = new ElevenLabsClient({
      apiKey: process.env.ELEVENLABS_API_KEY,
    });
  }

  /**
   * Generate AI response and directly stream audio to response
   * @param messages Array of chat messages
   * @param res Express response object
   * @param options Configuration options for AI and TTS
   */
  async generateVoiceStream( messages: ChatMessage[], res: Response, options: AIVoiceStreamOptions = {}): Promise<string | undefined> {
    const {
      openaiModel = 'gpt-4o-mini',
      stability = 0.75,
      similarityBoost = 0.85
    } = options;
    
    const system_prompt: ChatMessage = {
      "role": "system",
      "content": system_prompt_natural
    }

    messages = [system_prompt, ...messages]
    try {
      // Generate text response from OpenAI
      const textStream = await this.openai.beta.chat.completions.stream({
        model: openaiModel,
        messages: messages,
        stream: true,
      });

      // Collect full text response
      let fullContent = '';
      for await (const chunk of textStream) {
        const delta = chunk.choices[0]?.delta?.content || '';
        fullContent += delta;
      }
      console.log("response from AI: ", fullContent)
      // Set headers for audio streaming
      res.setHeader('Content-Type', 'audio/mpeg');
      res.setHeader('Transfer-Encoding', 'chunked');
      // Directly stream audio to response
      const audioStream = await this.client.generate(
        {
          stream: true,
          voice: "Sarah",
          text: fullContent,
          model_id: "eleven_flash_v2_5", // eleven_flash_v2_5 or eleven_turbo_v2
          voice_settings: {
            stability,
            similarity_boost: similarityBoost,
          },
        }
      );

      // Pipe the audio stream directly to the response
      for await (const chunk of audioStream) {
        res.write(chunk);
      }
      
      // End the response
      res.end();

      return fullContent;

    } catch (error: any) {
      console.error('Voice stream generation error:', error);
      if (!res.headersSent) {
        res.status(500).json({ 
          error: "Failed to generate voice stream:, error.message"
        });
      }
    }
  }
}

export default AIVoiceStreamService;
`