-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
82 lines (61 loc) · 2.23 KB
/
app.py
File metadata and controls
82 lines (61 loc) · 2.23 KB
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
'''
Author : Emon Hasan
Email : iconicemon01@gmail.com
GitHub : https://github.com/Md-Emon-Hasan
LinkedIn: https://www.linkedin.com/in/emon-hasan/
Date : 01/14/2025
Time : 21:08
Project : building ai chatbot using llama
Purpose : bulding a simple chatbot using llama model and groq
'''
import os
from typing import List, Dict
from dotenv import load_dotenv
from flask import Flask, request, jsonify, render_template
from groq import Groq
from flask_cors import CORS
load_dotenv()
GROQ_API_KEY = os.getenv("GROQ_API_KEY")
if not GROQ_API_KEY:
raise ValueError("API key for Groq is missing. Please set the GROQ_API_KEY in the .env file.")
app = Flask(__name__)
CORS(app)
client = Groq(api_key=GROQ_API_KEY)
conversations: Dict[str, List[Dict[str, str]]] = {}
def query_groq_api(conversation: List[Dict[str, str]]) -> str:
try:
completion = client.chat.completions.create(
model="llama-3.3-70B-specdec",
messages=conversation,
temperature=1,
max_tokens=1024,
top_p=1,
stream=True,
stop=None,
)
response = ""
for chunk in completion:
response += chunk.choices[0].delta.content or ""
return response
except Exception as e:
return f"Error with Groq API: {str(e)}"
@app.route('/')
def index():
return render_template('index.html')
@app.route('/chat/', methods=['POST'])
def chat():
data = request.json
message = data.get('message')
role = data.get('role', 'user')
conversation_id = data.get('conversation_id')
if not conversation_id:
return jsonify({"error": "conversation_id is required"}), 400
if conversation_id not in conversations:
conversations[conversation_id] = [{"role": "system", "content": "You are a useful AI assistant."}]
conversation = conversations[conversation_id]
conversation.append({"role": role, "content": message})
response = query_groq_api(conversation)
conversation.append({"role": "assistant", "content": response})
return jsonify({"response": response, "conversation_id": conversation_id})
if __name__ == '__main__':
app.run(debug=True, host='0.0.0.0', port=8000)