fix(G7): skill trial路由 + LLM API key 传递到 Rust sidecar + Authorization header
This commit is contained in:
@@ -6,6 +6,8 @@ import (
|
||||
"fmt"
|
||||
"net/http"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"time"
|
||||
|
||||
"github.com/xiaoxue/memoryweave/internal/governance"
|
||||
@@ -79,15 +81,44 @@ func (aa *AdminAPI) Forget(w http.ResponseWriter, r *http.Request) {
|
||||
// POST /api/v1/admin/backup
|
||||
func (aa *AdminAPI) Backup(w http.ResponseWriter, r *http.Request) {
|
||||
timestamp := time.Now().Format("20060102-150405")
|
||||
backupPath := fmt.Sprintf("/home/muc/backups/memoryweave/%s", timestamp)
|
||||
os.MkdirAll(backupPath, 0755)
|
||||
|
||||
if err := aa.LanceDB.Backup(backupPath); err != nil {
|
||||
respondError(w, 500, "backup failed: "+err.Error())
|
||||
backupDir := fmt.Sprintf("/home/muc/backups/memoryweave/%s", timestamp)
|
||||
dataDir := "/var/lib/memoryweave"
|
||||
if err := os.MkdirAll(backupDir, 0755); err != nil {
|
||||
respondError(w, 500, "mkdir failed: "+err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
// 1. SQLite backup: graph.db
|
||||
graphBackup := filepath.Join(backupDir, "graph.db")
|
||||
if err := exec.Command("sqlite3", filepath.Join(dataDir, "graph.db"), ".backup "+graphBackup).Run(); err != nil {
|
||||
respondError(w, 500, "graph.db backup failed: "+err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
// 2. SQLite backup: memoryweave.db
|
||||
mwBackup := filepath.Join(backupDir, "memoryweave.db")
|
||||
if err := exec.Command("sqlite3", filepath.Join(dataDir, "memoryweave.db"), ".backup "+mwBackup).Run(); err != nil {
|
||||
respondError(w, 500, "memoryweave.db backup failed: "+err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
// 3. Redis BGSAVE (async)
|
||||
exec.Command("redis-cli", "BGSAVE").Run()
|
||||
|
||||
// 4. Tar LanceDB directories
|
||||
if err := exec.Command("tar", "czf",
|
||||
filepath.Join(backupDir, "lance-data.tar.gz"),
|
||||
"-C", dataDir,
|
||||
"episodes.lance", "memories.lance", "tombstones.lance",
|
||||
).Run(); err != nil {
|
||||
respondError(w, 500, "lance backup failed: "+err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
respond(w, 200, map[string]string{
|
||||
"status": "ok", "path": backupPath, "timestamp": timestamp,
|
||||
"status": "ok",
|
||||
"path": backupDir,
|
||||
"timestamp": timestamp,
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
@@ -25,6 +25,7 @@ type ConsolidateRequest struct {
|
||||
SQLitePath string `json:"sqlite_path"` // SQLite 图谱路径
|
||||
LLMEndpoint string `json:"llm_endpoint"` // LLM API 端点
|
||||
LLMModel string `json:"llm_model"` // LLM 模型名
|
||||
LLMApiKey string `json:"llm_api_key"` // LLM API Key (Authorization header)
|
||||
LLMBudget int `json:"llm_budget"` // 本次可用 LLM 次数
|
||||
Epsilon float64 `json:"epsilon"` // DBSCAN 邻域半径
|
||||
MinPoints int `json:"min_points"` // DBSCAN 最小点数
|
||||
@@ -65,13 +66,16 @@ const (
|
||||
// Run 通过 Unix Socket 调 Rust zhiyi-consolidate,执行深度整合
|
||||
func Run(dataDir, sqlitePath, mode string) (*Result, error) {
|
||||
return RunWithOptions(ConsolidateRequest{
|
||||
Task: mode,
|
||||
LanceDBPath: dataDir,
|
||||
SQLitePath: sqlitePath,
|
||||
LLMBudget: 20,
|
||||
Epsilon: 0.3,
|
||||
MinPoints: 3,
|
||||
})
|
||||
Task: mode,
|
||||
LanceDBPath: dataDir,
|
||||
SQLitePath: sqlitePath,
|
||||
LLMEndpoint: os.Getenv("LLM_ENDPOINT"),
|
||||
LLMModel: os.Getenv("LLM_MODEL"),
|
||||
LLMApiKey: os.Getenv("LLM_API_KEY"),
|
||||
LLMBudget: 20,
|
||||
Epsilon: 0.3,
|
||||
MinPoints: 3,
|
||||
})
|
||||
}
|
||||
|
||||
// RunWithOptions 完整参数调用
|
||||
|
||||
+21
-6
@@ -55,6 +55,10 @@ struct Args {
|
||||
#[arg(long, default_value = "deepseek/deepseek-v4-pro")]
|
||||
llm_model: String,
|
||||
|
||||
/// LLM API Key (Authorization header)
|
||||
#[arg(long, default_value = "")]
|
||||
llm_api_key: String,
|
||||
|
||||
/// LLM 预算(本次可用次数)
|
||||
#[arg(long, default_value = "20")]
|
||||
llm_budget: usize,
|
||||
@@ -90,6 +94,9 @@ struct ConsolidateRequest {
|
||||
task: String,
|
||||
lancedb_path: String,
|
||||
sqlite_path: String,
|
||||
#[serde(rename = "llm_endpoint")] llm_endpoint: String,
|
||||
#[serde(rename = "llm_model")] llm_model: String,
|
||||
#[serde(rename = "llm_api_key")] llm_api_key: String,
|
||||
llm_budget: usize,
|
||||
epsilon: f64,
|
||||
min_points: usize,
|
||||
@@ -297,11 +304,19 @@ fn handle_client(mut stream: UnixStream, args: &Args, lancedb: LanceDBOps, state
|
||||
}
|
||||
};
|
||||
let run_args = Args {
|
||||
mode: req.task, data_dir: req.lancedb_path, sqlite_path: req.sqlite_path,
|
||||
llm_endpoint: args.llm_endpoint.clone(), llm_model: args.llm_model.clone(),
|
||||
llm_budget: req.llm_budget, socket: None,
|
||||
model_dir: String::new(), text: None, texts: None,
|
||||
epsilon: req.epsilon, min_points: req.min_points,
|
||||
mode: req.task.clone(),
|
||||
data_dir: req.lancedb_path.clone(),
|
||||
sqlite_path: req.sqlite_path.clone(),
|
||||
llm_endpoint: req.llm_endpoint.clone(),
|
||||
llm_model: req.llm_model.clone(),
|
||||
llm_api_key: req.llm_api_key.clone(),
|
||||
llm_budget: req.llm_budget,
|
||||
socket: None,
|
||||
model_dir: String::new(),
|
||||
text: None,
|
||||
texts: None,
|
||||
epsilon: req.epsilon,
|
||||
min_points: req.min_points,
|
||||
};
|
||||
let report = run_consolidation(&run_args, &lancedb);
|
||||
send_ok(&mut stream, &serde_json::to_string(&report).unwrap_or_default());
|
||||
@@ -429,7 +444,7 @@ fn run_consolidation(args: &Args, lancedb: &LanceDBOps) -> ConsolidationReport {
|
||||
|
||||
// Step 4: 质量回溯
|
||||
if args.mode == "full" && !args.llm_endpoint.is_empty() {
|
||||
let backtracer = QualityBacktracer::new(&args.llm_endpoint, &args.llm_model);
|
||||
let backtracer = QualityBacktracer::new(&args.llm_endpoint, &args.llm_model, &args.llm_api_key);
|
||||
// 从 LanceDB 加载(content = distilled, source metadata = original)
|
||||
let all_records = lancedb.scan_all().unwrap_or_default();
|
||||
let samples: Vec<QualitySample> = all_records
|
||||
|
||||
@@ -35,17 +35,19 @@ pub struct SampleBacktrace {
|
||||
|
||||
/// 质量回溯器
|
||||
pub struct QualityBacktracer {
|
||||
pub llm_endpoint: String, // LLM API 端点 (new-api / molfang)
|
||||
pub llm_endpoint: String, // LLM API 端点 (new-api / molfang)
|
||||
pub llm_model: String,
|
||||
pub api_key: String, // API Key for Authorization header
|
||||
pub client: Client,
|
||||
pub score_threshold: f64, // 信息损失阈值 (默认 0.7)
|
||||
pub score_threshold: f64, // 信息损失阈值 (默认 0.7)
|
||||
}
|
||||
|
||||
impl QualityBacktracer {
|
||||
pub fn new(llm_endpoint: &str, llm_model: &str) -> Self {
|
||||
pub fn new(llm_endpoint: &str, llm_model: &str, api_key: &str) -> Self {
|
||||
Self {
|
||||
llm_endpoint: llm_endpoint.to_string(),
|
||||
llm_model: llm_model.to_string(),
|
||||
api_key: api_key.to_string(),
|
||||
client: Client::builder()
|
||||
.timeout(Duration::from_secs(30))
|
||||
.build()
|
||||
@@ -135,15 +137,16 @@ impl QualityBacktracer {
|
||||
"temperature": 0.3,
|
||||
"max_tokens": 200
|
||||
});
|
||||
|
||||
let resp = self.client
|
||||
let resp = self
|
||||
.client
|
||||
.post(&self.llm_endpoint)
|
||||
.header("Content-Type", "application/json")
|
||||
.header("Authorization", format!("Bearer {}", self.api_key))
|
||||
.body(serde_json::to_string(&body)?)
|
||||
.send()?
|
||||
.text()?;
|
||||
.send()?;
|
||||
let text = resp.text()?;
|
||||
|
||||
let parsed: serde_json::Value = serde_json::from_str(&resp)?;
|
||||
let parsed: serde_json::Value = serde_json::from_str(&text)?;
|
||||
let content = parsed["choices"][0]["message"]["content"]
|
||||
.as_str()
|
||||
.unwrap_or("")
|
||||
|
||||
Reference in New Issue
Block a user