File size: 4,991 Bytes
d24a125
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
#!/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/<name>', 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/<name>/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/<name>/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/<name>/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/<name>/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/<name> - get creature")
        print("  POST /api/creature/<name>/learn - learn from interaction")
        print("  GET  /api/creature/<name>/weights - download weights")
        print("  POST /api/creature/<name>/weights - import weights")
        print("  GET  /api/creature/<name>/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")