jarvis-ai-assistant 0.1.65__tar.gz → 0.1.67__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of jarvis-ai-assistant might be problematic. Click here for more details.

Files changed (41) hide show
  1. {jarvis_ai_assistant-0.1.65/src/jarvis_ai_assistant.egg-info → jarvis_ai_assistant-0.1.67}/PKG-INFO +4 -5
  2. {jarvis_ai_assistant-0.1.65 → jarvis_ai_assistant-0.1.67}/README.md +3 -4
  3. {jarvis_ai_assistant-0.1.65 → jarvis_ai_assistant-0.1.67}/pyproject.toml +1 -1
  4. {jarvis_ai_assistant-0.1.65 → jarvis_ai_assistant-0.1.67}/setup.py +1 -1
  5. {jarvis_ai_assistant-0.1.65 → jarvis_ai_assistant-0.1.67}/src/jarvis/__init__.py +1 -1
  6. jarvis_ai_assistant-0.1.67/src/jarvis/jarvis_codebase/main.py +447 -0
  7. {jarvis_ai_assistant-0.1.65 → jarvis_ai_assistant-0.1.67}/src/jarvis/jarvis_coder/main.py +1 -4
  8. jarvis_ai_assistant-0.1.67/src/jarvis/tools/__init__.py +6 -0
  9. {jarvis_ai_assistant-0.1.65 → jarvis_ai_assistant-0.1.67/src/jarvis_ai_assistant.egg-info}/PKG-INFO +4 -5
  10. jarvis_ai_assistant-0.1.65/src/jarvis/jarvis_codebase/main.py +0 -342
  11. jarvis_ai_assistant-0.1.65/src/jarvis/tools/__init__.py +0 -9
  12. {jarvis_ai_assistant-0.1.65 → jarvis_ai_assistant-0.1.67}/LICENSE +0 -0
  13. {jarvis_ai_assistant-0.1.65 → jarvis_ai_assistant-0.1.67}/MANIFEST.in +0 -0
  14. {jarvis_ai_assistant-0.1.65 → jarvis_ai_assistant-0.1.67}/setup.cfg +0 -0
  15. {jarvis_ai_assistant-0.1.65 → jarvis_ai_assistant-0.1.67}/src/jarvis/agent.py +0 -0
  16. {jarvis_ai_assistant-0.1.65 → jarvis_ai_assistant-0.1.67}/src/jarvis/jarvis_codebase/__init__.py +0 -0
  17. {jarvis_ai_assistant-0.1.65 → jarvis_ai_assistant-0.1.67}/src/jarvis/main.py +0 -0
  18. {jarvis_ai_assistant-0.1.65 → jarvis_ai_assistant-0.1.67}/src/jarvis/models/__init__.py +0 -0
  19. {jarvis_ai_assistant-0.1.65 → jarvis_ai_assistant-0.1.67}/src/jarvis/models/ai8.py +0 -0
  20. {jarvis_ai_assistant-0.1.65 → jarvis_ai_assistant-0.1.67}/src/jarvis/models/base.py +0 -0
  21. {jarvis_ai_assistant-0.1.65 → jarvis_ai_assistant-0.1.67}/src/jarvis/models/kimi.py +0 -0
  22. {jarvis_ai_assistant-0.1.65 → jarvis_ai_assistant-0.1.67}/src/jarvis/models/openai.py +0 -0
  23. {jarvis_ai_assistant-0.1.65 → jarvis_ai_assistant-0.1.67}/src/jarvis/models/oyi.py +0 -0
  24. {jarvis_ai_assistant-0.1.65 → jarvis_ai_assistant-0.1.67}/src/jarvis/models/registry.py +0 -0
  25. {jarvis_ai_assistant-0.1.65 → jarvis_ai_assistant-0.1.67}/src/jarvis/tools/base.py +0 -0
  26. {jarvis_ai_assistant-0.1.65 → jarvis_ai_assistant-0.1.67}/src/jarvis/tools/codebase_qa.py +0 -0
  27. {jarvis_ai_assistant-0.1.65 → jarvis_ai_assistant-0.1.67}/src/jarvis/tools/coder.py +0 -0
  28. {jarvis_ai_assistant-0.1.65 → jarvis_ai_assistant-0.1.67}/src/jarvis/tools/file_ops.py +0 -0
  29. {jarvis_ai_assistant-0.1.65 → jarvis_ai_assistant-0.1.67}/src/jarvis/tools/generator.py +0 -0
  30. {jarvis_ai_assistant-0.1.65 → jarvis_ai_assistant-0.1.67}/src/jarvis/tools/methodology.py +0 -0
  31. {jarvis_ai_assistant-0.1.65 → jarvis_ai_assistant-0.1.67}/src/jarvis/tools/registry.py +0 -0
  32. {jarvis_ai_assistant-0.1.65 → jarvis_ai_assistant-0.1.67}/src/jarvis/tools/search.py +0 -0
  33. {jarvis_ai_assistant-0.1.65 → jarvis_ai_assistant-0.1.67}/src/jarvis/tools/shell.py +0 -0
  34. {jarvis_ai_assistant-0.1.65 → jarvis_ai_assistant-0.1.67}/src/jarvis/tools/sub_agent.py +0 -0
  35. {jarvis_ai_assistant-0.1.65 → jarvis_ai_assistant-0.1.67}/src/jarvis/tools/webpage.py +0 -0
  36. {jarvis_ai_assistant-0.1.65 → jarvis_ai_assistant-0.1.67}/src/jarvis/utils.py +0 -0
  37. {jarvis_ai_assistant-0.1.65 → jarvis_ai_assistant-0.1.67}/src/jarvis_ai_assistant.egg-info/SOURCES.txt +0 -0
  38. {jarvis_ai_assistant-0.1.65 → jarvis_ai_assistant-0.1.67}/src/jarvis_ai_assistant.egg-info/dependency_links.txt +0 -0
  39. {jarvis_ai_assistant-0.1.65 → jarvis_ai_assistant-0.1.67}/src/jarvis_ai_assistant.egg-info/entry_points.txt +0 -0
  40. {jarvis_ai_assistant-0.1.65 → jarvis_ai_assistant-0.1.67}/src/jarvis_ai_assistant.egg-info/requires.txt +0 -0
  41. {jarvis_ai_assistant-0.1.65 → jarvis_ai_assistant-0.1.67}/src/jarvis_ai_assistant.egg-info/top_level.txt +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.2
2
2
  Name: jarvis-ai-assistant
3
- Version: 0.1.65
3
+ Version: 0.1.67
4
4
  Summary: Jarvis: An AI assistant that uses tools to interact with the system
5
5
  Home-page: https://github.com/skyfireitdiy/Jarvis
6
6
  Author: skyfire
@@ -123,7 +123,6 @@ Jarvis supports configuration through environment variables that can be set in t
123
123
  |---------|------|--------|------|
124
124
  | JARVIS_PLATFORM | AI platform to use, supports kimi/openai/ai8 etc | kimi | Yes |
125
125
  | JARVIS_MODEL | Model name to use | - | No |
126
-
127
126
  | JARVIS_CODEGEN_PLATFORM | AI platform for code generation | Same as JARVIS_PLATFORM | No |
128
127
  | JARVIS_CODEGEN_MODEL | Model name for code generation | Same as JARVIS_MODEL | No |
129
128
  | JARVIS_CHEAP_PLATFORM | AI platform for cheap operations | Same as JARVIS_PLATFORM | No |
@@ -155,17 +154,17 @@ jarvis -p openai # Use OpenAI platform
155
154
 
156
155
  ### Code Modification
157
156
  ```bash
158
- jarvis coder --feature "Add new feature" # Modify code to add new feature
157
+ jarvis-coder --feature "Add new feature" # Modify code to add new feature
159
158
  ```
160
159
 
161
160
  ### Codebase Search
162
161
  ```bash
163
- jarvis codebase --search "database connection" # Search codebase
162
+ jarvis-codebase --search "database connection" # Search codebase
164
163
  ```
165
164
 
166
165
  ### Codebase Question
167
166
  ```bash
168
- jarvis codebase --ask "How to use the database?" # Ask about codebase
167
+ jarvis-codebase --ask "How to use the database?" # Ask about codebase
169
168
  ```
170
169
 
171
170
  ### Keep Chat History
@@ -65,7 +65,6 @@ Jarvis supports configuration through environment variables that can be set in t
65
65
  |---------|------|--------|------|
66
66
  | JARVIS_PLATFORM | AI platform to use, supports kimi/openai/ai8 etc | kimi | Yes |
67
67
  | JARVIS_MODEL | Model name to use | - | No |
68
-
69
68
  | JARVIS_CODEGEN_PLATFORM | AI platform for code generation | Same as JARVIS_PLATFORM | No |
70
69
  | JARVIS_CODEGEN_MODEL | Model name for code generation | Same as JARVIS_MODEL | No |
71
70
  | JARVIS_CHEAP_PLATFORM | AI platform for cheap operations | Same as JARVIS_PLATFORM | No |
@@ -97,17 +96,17 @@ jarvis -p openai # Use OpenAI platform
97
96
 
98
97
  ### Code Modification
99
98
  ```bash
100
- jarvis coder --feature "Add new feature" # Modify code to add new feature
99
+ jarvis-coder --feature "Add new feature" # Modify code to add new feature
101
100
  ```
102
101
 
103
102
  ### Codebase Search
104
103
  ```bash
105
- jarvis codebase --search "database connection" # Search codebase
104
+ jarvis-codebase --search "database connection" # Search codebase
106
105
  ```
107
106
 
108
107
  ### Codebase Question
109
108
  ```bash
110
- jarvis codebase --ask "How to use the database?" # Ask about codebase
109
+ jarvis-codebase --ask "How to use the database?" # Ask about codebase
111
110
  ```
112
111
 
113
112
  ### Keep Chat History
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "jarvis-ai-assistant"
7
- version = "0.1.65"
7
+ version = "0.1.67"
8
8
  description = "Jarvis: An AI assistant that uses tools to interact with the system"
9
9
  readme = "README.md"
10
10
  authors = [{ name = "Your Name", email = "your.email@example.com" }]
@@ -2,7 +2,7 @@ from setuptools import setup, find_packages
2
2
 
3
3
  setup(
4
4
  name="jarvis-ai-assistant",
5
- version="0.1.65",
5
+ version="0.1.67",
6
6
  author="skyfire",
7
7
  author_email="skyfireitdiy@hotmail.com",
8
8
  description="An AI assistant that uses various tools to interact with the system",
@@ -1,3 +1,3 @@
1
1
  """Jarvis AI Assistant"""
2
2
 
3
- __version__ = "0.1.65"
3
+ __version__ = "0.1.67"
@@ -0,0 +1,447 @@
1
+ import hashlib
2
+ import os
3
+ import numpy as np
4
+ import faiss
5
+ from typing import List, Tuple, Optional
6
+ from jarvis.models.registry import PlatformRegistry
7
+ import concurrent.futures
8
+ from threading import Lock
9
+ from concurrent.futures import ThreadPoolExecutor
10
+ from jarvis.utils import OutputType, PrettyOutput, find_git_root
11
+ from jarvis.utils import load_env_from_file
12
+ import argparse
13
+ from sentence_transformers import SentenceTransformer
14
+ import pickle
15
+
16
+ class CodeBase:
17
+ def __init__(self, root_dir: str):
18
+ load_env_from_file()
19
+ self.root_dir = root_dir
20
+ os.chdir(self.root_dir)
21
+ self.thread_count = os.environ.get("JARVIS_THREAD_COUNT") or 10
22
+ self.cheap_platform = os.environ.get("JARVIS_CHEAP_PLATFORM") or os.environ.get("JARVIS_PLATFORM") or "kimi"
23
+ self.cheap_model = os.environ.get("JARVIS_CHEAP_MODEL") or os.environ.get("JARVIS_MODEL") or "kimi"
24
+ self.normal_platform = os.environ.get("JARVIS_PLATFORM") or "kimi"
25
+ self.normal_model = os.environ.get("JARVIS_MODEL") or "kimi"
26
+ self.embedding_model_name = os.environ.get("JARVIS_EMBEDDING_MODEL") or "BAAI/bge-large-zh-v1.5"
27
+ if not self.cheap_platform or not self.cheap_model or not self.embedding_model_name or not self.normal_platform or not self.normal_model:
28
+ raise ValueError("JARVIS_CHEAP_PLATFORM or JARVIS_CHEAP_MODEL or JARVIS_EMBEDDING_MODEL or JARVIS_PLATFORM or JARVIS_MODEL is not set")
29
+
30
+ PrettyOutput.print(f"廉价模型使用平台: {self.cheap_platform} 模型: {self.cheap_model}", output_type=OutputType.INFO)
31
+ PrettyOutput.print(f"分析模型使用平台: {self.normal_platform} 模型: {self.normal_model}", output_type=OutputType.INFO)
32
+ PrettyOutput.print(f"嵌入模型: {self.embedding_model_name}", output_type=OutputType.INFO)
33
+ PrettyOutput.print(f"检索算法:分层导航小世界算法", output_type=OutputType.INFO)
34
+
35
+ # 初始化数据目录
36
+ self.data_dir = os.path.join(self.root_dir, ".jarvis-codebase")
37
+ if not os.path.exists(self.data_dir):
38
+ os.makedirs(self.data_dir)
39
+
40
+ # 初始化嵌入模型,使用系统默认缓存目录
41
+ try:
42
+ PrettyOutput.print("正在加载/下载模型,请稍候...", output_type=OutputType.INFO)
43
+ self.embedding_model = SentenceTransformer(self.embedding_model_name)
44
+
45
+ # 强制完全加载所有模型组件
46
+ test_text = """
47
+ 这是一段测试文本,用于确保模型完全加载。
48
+ 包含多行内容,以模拟实际使用场景。
49
+ """
50
+ # 预热模型,确保所有组件都被加载
51
+ self.embedding_model.encode([test_text],
52
+ convert_to_tensor=True,
53
+ normalize_embeddings=True)
54
+ PrettyOutput.print("模型加载完成", output_type=OutputType.SUCCESS)
55
+ except Exception as e:
56
+ PrettyOutput.print(f"加载模型失败: {str(e)}", output_type=OutputType.ERROR)
57
+ raise
58
+
59
+ self.vector_dim = self.embedding_model.get_sentence_embedding_dimension()
60
+
61
+ self.git_file_list = self.get_git_file_list()
62
+ self.platform_registry = PlatformRegistry().get_global_platform_registry()
63
+
64
+ # 初始化缓存和索引
65
+ self.cache_path = os.path.join(self.data_dir, "cache.pkl")
66
+ self.vector_cache = {}
67
+ self.file_paths = []
68
+
69
+ # 加载缓存
70
+ if os.path.exists(self.cache_path):
71
+ try:
72
+ with open(self.cache_path, 'rb') as f:
73
+ cache_data = pickle.load(f)
74
+ self.vector_cache = cache_data["vectors"]
75
+ self.file_paths = cache_data["file_paths"]
76
+ PrettyOutput.print(f"加载了 {len(self.vector_cache)} 个向量缓存",
77
+ output_type=OutputType.INFO)
78
+ # 从缓存重建索引
79
+ self.build_index()
80
+ except Exception as e:
81
+ PrettyOutput.print(f"加载缓存失败: {str(e)}",
82
+ output_type=OutputType.WARNING)
83
+ self.vector_cache = {}
84
+ self.file_paths = []
85
+ self.index = None
86
+
87
+ def get_git_file_list(self):
88
+ """获取 git 仓库中的文件列表,排除 .jarvis-codebase 目录"""
89
+ files = os.popen("git ls-files").read().splitlines()
90
+ # 过滤掉 .jarvis-codebase 目录下的文件
91
+ return [f for f in files if not f.startswith(".jarvis-codebase/")]
92
+
93
+ def is_text_file(self, file_path: str):
94
+ with open(file_path, "r", encoding="utf-8") as f:
95
+ try:
96
+ f.read()
97
+ return True
98
+ except UnicodeDecodeError:
99
+ return False
100
+
101
+ def make_description(self, file_path: str) -> str:
102
+ model = self.platform_registry.create_platform(self.cheap_platform)
103
+ model.set_model_name(self.cheap_model)
104
+ model.set_suppress_output(True)
105
+ content = open(file_path, "r", encoding="utf-8").read()
106
+ prompt = f"""请分析以下代码文件,并生成一个详细的描述。描述应该包含以下要点:
107
+
108
+ 1. 主要功能和用途
109
+ 2. 关键类和方法的作用
110
+ 3. 重要的依赖和技术特征(如使用了什么框架、算法、设计模式等)
111
+ 4. 代码处理的主要数据类型和数据结构
112
+ 5. 关键业务逻辑和处理流程
113
+ 6. 特殊功能点和亮点特性
114
+
115
+ 请用简洁专业的语言描述,突出代码的技术特征和功能特点,以便后续进行相似代码检索。
116
+
117
+ 文件路径:{file_path}
118
+ 代码内容:
119
+ {content}
120
+ """
121
+ response = model.chat(prompt)
122
+ return response
123
+
124
+ def save_cache(self):
125
+ """保存缓存数据"""
126
+ try:
127
+ cache_data = {
128
+ "vectors": self.vector_cache,
129
+ "file_paths": self.file_paths
130
+ }
131
+ with open(self.cache_path, 'wb') as f:
132
+ pickle.dump(cache_data, f)
133
+ PrettyOutput.print(f"保存了 {len(self.vector_cache)} 个向量缓存",
134
+ output_type=OutputType.INFO)
135
+ except Exception as e:
136
+ PrettyOutput.print(f"保存缓存失败: {str(e)}",
137
+ output_type=OutputType.ERROR)
138
+
139
+ def get_cached_vector(self, file_path: str, description: str) -> Optional[np.ndarray]:
140
+ """从缓存获取文件的向量表示"""
141
+ if file_path not in self.vector_cache:
142
+ return None
143
+
144
+ # 检查文件是否被修改
145
+ try:
146
+ with open(file_path, "rb") as f:
147
+ current_md5 = hashlib.md5(f.read()).hexdigest()
148
+ except Exception as e:
149
+ PrettyOutput.print(f"计算文件MD5失败 {file_path}: {str(e)}",
150
+ output_type=OutputType.ERROR)
151
+ return None
152
+
153
+ cached_data = self.vector_cache[file_path]
154
+ if cached_data["md5"] != current_md5:
155
+ return None
156
+
157
+ # 检查描述是否变化
158
+ if cached_data["description"] != description:
159
+ return None
160
+
161
+ return cached_data["vector"]
162
+
163
+ def cache_vector(self, file_path: str, vector: np.ndarray, description: str):
164
+ """缓存文件的向量表示"""
165
+ try:
166
+ with open(file_path, "rb") as f:
167
+ file_md5 = hashlib.md5(f.read()).hexdigest()
168
+ except Exception as e:
169
+ PrettyOutput.print(f"计算文件MD5失败 {file_path}: {str(e)}",
170
+ output_type=OutputType.ERROR)
171
+ file_md5 = ""
172
+
173
+ self.vector_cache[file_path] = {
174
+ "path": file_path, # 保存文件路径
175
+ "md5": file_md5, # 保存文件MD5
176
+ "description": description, # 保存文件描述
177
+ "vector": vector # 保存向量
178
+ }
179
+
180
+ # 保存缓存到文件
181
+ try:
182
+ with open(self.cache_path, 'wb') as f:
183
+ cache_data = {
184
+ "vectors": self.vector_cache,
185
+ "file_paths": self.file_paths
186
+ }
187
+ pickle.dump(cache_data, f)
188
+ except Exception as e:
189
+ PrettyOutput.print(f"保存向量缓存失败: {str(e)}",
190
+ output_type=OutputType.ERROR)
191
+
192
+ def get_embedding(self, text: str) -> np.ndarray:
193
+ """使用 transformers 模型获取文本的向量表示"""
194
+ # 对长文本进行截断
195
+ max_length = 512 # 或其他合适的长度
196
+ text = ' '.join(text.split()[:max_length])
197
+
198
+ # 获取嵌入向量
199
+ embedding = self.embedding_model.encode(text,
200
+ normalize_embeddings=True, # L2归一化
201
+ show_progress_bar=False)
202
+ vector = np.array(embedding, dtype=np.float32)
203
+ return vector
204
+
205
+ def vectorize_file(self, file_path: str, description: str) -> np.ndarray:
206
+ """将文件内容和描述向量化"""
207
+ try:
208
+ # 先尝试从缓存获取
209
+ cached_vector = self.get_cached_vector(file_path, description)
210
+ if cached_vector is not None:
211
+ return cached_vector
212
+
213
+ # 组合文件信息
214
+ combined_text = f"""
215
+ 文件路径: {file_path}
216
+ 文件描述: {description}
217
+ """
218
+ vector = self.get_embedding(combined_text)
219
+
220
+ # 保存到缓存
221
+ self.cache_vector(file_path, vector, description)
222
+ return vector
223
+ except Exception as e:
224
+ PrettyOutput.print(f"Error vectorizing file {file_path}: {str(e)}",
225
+ output_type=OutputType.ERROR)
226
+ return np.zeros(self.vector_dim, dtype=np.float32)
227
+
228
+ def clean_cache(self) -> bool:
229
+ """清理过期的缓存记录,返回是否有文件被删除"""
230
+ files_to_delete = []
231
+ for file_path in list(self.vector_cache.keys()):
232
+ if file_path not in self.git_file_list:
233
+ del self.vector_cache[file_path]
234
+ files_to_delete.append(file_path)
235
+
236
+ if files_to_delete:
237
+ self.save_cache()
238
+ PrettyOutput.print(f"清理了 {len(files_to_delete)} 个文件的缓存",
239
+ output_type=OutputType.INFO)
240
+ return True
241
+ return False
242
+
243
+ def process_file(self, file_path: str):
244
+ """处理单个文件"""
245
+ try:
246
+ # 跳过不存在的文件
247
+ if not os.path.exists(file_path):
248
+ return None
249
+
250
+ if not self.is_text_file(file_path):
251
+ return None
252
+
253
+ md5 = hashlib.md5(open(file_path, "rb").read()).hexdigest()
254
+
255
+ # 检查文件是否已经处理过且内容未变
256
+ if file_path in self.vector_cache:
257
+ if self.vector_cache[file_path].get("md5") == md5:
258
+ return None
259
+
260
+ description = self.make_description(file_path)
261
+ vector = self.vectorize_file(file_path, description)
262
+
263
+ # 保存到缓存,使用实际文件路径作为键
264
+ self.vector_cache[file_path] = {
265
+ "vector": vector,
266
+ "description": description,
267
+ "md5": md5
268
+ }
269
+
270
+ return file_path
271
+
272
+ except Exception as e:
273
+ PrettyOutput.print(f"处理文件失败 {file_path}: {str(e)}",
274
+ output_type=OutputType.ERROR,
275
+ traceback=True)
276
+ return None
277
+
278
+ def build_index(self):
279
+ """从向量缓存构建 faiss 索引"""
280
+ # 创建底层 HNSW 索引
281
+ hnsw_index = faiss.IndexHNSWFlat(self.vector_dim, 16)
282
+ hnsw_index.hnsw.efConstruction = 40
283
+ hnsw_index.hnsw.efSearch = 16
284
+
285
+ # 用 IndexIDMap 包装 HNSW 索引
286
+ self.index = faiss.IndexIDMap(hnsw_index)
287
+
288
+ vectors = []
289
+ ids = []
290
+ self.file_paths = [] # 重置文件路径列表
291
+
292
+ for i, (file_path, data) in enumerate(self.vector_cache.items()):
293
+ vectors.append(data["vector"].reshape(1, -1))
294
+ ids.append(i)
295
+ self.file_paths.append(file_path)
296
+
297
+ if vectors:
298
+ vectors = np.vstack(vectors)
299
+ self.index.add_with_ids(vectors, np.array(ids))
300
+ else:
301
+ self.index = None
302
+
303
+ def gen_vector_db_from_cache(self):
304
+ """从缓存生成向量数据库"""
305
+ self.build_index()
306
+ self.save_cache()
307
+
308
+ def generate_codebase(self):
309
+ """生成代码库索引"""
310
+ files_deleted = self.clean_cache() # 清理过期缓存
311
+ processed_files = []
312
+
313
+ # 使用线程池处理文件
314
+ with ThreadPoolExecutor(max_workers=self.thread_count) as executor:
315
+ futures = [executor.submit(self.process_file, file) for file in self.git_file_list]
316
+ for future in concurrent.futures.as_completed(futures):
317
+ result = future.result()
318
+ if result:
319
+ processed_files.append(result)
320
+ PrettyOutput.print(f"索引文件: {result}", output_type=OutputType.INFO)
321
+
322
+ if files_deleted or processed_files:
323
+ PrettyOutput.print("重新生成向量数据库", output_type=OutputType.INFO)
324
+ self.gen_vector_db_from_cache()
325
+ else:
326
+ PrettyOutput.print("没有新的文件变更,跳过向量数据库生成", output_type=OutputType.INFO)
327
+
328
+ PrettyOutput.print(f"成功为 {len(processed_files)} 个文件生成索引", output_type=OutputType.INFO)
329
+
330
+ def search_similar(self, query: str, top_k: int = 5) -> List[Tuple[str, float, str]]:
331
+ """搜索相似文件"""
332
+ model = self.platform_registry.create_platform(self.normal_platform)
333
+ model.set_model_name(self.normal_model)
334
+ model.set_suppress_output(True)
335
+
336
+ try:
337
+ prompt = f"""请根据以下查询,生成意思完全相同的另一个表述。这个表述将用于代码搜索,所以要保持专业性和准确性。
338
+ 原始查询: {query}
339
+
340
+ 请直接输出新表述,不要有编号或其他标记。
341
+ """
342
+
343
+ query = model.chat(prompt)
344
+
345
+ finally:
346
+ model.delete_chat()
347
+
348
+ PrettyOutput.print(f"查询: {query}", output_type=OutputType.INFO)
349
+
350
+ # 为每个查询获取相似文件
351
+ all_results = {} # 文件路径 -> (总分数, 出现次数, 描述)
352
+
353
+ q_vector = self.get_embedding(query)
354
+ q_vector = q_vector.reshape(1, -1)
355
+
356
+ distances, indices = self.index.search(q_vector, top_k)
357
+
358
+ PrettyOutput.print(f"查询 {query} 的结果: ", output_type=OutputType.INFO)
359
+
360
+ ret = []
361
+
362
+ for i, distance in zip(indices[0], distances[0]):
363
+ if i == -1: # faiss返回-1表示无效结果
364
+ continue
365
+
366
+ similarity = 1.0 / (1.0 + float(distance))
367
+ PrettyOutput.print(f" {self.file_paths[i]} : 距离 {distance:.3f}, 相似度 {similarity:.3f}",
368
+ output_type=OutputType.INFO)
369
+
370
+ file_path = self.file_paths[i]
371
+ data = self.vector_cache[file_path]
372
+ ret.append((file_path, similarity, data["description"]))
373
+ return ret
374
+
375
+ def ask_codebase(self, query: str, top_k: int = 5) -> List[Tuple[str, float, str]]:
376
+ """查询代码库"""
377
+ results = self.search_similar(query, top_k)
378
+ PrettyOutput.print(f"找到的关联文件: ", output_type=OutputType.INFO)
379
+ for path, score, _ in results:
380
+ PrettyOutput.print(f"文件: {path} 关联度: {score:.3f}",
381
+ output_type=OutputType.INFO)
382
+
383
+ prompt = f"""你是一个代码专家,请根据以下文件信息回答用户的问题:
384
+ """
385
+ for path, _, _ in results:
386
+ try:
387
+ content = open(path, "r", encoding="utf-8").read()
388
+ prompt += f"""
389
+ 文件路径: {path}
390
+ 文件内容:
391
+ {content}
392
+ ========================================
393
+ """
394
+ except Exception as e:
395
+ PrettyOutput.print(f"读取文件失败 {path}: {str(e)}",
396
+ output_type=OutputType.ERROR)
397
+ continue
398
+
399
+ prompt += f"""
400
+ 用户问题: {query}
401
+
402
+ 请用专业的语言回答用户的问题,如果给出的文件内容不足以回答用户的问题,请告诉用户,绝对不要胡编乱造。
403
+ """
404
+ model = self.platform_registry.create_platform(self.normal_platform)
405
+ model.set_model_name(self.normal_model)
406
+ try:
407
+ response = model.chat(prompt)
408
+ return response
409
+ finally:
410
+ model.delete_chat()
411
+
412
+
413
+ def main():
414
+ parser = argparse.ArgumentParser(description='Codebase management and search tool')
415
+ parser.add_argument('--search', type=str, help='Search query to find similar code files')
416
+ parser.add_argument('--top-k', type=int, default=5, help='Number of results to return (default: 5)')
417
+ parser.add_argument('--ask', type=str, help='Ask a question about the codebase')
418
+ args = parser.parse_args()
419
+
420
+ current_dir = find_git_root()
421
+ codebase = CodeBase(current_dir)
422
+
423
+ try:
424
+ codebase.generate_codebase()
425
+ PrettyOutput.print("\nCodebase generation completed", output_type=OutputType.SUCCESS)
426
+ except Exception as e:
427
+ PrettyOutput.print(f"Error during codebase generation: {str(e)}", output_type=OutputType.ERROR)
428
+
429
+ if args.search:
430
+ results = codebase.search_similar(args.search, args.top_k)
431
+ if not results:
432
+ PrettyOutput.print("No similar files found", output_type=OutputType.WARNING)
433
+ return
434
+
435
+ PrettyOutput.print("\nSearch Results:", output_type=OutputType.INFO)
436
+ for path, score, desc in results:
437
+ PrettyOutput.print("\n" + "="*50, output_type=OutputType.INFO)
438
+ PrettyOutput.print(f"File: {path}", output_type=OutputType.INFO)
439
+ PrettyOutput.print(f"Similarity: {score:.3f}", output_type=OutputType.INFO)
440
+ PrettyOutput.print(f"Description: {desc[100:]}", output_type=OutputType.INFO)
441
+
442
+ if args.ask:
443
+ codebase.ask_codebase(args.ask, args.top_k)
444
+
445
+
446
+ if __name__ == "__main__":
447
+ exit(main())
@@ -1,11 +1,8 @@
1
- from concurrent.futures import ThreadPoolExecutor, as_completed
2
- import hashlib
3
1
  import os
4
2
  import re
5
- import sqlite3
6
3
  import threading
7
4
  import time
8
- from typing import Dict, Any, List, Optional, Tuple
5
+ from typing import Dict, Any, List, Tuple
9
6
 
10
7
  import yaml
11
8
  from jarvis.models.base import BasePlatform
@@ -0,0 +1,6 @@
1
+ from .registry import ToolRegistry
2
+
3
+ __all__ = [
4
+ 'ToolRegistry',
5
+ ]
6
+
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.2
2
2
  Name: jarvis-ai-assistant
3
- Version: 0.1.65
3
+ Version: 0.1.67
4
4
  Summary: Jarvis: An AI assistant that uses tools to interact with the system
5
5
  Home-page: https://github.com/skyfireitdiy/Jarvis
6
6
  Author: skyfire
@@ -123,7 +123,6 @@ Jarvis supports configuration through environment variables that can be set in t
123
123
  |---------|------|--------|------|
124
124
  | JARVIS_PLATFORM | AI platform to use, supports kimi/openai/ai8 etc | kimi | Yes |
125
125
  | JARVIS_MODEL | Model name to use | - | No |
126
-
127
126
  | JARVIS_CODEGEN_PLATFORM | AI platform for code generation | Same as JARVIS_PLATFORM | No |
128
127
  | JARVIS_CODEGEN_MODEL | Model name for code generation | Same as JARVIS_MODEL | No |
129
128
  | JARVIS_CHEAP_PLATFORM | AI platform for cheap operations | Same as JARVIS_PLATFORM | No |
@@ -155,17 +154,17 @@ jarvis -p openai # Use OpenAI platform
155
154
 
156
155
  ### Code Modification
157
156
  ```bash
158
- jarvis coder --feature "Add new feature" # Modify code to add new feature
157
+ jarvis-coder --feature "Add new feature" # Modify code to add new feature
159
158
  ```
160
159
 
161
160
  ### Codebase Search
162
161
  ```bash
163
- jarvis codebase --search "database connection" # Search codebase
162
+ jarvis-codebase --search "database connection" # Search codebase
164
163
  ```
165
164
 
166
165
  ### Codebase Question
167
166
  ```bash
168
- jarvis codebase --ask "How to use the database?" # Ask about codebase
167
+ jarvis-codebase --ask "How to use the database?" # Ask about codebase
169
168
  ```
170
169
 
171
170
  ### Keep Chat History
@@ -1,342 +0,0 @@
1
- import hashlib
2
- import os
3
- import sqlite3
4
- import time
5
- import numpy as np
6
- import faiss
7
- from typing import List, Tuple, Optional
8
- from jarvis.models.registry import PlatformRegistry
9
- import concurrent.futures
10
- from threading import Lock
11
- from concurrent.futures import ThreadPoolExecutor
12
- from jarvis.utils import OutputType, PrettyOutput, find_git_root
13
- from jarvis.utils import load_env_from_file
14
- import argparse
15
- from sentence_transformers import SentenceTransformer
16
-
17
- class CodeBase:
18
- def __init__(self, root_dir: str, thread_count: int = 10):
19
- load_env_from_file()
20
- self.root_dir = root_dir
21
- os.chdir(self.root_dir)
22
- self.thread_count = thread_count
23
- self.cheap_platform = os.environ.get("JARVIS_CHEAP_PLATFORM") or os.environ.get("JARVIS_PLATFORM") or "kimi"
24
- self.cheap_model = os.environ.get("JARVIS_CHEAP_MODEL") or os.environ.get("JARVIS_MODEL") or "kimi"
25
- self.normal_platform = os.environ.get("JARVIS_PLATFORM") or "kimi"
26
- self.normal_model = os.environ.get("JARVIS_MODEL") or "kimi"
27
- self.embedding_model_name = os.environ.get("JARVIS_EMBEDDING_MODEL") or "BAAI/bge-large-zh-v1.5"
28
- if not self.cheap_platform or not self.cheap_model or not self.embedding_model_name or not self.normal_platform or not self.normal_model:
29
- raise ValueError("JARVIS_CHEAP_PLATFORM or JARVIS_CHEAP_MODEL or JARVIS_EMBEDDING_MODEL or JARVIS_PLATFORM or JARVIS_MODEL is not set")
30
-
31
- PrettyOutput.print(f"廉价模型使用平台: {self.cheap_platform} 模型: {self.cheap_model}", output_type=OutputType.INFO)
32
- PrettyOutput.print(f"分析模型使用平台: {self.normal_platform} 模型: {self.normal_model}", output_type=OutputType.INFO)
33
- PrettyOutput.print(f"嵌入模型: {self.embedding_model_name}", output_type=OutputType.INFO)
34
- PrettyOutput.print(f"检索算法:分层导航小世界算法", output_type=OutputType.INFO)
35
-
36
- # 初始化数据目录
37
- self.data_dir = os.path.join(self.root_dir, ".jarvis-codebase")
38
- if not os.path.exists(self.data_dir):
39
- os.makedirs(self.data_dir)
40
-
41
- # 初始化嵌入模型,使用系统默认缓存目录
42
- try:
43
- PrettyOutput.print("正在加载/下载模型,请稍候...", output_type=OutputType.INFO)
44
- self.embedding_model = SentenceTransformer(self.embedding_model_name)
45
-
46
- # 强制完全加载所有模型组件
47
- test_text = """
48
- 这是一段测试文本,用于确保模型完全加载。
49
- 包含多行内容,以模拟实际使用场景。
50
- """
51
- # 预热模型,确保所有组件都被加载
52
- self.embedding_model.encode([test_text],
53
- convert_to_tensor=True,
54
- normalize_embeddings=True)
55
- PrettyOutput.print("模型加载完成", output_type=OutputType.SUCCESS)
56
- except Exception as e:
57
- PrettyOutput.print(f"加载模型失败: {str(e)}", output_type=OutputType.ERROR)
58
- raise
59
-
60
- self.vector_dim = self.embedding_model.get_sentence_embedding_dimension()
61
-
62
-
63
- self.db_path = os.path.join(self.data_dir, "codebase.db")
64
- if not os.path.exists(self.db_path):
65
- self.create_db()
66
- self.git_file_list = self.get_git_file_list()
67
- self.platform_registry = PlatformRegistry().get_global_platform_registry()
68
- self.index_path = os.path.join(self.data_dir, "vectors.index")
69
- self.index = None
70
- if os.path.exists(self.index_path):
71
- PrettyOutput.print("正在加载向量数据库", output_type=OutputType.INFO)
72
- self.index = faiss.read_index(self.index_path)
73
-
74
- def get_git_file_list(self):
75
- return os.popen("git ls-files").read().splitlines()
76
-
77
- def get_db_connection(self):
78
- """创建并返回一个新的数据库连接"""
79
- return sqlite3.connect(self.db_path)
80
-
81
- def clean_db(self) -> bool:
82
- """清理数据库和向量索引中的过期记录"""
83
- db = self.get_db_connection()
84
- try:
85
- # 获取所有数据库记录
86
- all_records = db.execute("SELECT path FROM codebase").fetchall()
87
- files_to_delete = []
88
-
89
- # 找出需要删除的文件
90
- for row in all_records:
91
- if row[0] not in self.git_file_list:
92
- files_to_delete.append(row[0])
93
-
94
- if not files_to_delete:
95
- return False
96
-
97
- for file_path in files_to_delete:
98
- db.execute("DELETE FROM codebase WHERE path = ?", (file_path,))
99
-
100
- db.commit()
101
-
102
- PrettyOutput.print(f"清理了 {len(files_to_delete)} 个文件的记录",
103
- output_type=OutputType.INFO)
104
- return True
105
- finally:
106
- db.close()
107
-
108
- def create_db(self):
109
- db = self.get_db_connection()
110
- try:
111
- db.execute("CREATE TABLE IF NOT EXISTS codebase (path TEXT, md5 TEXT ,description TEXT)")
112
- db.commit()
113
- finally:
114
- db.close()
115
-
116
- def is_text_file(self, file_path: str):
117
- with open(file_path, "r", encoding="utf-8") as f:
118
- try:
119
- f.read()
120
- return True
121
- except UnicodeDecodeError:
122
- return False
123
-
124
- def make_description(self, file_path: str) -> str:
125
- model = self.platform_registry.create_platform(self.cheap_platform)
126
- model.set_model_name(self.cheap_model)
127
- model.set_suppress_output(True)
128
- content = open(file_path, "r", encoding="utf-8").read()
129
- prompt = f"""请分析以下代码文件,并生成一个详细的描述。描述应该包含以下要点:
130
-
131
- 1. 主要功能和用途
132
- 2. 关键类和方法的作用
133
- 3. 重要的依赖和技术特征(如使用了什么框架、算法、设计模式等)
134
- 4. 代码处理的主要数据类型和数据结构
135
- 5. 关键业务逻辑和处理流程
136
- 6. 特殊功能点和亮点特性
137
-
138
- 请用简洁专业的语言描述,突出代码的技术特征和功能特点,以便后续进行相似代码检索。
139
-
140
- 文件路径:{file_path}
141
- 代码内容:
142
- {content}
143
- """
144
- response = model.chat(prompt)
145
- return response
146
-
147
- def get_embedding(self, text: str) -> np.ndarray:
148
- """使用 transformers 模型获取文本的向量表示"""
149
- # 对长文本进行截断
150
- max_length = 512 # 或其他合适的长度
151
- text = ' '.join(text.split()[:max_length])
152
-
153
- # 获取嵌入向量
154
- embedding = self.embedding_model.encode(text,
155
- normalize_embeddings=True, # L2归一化
156
- show_progress_bar=False)
157
- return np.array(embedding, dtype=np.float32)
158
-
159
- def vectorize_file(self, file_path: str, description: str) -> np.ndarray:
160
- """将文件内容和描述向量化"""
161
- try:
162
- # 组合文件信息
163
- combined_text = f"""
164
- 文件路径: {file_path}
165
- 文件描述: {description}
166
- """
167
- return self.get_embedding(combined_text)
168
- except Exception as e:
169
- PrettyOutput.print(f"Error vectorizing file {file_path}: {str(e)}",
170
- output_type=OutputType.ERROR)
171
- return np.zeros(self.vector_dim, dtype=np.float32)
172
-
173
- def process_file(self, file):
174
- """处理单个文件的辅助方法"""
175
- db = self.get_db_connection()
176
- try:
177
- if not self.is_text_file(file):
178
- return None
179
- md5 = hashlib.md5(open(file, "rb").read()).hexdigest()
180
- if db.execute("SELECT path FROM codebase WHERE md5 = ?", (md5,)).fetchone():
181
- return None
182
- description = self.make_description(file)
183
- return (file, md5, description)
184
- finally:
185
- db.close()
186
-
187
- def gen_vector_db_from_sqlite(self):
188
- self.index = faiss.IndexHNSWFlat(self.vector_dim, 16)
189
- self.index.hnsw.efConstruction = 40
190
- self.index.hnsw.efSearch = 16
191
- db = self.get_db_connection()
192
- try:
193
- all_records = db.execute("SELECT path, description FROM codebase").fetchall()
194
- for row in all_records:
195
- file, description = row
196
- PrettyOutput.print(f"正在向量化文件: {file}", output_type=OutputType.INFO)
197
- vector = self.vectorize_file(file, description)
198
- vector = vector.reshape(1, -1)
199
- self.index.add(vector)
200
- faiss.write_index(self.index, self.index_path)
201
- finally:
202
- db.close()
203
-
204
- def generate_codebase(self):
205
- updated =self.clean_db()
206
- db_lock = Lock()
207
- processed_files = [] # 用于跟踪已处理的文件
208
-
209
- def process_and_save(file):
210
- result = self.process_file(file)
211
- if result:
212
- file, md5, description = result
213
- db = self.get_db_connection()
214
- try:
215
- with db_lock:
216
- db.execute("DELETE FROM codebase WHERE path = ?", (file,))
217
- db.execute("INSERT INTO codebase (path, md5, description) VALUES (?, ?, ?)",
218
- (file, md5, description))
219
- db.commit()
220
- PrettyOutput.print(f"索引文件: {file}", output_type=OutputType.INFO)
221
- processed_files.append(file)
222
- finally:
223
- db.close()
224
-
225
- # 使用 ThreadPoolExecutor 并等待所有任务完成
226
- with ThreadPoolExecutor(max_workers=self.thread_count) as executor:
227
- futures = [executor.submit(process_and_save, file) for file in self.git_file_list]
228
- # 等待所有任务完成
229
- concurrent.futures.wait(futures)
230
-
231
- if updated or len(processed_files) > 0:
232
- PrettyOutput.print("有新的文件被删除或添加,正在重新生成向量数据库", output_type=OutputType.INFO)
233
- self.gen_vector_db_from_sqlite()
234
- else:
235
- PrettyOutput.print("没有新的文件被删除或添加,跳过向量数据库生成", output_type=OutputType.INFO)
236
-
237
- PrettyOutput.print(f"成功索引 {len(processed_files)} 个文件", output_type=OutputType.INFO)
238
-
239
- def search_similar(self, query: str, top_k: int = 5) -> List[Tuple[str, float, str]]:
240
- """搜索与查询最相似的文件
241
-
242
- Args:
243
- query: 查询文本
244
- top_k: 返回结果数量
245
-
246
- Returns:
247
- List of (file_path, similarity_score, description) tuples
248
- """
249
- # 获取查询文本的向量表示
250
- query_vector = self.get_embedding(query)
251
- query_vector = query_vector.reshape(1, -1)
252
-
253
- # 搜索最相似的向量
254
- distances, indices = self.index.search(query_vector, top_k)
255
-
256
- # 获取对应的文件信息
257
- db = self.get_db_connection()
258
- try:
259
- results = []
260
- for i, distance in zip(indices[0], distances[0]):
261
- if i == -1: # faiss返回-1表示无效结果
262
- continue
263
-
264
- # 将numpy.int64转换为Python int
265
- offset = int(i)
266
- # 获取文件路径和描述
267
- cursor = db.execute("SELECT path, description FROM codebase LIMIT 1 OFFSET ?", (offset,))
268
- row = cursor.fetchone()
269
- if row:
270
- path, description = row
271
- # 将distance转换为相似度分数(0-1之间)
272
- similarity = 1.0 / (1.0 + float(distance)) # 确保使用Python float
273
- results.append((path, similarity, description))
274
-
275
- return results
276
- finally:
277
- db.close()
278
-
279
- def ask_codebase(self, query: str, top_k: int = 5) -> List[Tuple[str, float, str]]:
280
- """Ask a question about the codebase"""
281
- # 使用搜索函数获取相似文件
282
- results = self.search_similar(query, top_k)
283
- PrettyOutput.print(f"找到的关联文件: ", output_type=OutputType.INFO)
284
- for path, score, _ in results:
285
- PrettyOutput.print(f"文件: {path} 关联度: {score:.3f}", output_type=OutputType.INFO)
286
-
287
- prompt = f"""你是一个代码专家,请根据以下文件信息回答用户的问题:
288
- """
289
- for path, _, _ in results:
290
- content = open(path, "r", encoding="utf-8").read()
291
- prompt += f"""
292
- 文件路径: {path}
293
- 文件内容:
294
- {content}
295
- ========================================
296
- """
297
- prompt += f"""
298
- 用户问题: {query}
299
-
300
- 请用专业的语言回答用户的问题,如果给出的文件内容不足以回答用户的问题,请告诉用户,绝对不要胡编乱造。
301
- """
302
- model = self.platform_registry.create_platform(self.normal_platform)
303
- model.set_model_name(self.normal_model)
304
- response = model.chat(prompt)
305
- return response
306
-
307
-
308
- def main():
309
- parser = argparse.ArgumentParser(description='Codebase management and search tool')
310
- parser.add_argument('--search', type=str, help='Search query to find similar code files')
311
- parser.add_argument('--top-k', type=int, default=5, help='Number of results to return (default: 5)')
312
- parser.add_argument('--ask', type=str, help='Ask a question about the codebase')
313
- args = parser.parse_args()
314
-
315
- current_dir = find_git_root()
316
- codebase = CodeBase(current_dir)
317
-
318
- try:
319
- codebase.generate_codebase()
320
- PrettyOutput.print("\nCodebase generation completed", output_type=OutputType.SUCCESS)
321
- except Exception as e:
322
- PrettyOutput.print(f"Error during codebase generation: {str(e)}", output_type=OutputType.ERROR)
323
-
324
- if args.search:
325
- results = codebase.search_similar(args.search, args.top_k)
326
- if not results:
327
- PrettyOutput.print("No similar files found", output_type=OutputType.WARNING)
328
- return
329
-
330
- PrettyOutput.print("\nSearch Results:", output_type=OutputType.INFO)
331
- for path, score, desc in results:
332
- PrettyOutput.print("\n" + "="*50, output_type=OutputType.INFO)
333
- PrettyOutput.print(f"File: {path}", output_type=OutputType.INFO)
334
- PrettyOutput.print(f"Similarity: {score:.3f}", output_type=OutputType.INFO)
335
- PrettyOutput.print(f"Description: {desc[100:]}", output_type=OutputType.INFO)
336
-
337
- if args.ask:
338
- codebase.ask_codebase(args.ask, args.top_k)
339
-
340
-
341
- if __name__ == "__main__":
342
- exit(main())
@@ -1,9 +0,0 @@
1
- from .registry import ToolRegistry
2
- from jarvis.tools.codebase_qa import CodebaseQATool
3
-
4
- __all__ = [
5
- 'ToolRegistry',
6
- ]
7
-
8
- def register_tools():
9
- register_tool(CodebaseQATool())