PreCET/api.py

79 lines
2.3 KiB
Python

from threading import Thread
from uuid import uuid4 as uuid
from flask import Flask, jsonify, request, abort
from crew import ChatCrew
from job_manager import jobs_lock, append_event, jobs, Event
from datetime import datetime
import json
app = Flask(__name__)
def kickoff_crew(job_id, company, contact, interests, city):
print(f"Running crew for {job_id} for company {company} with point of contact {contact}")
# Setup the crew, run, and process results
results = None
try:
crew = ChatCrew(job_id=job_id)
crew.setup_crew(company=company, contact=contact, interests=interests, city=city)
result = crew.kickoff()
except Exception as e:
print(f"CREW FALED: {str(e)}")
append_event(job_id, f"CREW FAILED: {str(e)}")
with jobs_lock:
jobs[job_id].status = "ERROR"
jobs[job_id].result = str(e)
with jobs_lock:
jobs[job_id].status = "COMPLETE"
jobs[job_id].result = result
jobs[job_id].events.append(Event(
data="CREW COMPLETED", timestamp=datetime.now()
))
@app.route('/api/crew', methods=['POST'])
def run_crew():
data = request.json
if not data or 'company' not in data or 'contact' not in data or 'interests' not in data or 'city' not in data:
abort(400, description='Invalid request')
job_id = str(uuid())
company = data['company']
contact = data['contact']
interests = data['interests']
city = data['city']
# Run the crew
thread = Thread(target=kickoff_crew, args=(job_id, company, contact, interests, city))
thread.start()
return jsonify({'job_id': job_id}), 200
@app.route('/api/crew/<job_id>', methods=['GET'])
def get_status(job_id):
# Lock the job and check if it exists
with jobs_lock:
job = jobs.get(job_id)
if not job:
abort(404, description="Job not found")
try:
result_json = json.loads(job.result)
except:
result_json = job.result
print(f"{job_id} | {job.status} | {result_json}")
return jsonify({
'job_id': job_id,
'status': job.status,
'result': result_json,
'events': [{"timestamp": event.timestamp.isoformat(), "data": event.data} for event in job.events]
}), 200
if __name__ == '__main__':
app.run(debug=True, port=3001)