-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.py
executable file
·54 lines (38 loc) · 1.46 KB
/
main.py
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
import json
import os
import google.generativeai as genai
from flask import Flask, jsonify, request, send_file, send_from_directory
# 🔥 FILL THIS OUT FIRST! 🔥
# 🔥 GET YOUR GEMINI API KEY AT 🔥
# 🔥 https://makersuite.google.com/app/apikey 🔥
API_KEY = 'XXXXXXXXXXXXX'
genai.configure(api_key=API_KEY)
app = Flask(__name__)
@app.route("/")
def index():
return send_file('web/index.html')
@app.route("/api/generate", methods=["POST"])
def generate_api():
if request.method == "POST":
if API_KEY == 'TODO':
return jsonify({ "error": '''
To get started, get an API key at
https://makersuite.google.com/app/apikey and enter it in
main.py
'''.replace('\n', '') })
try:
req_body = request.get_json()
content = req_body.get("contents")
model = genai.GenerativeModel(model_name=req_body.get("model"))
response = model.generate_content(content, stream=True)
def stream():
for chunk in response:
yield 'data: %s\n\n' % json.dumps({ "text": chunk.text })
return stream(), {'Content-Type': 'text/event-stream'}
except Exception as e:
return jsonify({ "error": str(e) })
@app.route('/<path:path>')
def serve_static(path):
return send_from_directory('web', path)
if __name__ == "__main__":
app.run(port=int(os.environ.get('PORT', 80)))