File size: 3,076 Bytes
dd1839a
 
b19a42f
 
6600d84
 
dd1839a
 
 
b19a42f
 
dd1839a
6600d84
dd1839a
777758b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b19a42f
dd1839a
777758b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b19a42f
777758b
 
 
 
 
 
 
 
 
 
b19a42f
777758b
 
 
 
 
 
 
 
 
 
 
 
dd1839a
777758b
 
 
 
 
 
 
 
 
 
 
dd1839a
 
 
 
 
777758b
 
 
 
 
 
 
dd1839a
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
# app.py
from flask import Flask, request, jsonify, render_template, send_file
from dotenv import load_dotenv
from groq import Groq
import os
import uuid
import tempfile
import sounddevice as sd
import numpy as np
import io
import base64
import wave
import speech_recognition as sr
from gtts import gTTS

app = Flask(__name__, static_folder='static')
load_dotenv()

GROQ_API_KEY = os.getenv("GROQ_API_KEY")
client = Groq(api_key=GROQ_API_KEY)
MODEL = "llama3-70b-8192"

recognizer = sr.Recognizer()
conversations = {}

def load_base_prompt():
    try:
        with open("base_prompt.txt", "r") as file:
            return file.read().strip()
    except FileNotFoundError:
        print("Error: base_prompt.txt file not found.")
        return "You are a helpful assistant."

base_prompt = load_base_prompt()

def chat_with_groq(user_message, conversation_id=None):
    try:
        messages = conversations.get(conversation_id, [])
        if not messages:
            messages.append({"role": "system", "content": base_prompt})
        
        messages.append({"role": "user", "content": user_message})
        
        completion = client.chat.completions.create(
            model=MODEL,
            messages=messages,
            temperature=0.1,
        )
        
        assistant_message = completion.choices[0].message.content.strip()
        messages.append({"role": "assistant", "content": assistant_message})
        
        if conversation_id:
            conversations[conversation_id] = messages
        
        return assistant_message
    except Exception as e:
        print(f"Error in chat_with_groq: {str(e)}")
        return f"I apologize, but I'm having trouble responding right now. Error: {str(e)}"

def text_to_speech(text):
    try:
        tts = gTTS(text=text, lang='en')
        audio_io = io.BytesIO()
        tts.write_to_fp(audio_io)
        audio_io.seek(0)
        return audio_io
    except Exception as e:
        print(f"Error in text_to_speech: {str(e)}")
        return None

@app.route('/')
def index():
    return render_template('index.html')

@app.route('/api/chat', methods=['POST'])
def chat():
    try:
        data = request.get_json()
        user_message = data.get('message', '')
        conversation_id = data.get('conversation_id', str(uuid.uuid4()))
        voice_output = data.get('voice_output', False)
        
        if not user_message:
            return jsonify({'error': 'No message provided'}), 400
        
        response = chat_with_groq(user_message, conversation_id)
        
        result = {
            'response': response,
            'conversation_id': conversation_id
        }
        
        if voice_output:
            audio_io = text_to_speech(response)
            if audio_io:
                audio_base64 = base64.b64encode(audio_io.getvalue()).decode('utf-8')
                result['voice_response'] = audio_base64
        
        return jsonify(result)
    
    except Exception as e:
        return jsonify({'error': str(e)}), 500

if __name__ == '__main__':
    app.run(debug=True)