feat: iPet → iAs 完整迁移,Rust 版微信 AI 助手
Phase 1 ✅ CLI 框架 + 配置系统 - clap 子命令: login / listen / send / whoami / usage - config.json + env var 替换 - tracing 日志系统 - state 持久化(auth/runtime 文件存 + PostgreSQL) Phase 2 ✅ 微信通道 - wechat::client — 完整 iLink Bot HTTP API 实现 - 扫码登录(终端二维码 + 轮询状态) - 长轮询 getupdates / 消息收发 / 监听注册 Phase 3 ✅ AI 对话(纯文本 + function calling) - LlmProvider trait: DeepSeek + LM Studio 实现 - SSE 流式解析(text / reasoning / tool_calls delta / usage) - Conversation: 消息历史 + chat / chat_with_tools 工具循环 Phase 4 ✅ PostgreSQL 集成 - app_state(认证 KV 存储) - chat_records(消息收发记录) - llm_usage(Token 用量统计缓存命中率) - user_memories(长期记忆持久化) - pending_approvals(审批确认码) - scheduled_tasks(定时任务表) Phase 5 ✅ 一切皆 Skill(工具系统) - SkillRegistry: 系统 + 用户 skills 双目录合并 - SKILL.md 解析器 + 子进程执行器(stdin JSON → stdout) - 9 个系统 Skills: datetime / weather / search / email / shell / schedule / memos / read_memories / read_summaries - ApprovalManager: High 风险技能 → 确认码审批(透明模式) - High 风险技能:确认码审批(透明模式) Phase 6 ✅ 定时任务调度器 上下文管理 - ChatSession: checkpoint + token budget (28K) + summaries - Token 估算器(中英文自适应) - 12h 空闲 → trigger_idle_summary(不入会话) - Budget 溢出 → trigger_overflow_summary(入会话 + drain 旧消息) - Summarizer: LLM 生成自然语言摘要(fallback 简单截断) - 长期记忆 / 摘要 通过 read_memories / read_summaries 工具按需读取 工具调用日志 + Token 统计 - INFO: 工具名 + 参数 + 结果摘要 - DEBUG: 子进程 exit/stdout/stderr - ias usage --since --until --model 查看用量和缓存命中率
This commit is contained in:
@@ -0,0 +1,193 @@
|
||||
use chrono::{DateTime, Utc};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use sqlx::PgPool;
|
||||
|
||||
use crate::state::AuthState;
|
||||
|
||||
// ─── 认证状态 ───
|
||||
|
||||
/// 从数据库加载认证状态
|
||||
pub async fn load_auth(pool: &PgPool) -> Option<AuthState> {
|
||||
let row = sqlx::query_as::<_, (serde_json::Value,)>(
|
||||
"SELECT value FROM app_state WHERE key = 'auth'",
|
||||
)
|
||||
.fetch_optional(pool)
|
||||
.await
|
||||
.ok()??;
|
||||
|
||||
serde_json::from_value(row.0).ok()
|
||||
}
|
||||
|
||||
/// 保存认证状态到数据库
|
||||
pub async fn save_auth(pool: &PgPool, auth: &AuthState) -> Result<(), String> {
|
||||
let value = serde_json::to_value(auth).map_err(|e| format!("序列化 auth 失败: {}", e))?;
|
||||
|
||||
sqlx::query(
|
||||
r#"
|
||||
INSERT INTO app_state (key, value, updated_at)
|
||||
VALUES ('auth', $1, NOW())
|
||||
ON CONFLICT (key) DO UPDATE
|
||||
SET value = EXCLUDED.value, updated_at = NOW()
|
||||
"#,
|
||||
)
|
||||
.bind(&value)
|
||||
.execute(pool)
|
||||
.await
|
||||
.map_err(|e| format!("保存 auth 到数据库失败: {}", e))?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
// ─── 聊天记录 ───
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, sqlx::FromRow)]
|
||||
pub struct ChatRecord {
|
||||
pub id: i64,
|
||||
pub created_at: DateTime<Utc>,
|
||||
pub direction: String,
|
||||
pub user_id: String,
|
||||
pub account_id: String,
|
||||
pub text: String,
|
||||
pub source: String,
|
||||
pub context_token: String,
|
||||
pub message_id: String,
|
||||
}
|
||||
|
||||
/// 插入一条聊天记录
|
||||
pub async fn insert_chat_record(
|
||||
pool: &PgPool,
|
||||
direction: &str,
|
||||
user_id: &str,
|
||||
account_id: &str,
|
||||
text: &str,
|
||||
source: &str,
|
||||
context_token: Option<&str>,
|
||||
message_id: &str,
|
||||
) -> Result<i64, String> {
|
||||
let ctx = context_token.unwrap_or("");
|
||||
|
||||
let row: (i64,) = sqlx::query_as(
|
||||
r#"
|
||||
INSERT INTO chat_records (direction, user_id, account_id, text, source, context_token, message_id)
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7)
|
||||
RETURNING id
|
||||
"#,
|
||||
)
|
||||
.bind(direction)
|
||||
.bind(user_id)
|
||||
.bind(account_id)
|
||||
.bind(text)
|
||||
.bind(source)
|
||||
.bind(ctx)
|
||||
.bind(message_id)
|
||||
.fetch_one(pool)
|
||||
.await
|
||||
.map_err(|e| format!("插入聊天记录失败: {}", e))?;
|
||||
|
||||
Ok(row.0)
|
||||
}
|
||||
|
||||
/// 查询最近的聊天记录(用户维度)
|
||||
pub async fn list_recent_chat_records(
|
||||
pool: &PgPool,
|
||||
user_id: &str,
|
||||
limit: i64,
|
||||
) -> Result<Vec<ChatRecord>, String> {
|
||||
let records = sqlx::query_as::<_, ChatRecord>(
|
||||
r#"
|
||||
SELECT id, created_at, direction, user_id, account_id, text, source, context_token, message_id
|
||||
FROM chat_records
|
||||
WHERE user_id = $1
|
||||
ORDER BY created_at DESC
|
||||
LIMIT $2
|
||||
"#,
|
||||
)
|
||||
.bind(user_id)
|
||||
.bind(limit)
|
||||
.fetch_all(pool)
|
||||
.await
|
||||
.map_err(|e| format!("查询聊天记录失败: {}", e))?;
|
||||
|
||||
Ok(records)
|
||||
}
|
||||
|
||||
// ─── LLM 用量 ───
|
||||
|
||||
/// 插入一条 LLM 用量记录
|
||||
pub async fn insert_llm_usage(
|
||||
pool: &PgPool,
|
||||
user_id: &str,
|
||||
model: &str,
|
||||
provider: &str,
|
||||
prompt_tokens: u32,
|
||||
completion_tokens: u32,
|
||||
cache_hit_tokens: u32,
|
||||
cache_miss_tokens: u32,
|
||||
) -> Result<(), String> {
|
||||
let total = prompt_tokens + completion_tokens;
|
||||
sqlx::query(
|
||||
r#"
|
||||
INSERT INTO llm_usage (user_id, model, provider, prompt_tokens, completion_tokens, total_tokens, cache_hit_tokens, cache_miss_tokens)
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7, $8)
|
||||
"#,
|
||||
)
|
||||
.bind(user_id)
|
||||
.bind(model)
|
||||
.bind(provider)
|
||||
.bind(prompt_tokens as i32)
|
||||
.bind(completion_tokens as i32)
|
||||
.bind(total as i32)
|
||||
.bind(cache_hit_tokens as i32)
|
||||
.bind(cache_miss_tokens as i32)
|
||||
.execute(pool)
|
||||
.await
|
||||
.map_err(|e| format!("插入 LLM 用量失败: {}", e))?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// LLM 用量聚合统计
|
||||
#[derive(Debug, Clone, sqlx::FromRow)]
|
||||
pub struct LlmUsageStats {
|
||||
pub total_calls: i64,
|
||||
pub total_prompt_tokens: i64,
|
||||
pub total_completion_tokens: i64,
|
||||
pub total_tokens: i64,
|
||||
pub total_cache_hit: i64,
|
||||
pub total_cache_miss: i64,
|
||||
}
|
||||
|
||||
/// 查询 LLM 用量统计(按时间范围过滤)
|
||||
pub async fn query_llm_usage_stats(
|
||||
pool: &PgPool,
|
||||
since: Option<chrono::DateTime<chrono::Utc>>,
|
||||
until: Option<chrono::DateTime<chrono::Utc>>,
|
||||
model_filter: Option<&str>,
|
||||
) -> Result<LlmUsageStats, String> {
|
||||
let since = since.unwrap_or_else(|| {
|
||||
chrono::Utc::now() - chrono::Duration::days(7)
|
||||
});
|
||||
let until = until.unwrap_or_else(chrono::Utc::now);
|
||||
|
||||
let row = sqlx::query_as::<_, LlmUsageStats>(
|
||||
r#"
|
||||
SELECT
|
||||
COUNT(*)::bigint as total_calls,
|
||||
COALESCE(SUM(prompt_tokens), 0)::bigint as total_prompt_tokens,
|
||||
COALESCE(SUM(completion_tokens), 0)::bigint as total_completion_tokens,
|
||||
COALESCE(SUM(total_tokens), 0)::bigint as total_tokens,
|
||||
COALESCE(SUM(cache_hit_tokens), 0)::bigint as total_cache_hit,
|
||||
COALESCE(SUM(cache_miss_tokens), 0)::bigint as total_cache_miss
|
||||
FROM llm_usage
|
||||
WHERE created_at >= $1 AND created_at <= $2
|
||||
AND ($3::text IS NULL OR model = $3)
|
||||
"#,
|
||||
)
|
||||
.bind(since)
|
||||
.bind(until)
|
||||
.bind(model_filter)
|
||||
.fetch_one(pool)
|
||||
.await
|
||||
.map_err(|e| format!("查询 LLM 用量失败: {}", e))?;
|
||||
|
||||
Ok(row)
|
||||
}
|
||||
Reference in New Issue
Block a user