The following program will simulate an open ai api for chatgpt. This can be used to simulate a connection for testing purposes. I needed a way to fake an open ai connection.
from flask import Flask, request, jsonify
app = Flask(__name__)
@app.route('/v1/chat/completions', methods=['POST'])
def chat_completions():
data = request.get_json()
# Check if the request contains the required keys
if not data or 'model' not in data or 'messages' not in data:
return jsonify({'error': 'Invalid request'}), 400
# Check for valid API key in headers
api_key = request.headers.get('Authorization')
if api_key != 'Bearer your-api-key':
return jsonify({'error': 'Invalid API key'}), 401
# Fake response
response = {
'id': 'mock-id',
'object': 'chat.completion',
'created': 1234567890,
'model': data['model'],
'choices': [
{
'message': {
'role': 'assistant',
'content': 'This is a mock response from the simulated OpenAI API.'
},
'finish_reason': 'stop'
}
]
}
return jsonify(response)
if __name__ == '__main__':
app.run(port=5000)
'''
POST /v1/chat/completions
Host: api.openai.com
Authorization: Bearer YOUR_API_KEY
Content-Type: application/json
{
"model": "gpt-4",
"messages": [
{
"role": "system",
"content": "You are a helpful assistant."
},
{
"role": "user",
"content": "Can you explain how to use the OpenAI API?"
}
]
}
'''
No comments:
Post a Comment