#!/usr/bin/env python3 """ REST API for Creature Weights System Use on any platform - creatures travel everywhere! """ import json from pathlib import Path from datetime import datetime import sys sys.path.insert(0, '.') try: from flask import Flask, request, jsonify except ImportError: print("Flask not found. Install with: pip install flask") Flask = None from creature_system import CreatureManager, Creature app = Flask(__name__) if Flask else None manager = CreatureManager("creatures") # ============================================================ # API ENDPOINTS # ============================================================ @app.route('/api/creatures', methods=['GET']) def list_creatures(): """List all creatures.""" return jsonify([c.get_status() for c in [Creature(d.name) for d in Path("creatures").iterdir() if d.is_dir()]]) @app.route('/api/creature/', methods=['GET']) def get_creature(name): """Get specific creature status.""" try: creature = Creature(name) return jsonify(creature.get_status()) except: return jsonify({"error": f"Creature {name} not found"}), 404 @app.route('/api/creature//learn', methods=['POST']) def learn(name): """Creature learns from interaction.""" data = request.json user_input = data.get("input", "") creature_output = data.get("output", "") try: creature = Creature(name) creature.learn_from_interaction(user_input, creature_output) return jsonify({ "status": "learned", "creature": name, "concepts": len(creature.weights["salience"]), "associations": len(creature.weights["assoc"]), "turns": creature.weights["n"] }) except Exception as e: return jsonify({"error": str(e)}), 400 @app.route('/api/creature//weights', methods=['GET']) def get_weights(name): """Download creature's weights (JSON).""" try: creature = Creature(name) return jsonify(creature.export_portable()) except: return jsonify({"error": f"Creature {name} not found"}), 404 @app.route('/api/creature//weights', methods=['POST']) def import_weights(name): """Import weights from another platform.""" data = request.json try: creature = Creature(name) creature.import_portable(data) return jsonify({"status": "imported", "creature": name}) except Exception as e: return jsonify({"error": str(e)}), 400 @app.route('/api/creature//modelfile', methods=['GET']) def get_modelfile(name): """Get Ollama Modelfile for creature.""" try: creature = Creature(name) return app.response_class( response=creature.generate_modelfile(), status=200, mimetype='text/plain' ) except: return jsonify({"error": f"Creature {name} not found"}), 404 @app.route('/api/creature', methods=['POST']) def create_creature(): """Birth a new creature.""" data = request.json name = data.get("name") owner = data.get("owner") if not name: return jsonify({"error": "name required"}), 400 try: creature = manager.create_creature(name, owner) return jsonify({ "status": "created", "creature": creature.get_status() }), 201 except Exception as e: return jsonify({"error": str(e)}), 400 @app.route('/api/export-all', methods=['GET']) def export_all(): """Export all creatures (portable for any platform).""" try: portable = manager.export_all_creatures() return jsonify(portable) except Exception as e: return jsonify({"error": str(e)}), 400 # ============================================================ # CLI for testing (no Flask) # ============================================================ if __name__ == "__main__": if Flask and len(sys.argv) > 1 and sys.argv[1] == "serve": print("Starting REST API on http://localhost:5000") print("Endpoints:") print(" GET /api/creatures - list all creatures") print(" POST /api/creature - create creature") print(" GET /api/creature/ - get creature") print(" POST /api/creature//learn - learn from interaction") print(" GET /api/creature//weights - download weights") print(" POST /api/creature//weights - import weights") print(" GET /api/creature//modelfile - get Ollama modelfile") print(" GET /api/export-all - export all creatures\n") app.run(debug=True, port=5000) else: print("Usage: python creature_api.py serve") print("\nOr import for direct use:") print(" from creature_api import app, manager")