Spaces:
Sleeping
Sleeping
Upload 8 files
Browse files- database/setup.py +139 -140
database/setup.py
CHANGED
|
@@ -1,151 +1,150 @@
|
|
| 1 |
-
from langchain_google_genai import ChatGoogleGenerativeAI
|
| 2 |
-
from langchain_core.messages import AIMessage, HumanMessage, ToolMessage
|
| 3 |
-
from typing import List, Any
|
| 4 |
-
import json
|
| 5 |
import os
|
| 6 |
-
import
|
|
|
|
|
|
|
|
|
|
| 7 |
|
| 8 |
-
from .
|
| 9 |
-
from tools.tool_registry import get_tool_by_name
|
| 10 |
|
| 11 |
-
#
|
| 12 |
-
|
| 13 |
-
|
|
|
|
| 14 |
|
| 15 |
-
|
| 16 |
-
|
|
|
|
|
|
|
| 17 |
|
| 18 |
-
如果需要使用工具,请严格按照以下JSON格式进行响应,不要包含任何其他文本或解释:
|
| 19 |
-
{{
|
| 20 |
-
"tool": "要调用的工具名称",
|
| 21 |
-
"tool_input": {{ "参数1": "值1", "参数2": "值2" }}
|
| 22 |
-
}}
|
| 23 |
|
| 24 |
-
|
|
|
|
|
|
|
| 25 |
|
| 26 |
-
|
| 27 |
-
{chat_history}
|
| 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 |
-
if match:
|
| 59 |
-
json_str = match.group(0)
|
| 60 |
-
else:
|
| 61 |
-
return None
|
| 62 |
-
|
| 63 |
-
try:
|
| 64 |
-
return json.loads(json_str)
|
| 65 |
-
except json.JSONDecodeError:
|
| 66 |
-
return None
|
| 67 |
-
# ----------------------------------------------------
|
| 68 |
-
|
| 69 |
-
def _format_tools_for_prompt(self, tools: List[dict]) -> str:
|
| 70 |
-
# ... (此函数保持不变) ...
|
| 71 |
-
if not tools: return "没有可用的工具。"
|
| 72 |
-
tool_strings = []
|
| 73 |
-
for tool in tools:
|
| 74 |
-
try:
|
| 75 |
-
params = json.loads(tool['parameters'])
|
| 76 |
-
param_str = ", ".join([f"{p_name}: {p_type}" for p_name, p_type in params.items()])
|
| 77 |
-
tool_strings.append(f"- 工具名称: {tool['name']}\n - 描述: {tool['description']}\n - 参数: {param_str}")
|
| 78 |
-
except (json.JSONDecodeError, TypeError):
|
| 79 |
-
tool_strings.append(f"- 工具名称: {tool['name']}\n - 描述: {tool['description']}\n - 参数: 无法解析")
|
| 80 |
-
return "\n".join(tool_strings)
|
| 81 |
-
|
| 82 |
-
def _format_chat_history(self) -> str:
|
| 83 |
-
# ... (此函数保持不变) ...
|
| 84 |
-
formatted_history = []
|
| 85 |
-
for msg in self.chat_history:
|
| 86 |
-
if isinstance(msg, HumanMessage): formatted_history.append(f"用户: {msg.content}")
|
| 87 |
-
elif isinstance(msg, AIMessage): formatted_history.append(f"助理: {msg.content}")
|
| 88 |
-
elif isinstance(msg, ToolMessage): formatted_history.append(f"工具结果: {msg.content}")
|
| 89 |
-
return "\n".join(formatted_history)
|
| 90 |
-
|
| 91 |
-
def stream_run(self, user_input: str):
|
| 92 |
-
self.chat_history.append(HumanMessage(content=user_input))
|
| 93 |
-
yield "🤔 正在分析您的问题...\n"
|
| 94 |
-
|
| 95 |
-
yield "🔍 正在从工具库中推荐相关工具...\n"
|
| 96 |
-
recommended_tools_meta = self.tool_recommender.recommend_tools(user_input)
|
| 97 |
-
|
| 98 |
-
if not recommended_tools_meta:
|
| 99 |
-
yield "ℹ️ 未找到相关工具,将直接回答。\n"
|
| 100 |
-
recommended_tools_prompt = "没有推荐的工具。"
|
| 101 |
-
else:
|
| 102 |
-
tool_names = [t['name'] for t in recommended_tools_meta]
|
| 103 |
-
yield f"✅ 推荐工具: `{', '.join(tool_names)}`\n"
|
| 104 |
-
recommended_tools_prompt = self._format_tools_for_prompt(recommended_tools_meta)
|
| 105 |
-
|
| 106 |
-
yield f"🧠 正在让AI大脑({self.model_name})决定如何行动...\n"
|
| 107 |
-
prompt = AGENT_PROMPT_TEMPLATE.format(
|
| 108 |
-
tools=recommended_tools_prompt,
|
| 109 |
-
chat_history=self._format_chat_history(),
|
| 110 |
-
input=user_input
|
| 111 |
)
|
| 112 |
-
|
| 113 |
-
|
| 114 |
-
|
| 115 |
-
|
| 116 |
-
|
| 117 |
-
|
| 118 |
-
|
| 119 |
-
|
| 120 |
-
|
| 121 |
-
|
| 122 |
-
|
| 123 |
-
|
| 124 |
-
|
| 125 |
-
|
| 126 |
-
|
| 127 |
-
|
| 128 |
-
|
| 129 |
-
|
| 130 |
-
|
| 131 |
-
|
| 132 |
-
|
| 133 |
-
|
| 134 |
-
|
| 135 |
-
|
| 136 |
-
|
| 137 |
-
|
| 138 |
-
|
| 139 |
-
|
| 140 |
-
|
| 141 |
-
|
| 142 |
-
|
| 143 |
-
|
| 144 |
-
|
| 145 |
-
|
| 146 |
-
|
| 147 |
-
|
| 148 |
-
|
| 149 |
-
|
| 150 |
-
|
| 151 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
import os
|
| 2 |
+
import sqlite3
|
| 3 |
+
import json
|
| 4 |
+
from pymilvus import MilvusClient, FieldSchema, CollectionSchema, DataType
|
| 5 |
+
import google.generativeai as genai
|
| 6 |
|
| 7 |
+
from tools.tool_registry import get_all_tools
|
|
|
|
| 8 |
|
| 9 |
+
# --- 配置持久化路径 ---
|
| 10 |
+
DATA_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "data"))
|
| 11 |
+
SQLITE_DB_PATH = os.path.join(DATA_DIR, "tools.metadata.db")
|
| 12 |
+
MILVUS_DATA_PATH = os.path.join(DATA_DIR, "milvus_lite.db")
|
| 13 |
|
| 14 |
+
# --- 模型配置 ---
|
| 15 |
+
EMBEDDING_DIM = 3072
|
| 16 |
+
EMBEDDING_MODEL_NAME = "gemini-embedding-exp-03-07"
|
| 17 |
+
MILVUS_COLLECTION_NAME = "tool_embeddings"
|
| 18 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 19 |
|
| 20 |
+
def initialize_system():
|
| 21 |
+
print("--- 开始系统初始化 (最终通关版) ---")
|
| 22 |
+
os.makedirs(DATA_DIR, exist_ok=True)
|
| 23 |
|
| 24 |
+
# --- 正确的初始化顺序 ---
|
|
|
|
| 25 |
|
| 26 |
+
# 1. 初始化SQLite并同步工具元数据
|
| 27 |
+
# 确保SQLite里总是有最新的工具信息
|
| 28 |
+
_init_sqlite_db()
|
| 29 |
+
all_tools_definitions = get_all_tools()
|
| 30 |
+
_sync_tools_to_sqlite(all_tools_definitions)
|
| 31 |
|
| 32 |
+
# 2. 初始化Milvus并同步向量
|
| 33 |
+
# 它会从已经填充好的SQLite中读取数据
|
| 34 |
+
milvus_client = _init_milvus_and_sync_embeddings()
|
| 35 |
|
| 36 |
+
# 3. 创建工具推荐器
|
| 37 |
+
from core.tool_recommender import DirectToolRecommender
|
| 38 |
+
|
| 39 |
+
tool_recommender = DirectToolRecommender(
|
| 40 |
+
milvus_client=milvus_client, sqlite_db_path=SQLITE_DB_PATH
|
| 41 |
+
)
|
| 42 |
+
|
| 43 |
+
print("--- 系统初始化完成 ---")
|
| 44 |
+
return all_tools_definitions, tool_recommender
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
def _init_sqlite_db():
|
| 48 |
+
print(f"SQLite DB 路径: {SQLITE_DB_PATH}")
|
| 49 |
+
with sqlite3.connect(SQLITE_DB_PATH) as conn:
|
| 50 |
+
cursor = conn.cursor()
|
| 51 |
+
cursor.execute(
|
| 52 |
+
"""
|
| 53 |
+
CREATE TABLE IF NOT EXISTS tools (
|
| 54 |
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
| 55 |
+
name TEXT UNIQUE NOT NULL,
|
| 56 |
+
description TEXT NOT NULL,
|
| 57 |
+
parameters TEXT NOT NULL
|
| 58 |
+
)
|
| 59 |
+
"""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 60 |
)
|
| 61 |
+
conn.commit()
|
| 62 |
+
print("SQLite DB 表已确认存在。")
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
def _sync_tools_to_sqlite(tools_definitions):
|
| 66 |
+
print("正在同步工具元数据到SQLite...")
|
| 67 |
+
with sqlite3.connect(SQLITE_DB_PATH) as conn:
|
| 68 |
+
cursor = conn.cursor()
|
| 69 |
+
for tool in tools_definitions:
|
| 70 |
+
cursor.execute("SELECT id FROM tools WHERE name = ?", (tool.name,))
|
| 71 |
+
if cursor.fetchone() is None:
|
| 72 |
+
cursor.execute(
|
| 73 |
+
"INSERT INTO tools (name, description, parameters) VALUES (?, ?, ?)",
|
| 74 |
+
(tool.name, tool.description, json.dumps(tool.args)),
|
| 75 |
+
)
|
| 76 |
+
print(f" - 新增工具到SQLite: {tool.name}")
|
| 77 |
+
conn.commit()
|
| 78 |
+
print("SQLite同步完成。")
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
def _init_milvus_and_sync_embeddings():
|
| 82 |
+
print(f"Milvus Lite 数据路径: {MILVUS_DATA_PATH}")
|
| 83 |
+
client = MilvusClient(uri=MILVUS_DATA_PATH)
|
| 84 |
+
|
| 85 |
+
# 每次启动都重新创建集合,确保维度正确且数据最新
|
| 86 |
+
if client.has_collection(collection_name=MILVUS_COLLECTION_NAME):
|
| 87 |
+
client.drop_collection(collection_name=MILVUS_COLLECTION_NAME)
|
| 88 |
+
print("发现旧的Milvus集合,已删除以重建。")
|
| 89 |
+
|
| 90 |
+
print(f"Milvus集合 '{MILVUS_COLLECTION_NAME}' 正在创建,维度为 {EMBEDDING_DIM}...")
|
| 91 |
+
fields = [
|
| 92 |
+
FieldSchema(name="id", dtype=DataType.INT64, is_primary=True),
|
| 93 |
+
FieldSchema(name="embedding", dtype=DataType.FLOAT_VECTOR, dim=EMBEDDING_DIM),
|
| 94 |
+
]
|
| 95 |
+
schema = CollectionSchema(fields)
|
| 96 |
+
client.create_collection(collection_name=MILVUS_COLLECTION_NAME, schema=schema)
|
| 97 |
+
|
| 98 |
+
index_params = client.prepare_index_params()
|
| 99 |
+
index_params.add_index(
|
| 100 |
+
field_name="embedding", index_type="AUTOINDEX", metric_type="L2"
|
| 101 |
+
)
|
| 102 |
+
client.create_index(
|
| 103 |
+
collection_name=MILVUS_COLLECTION_NAME, index_params=index_params
|
| 104 |
+
)
|
| 105 |
+
print("Milvus集合和索引创建完成。")
|
| 106 |
+
|
| 107 |
+
# --- 关键:现在我们才同步嵌入 ---
|
| 108 |
+
_sync_tool_embeddings_to_milvus(client)
|
| 109 |
+
|
| 110 |
+
client.load_collection(collection_name=MILVUS_COLLECTION_NAME)
|
| 111 |
+
return client
|
| 112 |
+
|
| 113 |
+
|
| 114 |
+
def _sync_tool_embeddings_to_milvus(milvus_client):
|
| 115 |
+
print("正在同步工具嵌入到Milvus...")
|
| 116 |
+
api_key = os.environ.get("GEMINI_API_KEY")
|
| 117 |
+
if not api_key:
|
| 118 |
+
print("错误:无法找到GEMINI_API_KEY。")
|
| 119 |
+
return
|
| 120 |
+
genai.configure(api_key=api_key)
|
| 121 |
+
|
| 122 |
+
with sqlite3.connect(SQLITE_DB_PATH) as conn:
|
| 123 |
+
cursor = conn.cursor()
|
| 124 |
+
cursor.execute("SELECT id, description FROM tools")
|
| 125 |
+
all_tools_in_db = cursor.fetchall()
|
| 126 |
+
|
| 127 |
+
if not all_tools_in_db:
|
| 128 |
+
print("SQLite中没有工具可同步,这是一个错误!")
|
| 129 |
+
return
|
| 130 |
+
|
| 131 |
+
print(f"从SQLite发现 {len(all_tools_in_db)} 个工具,正在生成嵌入...")
|
| 132 |
+
docs_to_embed = [tool[1] for tool in all_tools_in_db]
|
| 133 |
+
|
| 134 |
+
print(f"使用嵌入模型: {EMBEDDING_MODEL_NAME}")
|
| 135 |
+
result = genai.embed_content(
|
| 136 |
+
model=EMBEDDING_MODEL_NAME,
|
| 137 |
+
content=docs_to_embed,
|
| 138 |
+
task_type="retrieval_document",
|
| 139 |
+
)
|
| 140 |
+
|
| 141 |
+
embeddings = result["embedding"]
|
| 142 |
+
tool_ids_to_insert = [tool[0] for tool in all_tools_in_db]
|
| 143 |
+
|
| 144 |
+
data_to_insert = [
|
| 145 |
+
{"id": tool_id, "embedding": embedding}
|
| 146 |
+
for tool_id, embedding in zip(tool_ids_to_insert, embeddings)
|
| 147 |
+
]
|
| 148 |
+
|
| 149 |
+
milvus_client.insert(collection_name=MILVUS_COLLECTION_NAME, data=data_to_insert)
|
| 150 |
+
print(f"成功将 {len(data_to_insert)} 个新嵌入插入到Milvus。")
|