Skip to content

Commit

Permalink
feat: api key protection, better err handling, vercel setup
Browse files Browse the repository at this point in the history
  • Loading branch information
nagarajpandith committed Dec 8, 2023
1 parent 7226d66 commit 11f602a
Show file tree
Hide file tree
Showing 4 changed files with 34 additions and 4 deletions.
3 changes: 2 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
/venv/**
/venv/**
.flaskenv
19 changes: 16 additions & 3 deletions main.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,14 @@
from flask import Flask, request, Response, jsonify
import g4f
import sys
import os
from dotenv import load_dotenv
load_dotenv()

app = Flask(__name__)

API_KEY = os.environ.get('API_KEY')

def generate_response(model, llm, content):
response_generator = g4f.ChatCompletion.create(
model=model,
Expand All @@ -19,11 +24,19 @@ def generate_response(model, llm, content):
def chat_completion():
data = request.get_json()

if 'content' not in data or 'provider' not in data:
return jsonify({"error": "Missing 'content' or 'provider' in the request"}), 400
required_params = {'content', 'provider', 'api_key'}
missing_params = required_params - set(data.keys())

if missing_params:
error_msg = f"Missing parameters: {', '.join(missing_params)}"
return jsonify({"error": error_msg}), 400

content = data['content']
pname = data['provider']
api_key = data['api_key']

if not api_key == API_KEY:
return jsonify({"error": "Invalid API key"}), 401

try:
llm = getattr(getattr(getattr(sys.modules[__name__], "g4f"), "Provider"), pname)
Expand All @@ -32,7 +45,7 @@ def chat_completion():

model = "gpt-3.5-turbo"

return Response(generate_response(model, llm, content), mimetype="text/event-stream")
return Response(generate_response(model, llm, content), content_type='text/plain', mimetype='text/event-stream')

@app.route('/working_providers', methods=['GET'])
def working_providers():
Expand Down
1 change: 1 addition & 0 deletions requirements.txt
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,7 @@ pydantic_core==2.14.5
PyExecJS==1.5.1
pyjsparser==2.7.1
PySocks==1.7.1
python-dotenv==1.0.0
requests==2.31.0
selenium==4.16.0
six==1.16.0
Expand Down
15 changes: 15 additions & 0 deletions vercel.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
{
"version": 2,
"builds": [
{
"src": "./main.py",
"use": "@vercel/python"
}
],
"routes": [
{
"src": "/(.*)",
"dest": "/"
}
]
}

0 comments on commit 11f602a

Please sign in to comment.