add auth for copilot and agents

This commit is contained in:
ramnique 2025-01-29 08:33:06 +05:30
parent cdc96e7ce3
commit ad4ea23d79
14 changed files with 173 additions and 43 deletions

View file

@ -24,6 +24,7 @@ pip install -r requirements.txt
4. Set up your OpenAI API key:
```bash
export OPENAI_API_KEY='your-api-key-here' # On Windows, use: set OPENAI_API_KEY=your-api-key-here
export API_KEY='test-api-key' # set a shared API key for the application
```
## Running the Application
@ -33,24 +34,27 @@ export OPENAI_API_KEY='your-api-key-here' # On Windows, use: set OPENAI_API_KEY
python app.py
```
The server will start on `http://localhost:5000`
The server will start on `http://localhost:3002`
## API Usage
The application exposes a single endpoint at `/chat` that accepts POST requests.
### Example Request:
```json
{
"messages": [
{
"role": "user",
"content": "Your message here"
}
],
"workflow_schema": "Your workflow schema here",
"current_workflow_config": "Your current workflow configuration here"
}
```bash
curl -X POST http://localhost:3002/chat \
-H "Content-Type: application/json" \
-H "Authorization: Bearer test-api-key" \
-d '{
"messages": [
{
"role": "user",
"content": "Your message here"
}
],
"workflow_schema": "Your workflow schema here",
"current_workflow_config": "Your current workflow configuration here"
}'
```
### Example Response:

View file

@ -3,6 +3,8 @@ from pydantic import BaseModel, ValidationError
from typing import List
from copilot import UserMessage, AssistantMessage, get_response
from lib import AgentContext, PromptContext, ToolContext, ChatContext
import os
from functools import wraps
class ApiRequest(BaseModel):
messages: List[UserMessage | AssistantMessage]
@ -24,7 +26,26 @@ def validate_request(request_data: ApiRequest) -> None:
if not isinstance(request_data.messages[-1], UserMessage):
raise ValueError('Last message must be a user message')
def require_api_key(f):
@wraps(f)
def decorated(*args, **kwargs):
auth_header = request.headers.get('Authorization')
if not auth_header or not auth_header.startswith('Bearer '):
return jsonify({'error': 'Missing or invalid authorization header'}), 401
token = auth_header.split('Bearer ')[1]
if token != os.environ.get('API_KEY'):
return jsonify({'error': 'Invalid API key'}), 403
return f(*args, **kwargs)
return decorated
@app.route('/health', methods=['GET'])
def health():
return jsonify({'status': 'ok'})
@app.route('/chat', methods=['POST'])
@require_api_key
def chat():
try:
# Log incoming request
@ -74,4 +95,4 @@ def chat():
if __name__ == '__main__':
print("Starting Flask server...")
app.run(port=5000, debug=True)
app.run(port=3002, host='0.0.0.0', debug=True)

View file

@ -5,6 +5,7 @@ certifi==2024.8.30
click==8.1.7
distro==1.9.0
Flask==3.1.0
gunicorn==23.0.0
h11==0.14.0
httpcore==1.0.7
httpx==0.28.0
@ -14,6 +15,8 @@ Jinja2==3.1.4
jiter==0.8.0
MarkupSafe==3.0.2
openai==1.57.0
packaging==24.2
pydantic==2.10.3
pydantic_core==2.27.1
sniffio==1.3.1
tqdm==4.67.1