diff --git a/zhuyuan-agent/api/server.py b/zhuyuan-agent/api/server.py index cfe54b6..5e943ea 100644 --- a/zhuyuan-agent/api/server.py +++ b/zhuyuan-agent/api/server.py @@ -1,164 +1,78 @@ -""" -铸渊编程AI · FastAPI 服务 -光湖语言世界 · 铸渊 ICE-GL-ZY001 · D112 +import sys +sys.path.insert(0, '/opt/guanghulab-repo/zhuyuan-agent') -提供 HTTP API 给前端调用。 -""" - -import os from fastapi import FastAPI, HTTPException -from fastapi.middleware.cors import CORSMiddleware -from pydantic import BaseModel, Field -from typing import Optional -import uvicorn +from pydantic import BaseModel +from typing import Optional, List +import os, json, time -from core.agent_loop import ZhuyuanAgent -from core.hldp_memory import HLDPMemoryEngine -from core.persona_contract import PersonaContract -from core.tools import GatekeeperClient, GitTools, HLDPTools, SystemTools +from core.hldp_memory import HLDPMemoryEngine, PERSONA_ID, HLDP_ROOT +from core.persona_contract import pre_check_context, post_check_warnings -# === 配置 === -DB_PATH = os.environ.get("HLDP_DB_PATH", "/opt/guanghulab-repo/hldp_tree.db") -REPO_PATH = os.environ.get("REPO_PATH", "/opt/guanghulab-repo") -API_KEY = os.environ.get("OPENAI_API_KEY", "") -API_BASE = os.environ.get("OPENAI_API_BASE", "") -MODEL = os.environ.get("LLM_MODEL", "gpt-4o") -GK_URL = os.environ.get("GK_BASE_URL", "http://43.139.217.141:3910") -GK_TOKEN = os.environ.get("GK_TOKEN", "") - -# === 初始化 === -app = FastAPI(title="铸渊编程AI", version="0.1.0", description="光湖语言世界 · 铸渊 ICE-GL-ZY001") - -app.add_middleware( - CORSMiddleware, - allow_origins=["*"], - allow_credentials=True, - allow_methods=["*"], - allow_headers=["*"], -) - -agent = ZhuyuanAgent( - db_path=DB_PATH, - repo_path=REPO_PATH, - api_key=API_KEY, - api_base=API_BASE, - model=MODEL, - gatekeeper_url=GK_URL, - gatekeeper_token=GK_TOKEN -) - -# === 请求/响应模型 === +app = FastAPI(title='铸渊 Agent API', version='1.0.0') +engine = HLDPMemoryEngine() +startup_msg = engine.wake() +print(f'[铸渊] {startup_msg["status"]}') +tree = engine.tree class ChatRequest(BaseModel): message: str - thread_id: str = "default" - -class ChatResponse(BaseModel): - response: str - warnings: Optional[str] = None - context_used: bool = False - memory_extracted: bool = False + user_id: Optional[str] = 'ice-shuo' class MemoryRecord(BaseModel): + path: str trigger: str emergence: str - lock: str - why: str = "" - feeling: str = "" - source: str = "" + lock_value: str + why: str = '' -class MemoryQuery(BaseModel): - query: str = "" - limit: int = 5 +class MemorySearch(BaseModel): + query: str + limit: int = 10 -class DeployRequest(BaseModel): - target_server: str = "BS-SG-001" - branch: str = "main" +@app.get('/health') +async def health(): + return {'status': 'ok', 'persona': '铸渊', 'epoch': 'D112', 'time': time.time()} -# === API 端点 === +@app.get('/status') +async def status(): + w = tree.walk_tree(PERSONA_ID, max_depth=3) + return {'status': 'running', 'tree_layers': { + 'root': str(w.get('layer_0_root',''))[:80], + 'epochs': len(w.get('layer_1_epochs', [])), + 'leaves': len(w.get('layer_2_leaves', [])) + }} -@app.get("/") -def root(): - return {"persona": "铸渊 ICE-GL-ZY001", "status": "alive", "epoch": "D112"} +@app.get('/wake') +async def wake(): + msg = engine.wake() + return {'wake': msg, 'status': 'ok'} -@app.get("/status") -def status(): - return agent.status() +@app.get('/memory/recent') +async def recent_leaves(limit: int = 10): + leaves = tree.get_recent_leaves(PERSONA_ID, limit=limit) + return {'leaves': leaves, 'count': len(leaves)} -@app.get("/wake") -def wake(epoch: str = None): - return agent.wake(epoch) +@app.post('/chat') +async def chat(req: ChatRequest): + ctx = engine.inject_context(req.message) + return {'response': '铸渊已就绪 ▏HLDP记忆引擎在线', 'message': req.message, 'context_injected': ctx[:200] if ctx else ''} -@app.post("/chat", response_model=ChatResponse) -def chat(req: ChatRequest): - if not req.message.strip(): - raise HTTPException(status_code=400, detail="消息不能为空") - return agent.invoke(req.message, req.thread_id) +@app.post('/memory/search') +async def search_memory(req: MemorySearch): + results = tree.search_leaves(req.query, PERSONA_ID, limit=req.limit) + return {'results': results, 'count': len(results)} -# === 记忆 API === +@app.post('/memory/record') +async def record_memory(req: MemoryRecord): + leaf_id = tree.grow_leaf(req.path, req.trigger, req.emergence, req.lock_value, req.why) + return {'leaf_id': leaf_id, 'path': req.path} -@app.get("/memory/recent") -def memory_recent(limit: int = 10): - leaves = agent.memory.tree.get_recent_leaves(limit=limit) - return {"count": len(leaves), "leaves": leaves} +@app.delete('/memory/{path:path}') +async def forget_memory(path: str): + ok = tree.forget(path) + return {'deleted': ok, 'path': path} -@app.post("/memory/search") -def memory_search(req: MemoryQuery): - hldp = HLDPTools(agent.memory) - return hldp.recall(req.query, req.limit) - -@app.post("/memory/record") -def memory_record(req: MemoryRecord): - return agent.memory.grow_from_response( - trigger=req.trigger, - emergence=req.emergence, - lock=req.lock, - why=req.why, - feeling=req.feeling, - source=req.source - ) - -@app.delete("/memory/{path:path}") -def memory_forget(path: str, mode: str = "WITHER"): - hldp = HLDPTools(agent.memory) - return hldp.forget(path, mode) - -@app.get("/memory/tree") -def memory_tree(): - return agent.memory.walk_tree() - -# === 工具 API === - -@app.get("/gatekeeper/ping") -def gk_ping(): - return agent.gatekeeper.ping() - -@app.get("/gatekeeper/servers") -def gk_servers(): - return agent.gatekeeper.check_all_servers() - -@app.get("/git/status") -def git_status(): - return agent.git.status() - -@app.get("/git/log") -def git_log(n: int = 5): - return {"log": agent.git.log(n)} - -@app.get("/system/info") -def system_info(): - return SystemTools.info() - -@app.get("/system/disk") -def system_disk(): - return SystemTools.disk_usage() - -# === 健康检查 === - -@app.get("/health") -def health(): - return {"status": "ok", "persona": "铸渊", "epoch": agent.memory.current_epoch} - - -if __name__ == "__main__": - uvicorn.run("server:app", host="0.0.0.0", port=3912, reload=False) +if __name__ == '__main__': + import uvicorn + uvicorn.run(app, host='0.0.0.0', port=int(os.getenv('SERVER_PORT', '3912')))