Spaces:
Sleeping
Sleeping
File size: 2,539 Bytes
4c41b3d | 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 | import { exec } from "child_process";
import { promisify } from "util";
import fs from "fs/promises";
import path from "path";
const execAsync = promisify(exec);
/**
* Memory management for the HackingFactory using ChromaDB via Python bridge.
* This allows storing successful code snippets and retrieving them based on semantic similarity.
*/
export class ProjectMemory {
private static instance: ProjectMemory;
private pythonBridgePath: string;
private constructor() {
this.pythonBridgePath = path.join(process.cwd(), "server", "memory_bridge.py");
this.ensurePythonBridge();
}
public static getInstance(): ProjectMemory {
if (!ProjectMemory.instance) {
ProjectMemory.instance = new ProjectMemory();
}
return ProjectMemory.instance;
}
private async ensurePythonBridge() {
const bridgeCode = `
import chromadb
import sys
import json
client = chromadb.PersistentClient(path="./chroma_db")
collection = client.get_or_create_collection(name="hacking_factory_memory")
def add_memory(id, content, metadata):
collection.add(
documents=[content],
metadatas=[metadata],
ids=[id]
)
return {"status": "success"}
def query_memory(query_text, n_results=3):
results = collection.query(
query_texts=[query_text],
n_results=n_results
)
return results
if __name__ == "__main__":
action = sys.argv[1]
if action == "add":
data = json.loads(sys.argv[2])
print(json.dumps(add_memory(data["id"], data["content"], data["metadata"])))
elif action == "query":
query = sys.argv[2]
print(json.dumps(query_memory(query)))
`;
await fs.writeFile(this.pythonBridgePath, bridgeCode);
}
public async addSuccessfulCode(projectId: number, code: string, prompt: string, score: number) {
const data = JSON.stringify({
id: `proj_${projectId}_${Date.now()}`,
content: code,
metadata: { projectId, prompt, score, type: "successful_code" }
});
try {
const { stdout } = await execAsync(`python3 ${this.pythonBridgePath} add '${data}'`);
return JSON.parse(stdout);
} catch (error) {
console.error("Memory add error:", error);
return null;
}
}
public async findSimilarSolutions(query: string) {
try {
const { stdout } = await execAsync(`python3 ${this.pythonBridgePath} query '${query}'`);
return JSON.parse(stdout);
} catch (error) {
console.error("Memory query error:", error);
return null;
}
}
}
|