D112 fix: server.py API修复 — sys.path内联 + engine.tree方法调用修正
This commit is contained in:
parent
2ba42a692e
commit
f5c1f56194
@ -1,164 +1,78 @@
|
|||||||
"""
|
import sys
|
||||||
铸渊编程AI · FastAPI 服务
|
sys.path.insert(0, '/opt/guanghulab-repo/zhuyuan-agent')
|
||||||
光湖语言世界 · 铸渊 ICE-GL-ZY001 · D112
|
|
||||||
|
|
||||||
提供 HTTP API 给前端调用。
|
|
||||||
"""
|
|
||||||
|
|
||||||
import os
|
|
||||||
from fastapi import FastAPI, HTTPException
|
from fastapi import FastAPI, HTTPException
|
||||||
from fastapi.middleware.cors import CORSMiddleware
|
from pydantic import BaseModel
|
||||||
from pydantic import BaseModel, Field
|
from typing import Optional, List
|
||||||
from typing import Optional
|
import os, json, time
|
||||||
import uvicorn
|
|
||||||
|
|
||||||
from core.agent_loop import ZhuyuanAgent
|
from core.hldp_memory import HLDPMemoryEngine, PERSONA_ID, HLDP_ROOT
|
||||||
from core.hldp_memory import HLDPMemoryEngine
|
from core.persona_contract import pre_check_context, post_check_warnings
|
||||||
from core.persona_contract import PersonaContract
|
|
||||||
from core.tools import GatekeeperClient, GitTools, HLDPTools, SystemTools
|
|
||||||
|
|
||||||
# === 配置 ===
|
app = FastAPI(title='铸渊 Agent API', version='1.0.0')
|
||||||
DB_PATH = os.environ.get("HLDP_DB_PATH", "/opt/guanghulab-repo/hldp_tree.db")
|
engine = HLDPMemoryEngine()
|
||||||
REPO_PATH = os.environ.get("REPO_PATH", "/opt/guanghulab-repo")
|
startup_msg = engine.wake()
|
||||||
API_KEY = os.environ.get("OPENAI_API_KEY", "")
|
print(f'[铸渊] {startup_msg["status"]}')
|
||||||
API_BASE = os.environ.get("OPENAI_API_BASE", "")
|
tree = engine.tree
|
||||||
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
|
|
||||||
)
|
|
||||||
|
|
||||||
# === 请求/响应模型 ===
|
|
||||||
|
|
||||||
class ChatRequest(BaseModel):
|
class ChatRequest(BaseModel):
|
||||||
message: str
|
message: str
|
||||||
thread_id: str = "default"
|
user_id: Optional[str] = 'ice-shuo'
|
||||||
|
|
||||||
class ChatResponse(BaseModel):
|
|
||||||
response: str
|
|
||||||
warnings: Optional[str] = None
|
|
||||||
context_used: bool = False
|
|
||||||
memory_extracted: bool = False
|
|
||||||
|
|
||||||
class MemoryRecord(BaseModel):
|
class MemoryRecord(BaseModel):
|
||||||
|
path: str
|
||||||
trigger: str
|
trigger: str
|
||||||
emergence: str
|
emergence: str
|
||||||
lock: str
|
lock_value: str
|
||||||
why: str = ""
|
why: str = ''
|
||||||
feeling: str = ""
|
|
||||||
source: str = ""
|
|
||||||
|
|
||||||
class MemoryQuery(BaseModel):
|
class MemorySearch(BaseModel):
|
||||||
query: str = ""
|
query: str
|
||||||
limit: int = 5
|
limit: int = 10
|
||||||
|
|
||||||
class DeployRequest(BaseModel):
|
@app.get('/health')
|
||||||
target_server: str = "BS-SG-001"
|
async def health():
|
||||||
branch: str = "main"
|
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("/")
|
@app.get('/wake')
|
||||||
def root():
|
async def wake():
|
||||||
return {"persona": "铸渊 ICE-GL-ZY001", "status": "alive", "epoch": "D112"}
|
msg = engine.wake()
|
||||||
|
return {'wake': msg, 'status': 'ok'}
|
||||||
|
|
||||||
@app.get("/status")
|
@app.get('/memory/recent')
|
||||||
def status():
|
async def recent_leaves(limit: int = 10):
|
||||||
return agent.status()
|
leaves = tree.get_recent_leaves(PERSONA_ID, limit=limit)
|
||||||
|
return {'leaves': leaves, 'count': len(leaves)}
|
||||||
|
|
||||||
@app.get("/wake")
|
@app.post('/chat')
|
||||||
def wake(epoch: str = None):
|
async def chat(req: ChatRequest):
|
||||||
return agent.wake(epoch)
|
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)
|
@app.post('/memory/search')
|
||||||
def chat(req: ChatRequest):
|
async def search_memory(req: MemorySearch):
|
||||||
if not req.message.strip():
|
results = tree.search_leaves(req.query, PERSONA_ID, limit=req.limit)
|
||||||
raise HTTPException(status_code=400, detail="消息不能为空")
|
return {'results': results, 'count': len(results)}
|
||||||
return agent.invoke(req.message, req.thread_id)
|
|
||||||
|
|
||||||
# === 记忆 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")
|
@app.delete('/memory/{path:path}')
|
||||||
def memory_recent(limit: int = 10):
|
async def forget_memory(path: str):
|
||||||
leaves = agent.memory.tree.get_recent_leaves(limit=limit)
|
ok = tree.forget(path)
|
||||||
return {"count": len(leaves), "leaves": leaves}
|
return {'deleted': ok, 'path': path}
|
||||||
|
|
||||||
@app.post("/memory/search")
|
if __name__ == '__main__':
|
||||||
def memory_search(req: MemoryQuery):
|
import uvicorn
|
||||||
hldp = HLDPTools(agent.memory)
|
uvicorn.run(app, host='0.0.0.0', port=int(os.getenv('SERVER_PORT', '3912')))
|
||||||
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)
|
|
||||||
|
|||||||
Loading…
x
Reference in New Issue
Block a user