jarvis-ai-assistant 0.1.159__py3-none-any.whl → 0.1.161__py3-none-any.whl

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.

jarvis/__init__.py CHANGED
@@ -1,3 +1,3 @@
1
1
  """Jarvis AI Assistant"""
2
2
 
3
- __version__ = "0.1.159"
3
+ __version__ = "0.1.161"
@@ -7,9 +7,8 @@ from typing import Any, Tuple
7
7
  from yaspin import yaspin
8
8
 
9
9
  from jarvis.jarvis_tools.file_operation import FileOperationTool
10
- from jarvis.jarvis_utils.config import INPUT_WINDOW_REVERSE_SIZE, get_max_input_token_count
11
- from jarvis.jarvis_utils.embedding import get_context_token_count
12
10
  from jarvis.jarvis_utils.output import OutputType, PrettyOutput
11
+ from jarvis.jarvis_utils.utils import is_context_overflow
13
12
 
14
13
 
15
14
  def file_input_handler(user_input: str, agent: Any) -> Tuple[str, bool]:
@@ -86,7 +85,7 @@ def file_input_handler(user_input: str, agent: Any) -> Tuple[str, bool]:
86
85
  spinner.text = "文件读取完成"
87
86
  spinner.ok("✅")
88
87
  prompt = result["stdout"] + "\n" + prompt
89
- if get_context_token_count(prompt) > get_max_input_token_count() - INPUT_WINDOW_REVERSE_SIZE:
88
+ if is_context_overflow(prompt):
90
89
  return old_prompt, False
91
90
 
92
91
  return prompt, False
@@ -94,7 +94,7 @@ def _select_task(tasks: Dict[str, str]) -> str:
94
94
  # 询问是否需要补充信息
95
95
  need_additional = user_confirm("需要为此任务添加补充信息吗?", default=False)
96
96
  if need_additional:
97
- additional_input = get_multiline_input("请输入补充信息(输入空行结束):")
97
+ additional_input = get_multiline_input("请输入补充信息:")
98
98
  if additional_input:
99
99
  selected_task = f"{selected_task}\n\n补充信息:\n{additional_input}"
100
100
  return selected_task
@@ -2,20 +2,19 @@ import re
2
2
  from typing import Dict, Any, Tuple
3
3
  import os
4
4
 
5
- from yaspin import yaspin
5
+ from yaspin import yaspin # type: ignore
6
6
 
7
7
  from jarvis.jarvis_agent.output_handler import OutputHandler
8
8
  from jarvis.jarvis_platform.base import BasePlatform
9
9
  from jarvis.jarvis_platform.registry import PlatformRegistry
10
10
  from jarvis.jarvis_git_utils.git_commiter import GitCommitTool
11
11
  from jarvis.jarvis_tools.file_operation import FileOperationTool
12
- from jarvis.jarvis_utils.config import INPUT_WINDOW_REVERSE_SIZE, get_max_input_token_count, is_confirm_before_apply_patch
13
- from jarvis.jarvis_utils.embedding import get_context_token_count
12
+ from jarvis.jarvis_utils.config import is_confirm_before_apply_patch
14
13
  from jarvis.jarvis_utils.git_utils import get_commits_between, get_latest_commit_hash
15
14
  from jarvis.jarvis_utils.globals import add_read_file_record, has_read_file
16
15
  from jarvis.jarvis_utils.input import get_multiline_input
17
16
  from jarvis.jarvis_utils.output import OutputType, PrettyOutput
18
- from jarvis.jarvis_utils.utils import get_file_line_count, user_confirm, chat_with_files
17
+ from jarvis.jarvis_utils.utils import is_context_overflow, get_file_line_count, user_confirm
19
18
  from jarvis.jarvis_utils.tag import ot, ct
20
19
 
21
20
 
@@ -95,7 +94,7 @@ def add(a, b):
95
94
  - 保持代码风格一致性,遵循项目现有的编码规范
96
95
  - 在修改前仔细分析原代码的格式风格,确保补丁与之完全兼容
97
96
  - 绝不提供完整文件内容,除非是新建文件
98
- - 每个文件的修改是独立的,不能出现"参照xxx文件的修改"这样的描述
97
+ - 每个文件的修改是独立的,不能出现“参照xxx文件的修改”这样的描述
99
98
  - 不要出现未实现的代码,如:TODO
100
99
  """
101
100
 
@@ -211,12 +210,8 @@ def apply_patch(output_str: str, agent: Any) -> str:
211
210
  final_ret += f"# 应用补丁:\n```diff\n{diff}\n```"
212
211
 
213
212
  # 修改后的提示逻辑
214
- addon_prompt = "1. 请确认补丁是否已正确应用\n"
215
- addon_prompt += "2. 检查修改后的代码是否符合预期\n"
216
- addon_prompt += "3. 如果确认无误,请继续进行下一步修改\n"
217
- addon_prompt += "4. 如果发现问题,请立即开始修复\n"
218
- addon_prompt += f"如果用户的需求已经完成,请终止,不要输出新的 {ot('PATCH')},不要实现任何超出用户需求外的内容\n"
219
- addon_prompt += "如果有任何信息不清楚,调用工具获取信息\n"
213
+ addon_prompt = f"如果用户的需求未完成,请继续生成补丁,如果已经完成,请终止,不要输出新的 {ot('PATCH')},不要实现任何超出用户需求外的内容\n"
214
+ addon_prompt += "如果有任何信息不明确,调用工具获取信息\n"
220
215
  addon_prompt += "每次响应必须且只能包含一个操作\n"
221
216
 
222
217
  agent.set_addon_prompt(addon_prompt)
@@ -348,14 +343,36 @@ def handle_commit_workflow() -> bool:
348
343
  """Handle the git commit workflow and return the commit details.
349
344
 
350
345
  Returns:
351
- tuple[bool, str, str]: (continue_execution, commit_id, commit_message)
346
+ bool: 提交是否成功
352
347
  """
353
348
  if is_confirm_before_apply_patch() and not user_confirm("是否要提交代码?", default=True):
354
349
  revert_change()
355
350
  return False
356
- git_commiter = GitCommitTool()
357
- commit_result = git_commiter.execute({})
358
- return commit_result["success"]
351
+
352
+ import subprocess
353
+ try:
354
+ # 获取当前分支的提交总数
355
+ commit_count = subprocess.run(
356
+ ['git', 'rev-list', '--count', 'HEAD'],
357
+ capture_output=True,
358
+ text=True
359
+ )
360
+ if commit_count.returncode != 0:
361
+ return False
362
+
363
+ commit_count = int(commit_count.stdout.strip())
364
+
365
+ # 暂存所有修改
366
+ subprocess.run(['git', 'add', '.'], check=True)
367
+
368
+ # 提交变更
369
+ subprocess.run(
370
+ ['git', 'commit', '-m', f'CheckPoint #{commit_count + 1}'],
371
+ check=True
372
+ )
373
+ return True
374
+ except subprocess.CalledProcessError as e:
375
+ return False
359
376
 
360
377
 
361
378
  def handle_code_operation(filepath: str, patch_content: str) -> bool:
@@ -377,7 +394,8 @@ def handle_small_code_operation(filepath: str, patch_content: str) -> bool:
377
394
  try:
378
395
  model = PlatformRegistry().get_normal_platform()
379
396
  file_content = FileOperationTool().execute({"operation":"read", "files":[{"path":filepath}]})["stdout"]
380
- model.set_suppress_output(True)
397
+
398
+ model.set_suppress_output(False)
381
399
 
382
400
  prompt = f"""
383
401
  # 代码合并专家指南
@@ -407,6 +425,7 @@ def handle_small_code_operation(filepath: str, patch_content: str) -> bool:
407
425
  {ot("MERGED_CODE")}
408
426
  [合并后的完整代码,包括所有空行和缩进]
409
427
  {ct("MERGED_CODE")}
428
+
410
429
  # 原始代码
411
430
  {file_content}
412
431
  """
@@ -418,7 +437,8 @@ def handle_small_code_operation(filepath: str, patch_content: str) -> bool:
418
437
  finished = False
419
438
  while count > 0:
420
439
  count -= 1
421
- response = model.chat_until_success(prompt).splitlines()
440
+ with spinner.hidden():
441
+ response = model.chat_until_success(prompt).splitlines()
422
442
  try:
423
443
  start_line = response.index(ot("MERGED_CODE")) + 1
424
444
  try:
@@ -466,18 +486,23 @@ def handle_small_code_operation(filepath: str, patch_content: str) -> bool:
466
486
  return False
467
487
 
468
488
 
489
+
469
490
  def handle_large_code_operation(filepath: str, patch_content: str, model: BasePlatform) -> bool:
470
491
  """处理大型代码文件的补丁操作,使用差异化补丁格式"""
471
492
  with yaspin(text=f"正在处理文件 {filepath}...", color="cyan") as spinner:
472
493
  try:
473
494
  file_content = FileOperationTool().execute({"operation":"read", "files":[{"path":filepath}]})["stdout"]
474
-
475
- # 检查是否需要特殊处理大文件
476
- need_special_handling = get_context_token_count(file_content) > get_max_input_token_count() - INPUT_WINDOW_REVERSE_SIZE
477
-
478
- model.set_suppress_output(True)
495
+ need_upload_file = is_context_overflow(file_content)
496
+ upload_success = False
497
+ # 读取原始文件内容
498
+ with spinner.hidden():
499
+ if need_upload_file and model.upload_files([filepath]):
500
+ upload_success = True
479
501
 
480
- prompt = f"""
502
+
503
+ model.set_suppress_output(False)
504
+
505
+ main_prompt = f"""
481
506
  # 代码补丁生成专家指南
482
507
 
483
508
  ## 任务描述
@@ -487,8 +512,7 @@ def handle_large_code_operation(filepath: str, patch_content: str, model: BasePl
487
512
  ```
488
513
  {patch_content}
489
514
  ```
490
- """
491
- suffix_prompt = """
515
+
492
516
  ## 补丁生成要求
493
517
  1. **精确性**:严格按照补丁的意图修改代码
494
518
  2. **格式一致性**:严格保持原始代码的格式风格
@@ -523,77 +547,69 @@ def handle_large_code_operation(filepath: str, patch_content: str, model: BasePl
523
547
  <<<<<< REPLACE
524
548
  {ct("DIFF")}
525
549
  """
526
- if need_special_handling:
527
- # 尝试上传文件
528
- upload_success = False
529
- with spinner.hidden():
530
- if model.upload_files([filepath]):
531
- upload_success = True
532
-
533
- if upload_success:
534
- response = model.chat_until_success(prompt + suffix_prompt)
550
+
551
+ for _ in range(3):
552
+ file_prompt = ""
553
+ if not need_upload_file:
554
+ file_prompt = f"""
555
+ # 原始代码
556
+ {file_content}
557
+ """
558
+ with spinner.hidden():
559
+ response = model.chat_until_success(main_prompt + file_prompt)
535
560
  else:
536
- # 使用chat_with_files生成补丁
537
- response = chat_with_files(
538
- [filepath],
539
- model,
540
- prompt,
541
- suffix_prompt
542
- )
543
- else:
544
- # 上下文足够,直接在prompt中包含文件内容
545
- prompt += f"""
546
- # 原始文件内容
547
- ```
548
- {file_content}
549
- ```
550
- """
551
- response = model.chat_until_success(prompt + suffix_prompt)
552
-
553
- # 解析差异化补丁
554
- diff_blocks = re.finditer(ot("DIFF")+r'\s*>{4,} SEARCH\n?(.*?)\n?={4,}\n?(.*?)\s*<{4,} REPLACE\n?'+ct("DIFF"),
555
- response, re.DOTALL)
556
-
557
- # 读取原始文件内容
558
- with open(filepath, 'r', encoding='utf-8', errors="ignore") as f:
559
- file_content = f.read()
560
-
561
- # 应用所有差异化补丁
562
- modified_content = file_content
563
- patch_count = 0
564
- success = True
565
- for match in diff_blocks:
566
- search_text = match.group(1).strip()
567
- replace_text = match.group(2).strip()
568
- patch_count += 1
569
- # 检查搜索文本是否存在于文件中
570
- if search_text in modified_content:
571
- # 如果有多处,报错
572
- if modified_content.count(search_text) > 1:
573
- prompt = f"补丁 #{patch_count} 应用失败:找到多个匹配的代码段"
574
- spinner.write(f"❌ 补丁 #{patch_count} 应用失败:找到多个匹配的代码段")
561
+ if upload_success:
562
+ with spinner.hidden():
563
+ response = model.chat_until_success(main_prompt)
564
+ else:
565
+ with spinner.hidden():
566
+ response = model.chat_big_content(file_content, main_prompt)
567
+
568
+ # 解析差异化补丁
569
+ diff_blocks = re.finditer(ot("DIFF")+r'\s*>{4,} SEARCH\n?(.*?)\n?={4,}\n?(.*?)\s*<{4,} REPLACE\n?'+ct("DIFF"),
570
+ response, re.DOTALL)
571
+
572
+ # 读取原始文件内容
573
+ with open(filepath, 'r', encoding='utf-8', errors="ignore") as f:
574
+ file_content = f.read()
575
+
576
+ # 应用所有差异化补丁
577
+ modified_content = file_content
578
+ patch_count = 0
579
+ success = True
580
+ for match in diff_blocks:
581
+ search_text = match.group(1).strip()
582
+ replace_text = match.group(2).strip()
583
+ patch_count += 1
584
+ # 检查搜索文本是否存在于文件中
585
+ if search_text in modified_content:
586
+ # 如果有多处,报错
587
+ if modified_content.count(search_text) > 1:
588
+ spinner.write(f"❌ 补丁 #{patch_count} 应用失败:找到多个匹配的代码段")
589
+ success = False
590
+ break
591
+ # 应用替换
592
+ modified_content = modified_content.replace(
593
+ search_text, replace_text)
594
+ spinner.write(f"✅ 补丁 #{patch_count} 应用成功")
595
+ else:
596
+ spinner.write(f"❌ 补丁 #{patch_count} 应用失败:无法找到匹配的代码段")
575
597
  success = False
576
598
  break
577
- # 应用替换
578
- modified_content = modified_content.replace(
579
- search_text, replace_text)
580
- spinner.write(f"✅ 补丁 #{patch_count} 应用成功")
581
- else:
582
- spinner.write(f"❌ 补丁 #{patch_count} 应用失败:无法找到匹配的代码段")
583
- prompt = f"补丁 #{patch_count} 应用失败:无法找到匹配的代码段"
584
- success = False
585
- break
586
- if not success:
587
- revert_file(filepath)
588
- return False
599
+ if not success:
600
+ revert_file(filepath)
601
+ continue
589
602
 
590
- # 写入修改后的内容
591
- with open(filepath, 'w', encoding='utf-8', errors="ignore") as f:
592
- f.write(modified_content)
603
+ # 写入修改后的内容
604
+ with open(filepath, 'w', encoding='utf-8', errors="ignore") as f:
605
+ f.write(modified_content)
593
606
 
594
- spinner.text = f"文件 {filepath} 修改完成,应用了 {patch_count} 个补丁"
595
- spinner.ok("✅")
596
- return True
607
+ spinner.text = f"文件 {filepath} 修改完成,应用了 {patch_count} 个补丁"
608
+ spinner.ok("✅")
609
+ return True
610
+ spinner.text = f"文件 {filepath} 修改失败"
611
+ spinner.fail("❌")
612
+ return False
597
613
 
598
614
  except Exception as e:
599
615
  spinner.text = f"文件修改失败: {str(e)}"
@@ -7,7 +7,7 @@ import os
7
7
  import sys
8
8
  import subprocess
9
9
  import argparse
10
- from typing import Optional, List, Tuple
10
+ from typing import Any, Dict, Optional, List, Tuple
11
11
 
12
12
  # 忽略yaspin的类型检查
13
13
  from yaspin import yaspin # type: ignore
@@ -243,6 +243,83 @@ class CodeAgent:
243
243
  """
244
244
  return self.root_dir
245
245
 
246
+ def get_loc_stats(self) -> str:
247
+ """使用loc命令获取当前目录的代码统计信息
248
+
249
+ 返回:
250
+ str: loc命令输出的原始字符串,失败时返回空字符串
251
+ """
252
+ try:
253
+ result = subprocess.run(
254
+ ['loc'],
255
+ cwd=self.root_dir,
256
+ capture_output=True,
257
+ text=True
258
+ )
259
+ return result.stdout if result.returncode == 0 else ""
260
+ except FileNotFoundError:
261
+ return ""
262
+
263
+ def get_recent_commits_with_files(self) -> List[Dict[str, Any]]:
264
+ """获取最近5次提交的commit信息和文件清单
265
+
266
+ 返回:
267
+ List[Dict[str, Any]]: 包含commit信息和文件清单的字典列表,格式为:
268
+ [
269
+ {
270
+ 'hash': 提交hash,
271
+ 'message': 提交信息,
272
+ 'author': 作者,
273
+ 'date': 提交日期,
274
+ 'files': [修改的文件列表] (最多50个文件)
275
+ },
276
+ ...
277
+ ]
278
+ 失败时返回空列表
279
+ """
280
+ try:
281
+ # 获取最近5次提交的基本信息
282
+ result = subprocess.run(
283
+ ['git', 'log', '-5', '--pretty=format:%H%n%s%n%an%n%ad'],
284
+ cwd=self.root_dir,
285
+ capture_output=True,
286
+ text=True
287
+ )
288
+ if result.returncode != 0:
289
+ return []
290
+
291
+ # 解析提交信息
292
+ commits = []
293
+ lines = result.stdout.splitlines()
294
+ for i in range(0, len(lines), 4):
295
+ if i + 3 >= len(lines):
296
+ break
297
+ commit = {
298
+ 'hash': lines[i],
299
+ 'message': lines[i+1],
300
+ 'author': lines[i+2],
301
+ 'date': lines[i+3],
302
+ 'files': []
303
+ }
304
+ commits.append(commit)
305
+
306
+ # 获取每个提交的文件修改清单
307
+ for commit in commits:
308
+ files_result = subprocess.run(
309
+ ['git', 'show', '--name-only', '--pretty=format:', commit['hash']],
310
+ cwd=self.root_dir,
311
+ capture_output=True,
312
+ text=True
313
+ )
314
+ if files_result.returncode == 0:
315
+ files = list(set(filter(None, files_result.stdout.splitlines())))
316
+ commit['files'] = files[:50] # 限制最多50个文件
317
+
318
+ return commits
319
+
320
+ except subprocess.CalledProcessError:
321
+ return []
322
+
246
323
  def _init_env(self) -> None:
247
324
  """初始化环境"""
248
325
  with yaspin(text="正在初始化环境...", color="cyan") as spinner:
@@ -261,8 +338,29 @@ class CodeAgent:
261
338
  if has_uncommitted_changes():
262
339
  PrettyOutput.print("检测到未提交的修改,是否要提交?", OutputType.WARNING)
263
340
  if user_confirm("是否要提交?", True):
264
- git_commiter = GitCommitTool()
265
- git_commiter.execute({})
341
+ import subprocess
342
+ try:
343
+ # 获取当前分支的提交总数
344
+ commit_count = subprocess.run(
345
+ ['git', 'rev-list', '--count', 'HEAD'],
346
+ capture_output=True,
347
+ text=True
348
+ )
349
+ if commit_count.returncode != 0:
350
+ return
351
+
352
+ commit_count = int(commit_count.stdout.strip())
353
+
354
+ # 暂存所有修改
355
+ subprocess.run(['git', 'add', '.'], check=True)
356
+
357
+ # 提交变更
358
+ subprocess.run(
359
+ ['git', 'commit', '-m', f'CheckPoint #{commit_count + 1}'],
360
+ check=True
361
+ )
362
+ except subprocess.CalledProcessError as e:
363
+ PrettyOutput.print(f"提交失败: {str(e)}", OutputType.ERROR)
266
364
 
267
365
  def _show_commit_history(
268
366
  self,
@@ -301,17 +399,14 @@ class CodeAgent:
301
399
  ) -> None:
302
400
  """处理提交确认和可能的重置"""
303
401
  if commits and user_confirm("是否接受以上提交记录?", True):
304
- if len(commits) > 1 and user_confirm(
305
- "是否要合并为一个更清晰的提交记录?", True
306
- ):
307
- subprocess.run(
308
- ["git", "reset", "--mixed", str(start_commit)],
309
- stdout=subprocess.DEVNULL,
310
- stderr=subprocess.DEVNULL,
311
- check=True
312
- )
313
- git_commiter = GitCommitTool()
314
- git_commiter.execute({})
402
+ subprocess.run(
403
+ ["git", "reset", "--mixed", str(start_commit)],
404
+ stdout=subprocess.DEVNULL,
405
+ stderr=subprocess.DEVNULL,
406
+ check=True
407
+ )
408
+ git_commiter = GitCommitTool()
409
+ git_commiter.execute({})
315
410
  elif start_commit:
316
411
  os.system(f"git reset --hard {str(start_commit)}") # 确保转换为字符串
317
412
  PrettyOutput.print("已重置到初始提交", OutputType.INFO)
@@ -329,8 +424,24 @@ class CodeAgent:
329
424
  self._init_env()
330
425
  start_commit = get_latest_commit_hash()
331
426
 
427
+ # 获取项目统计信息并附加到用户输入
428
+ loc_stats = self.get_loc_stats()
429
+ commits_info = self.get_recent_commits_with_files()
430
+
431
+ project_info = []
432
+ if loc_stats:
433
+ project_info.append(f"代码统计:\n{loc_stats}")
434
+ if commits_info:
435
+ commits_str = "\n".join(
436
+ f"提交 {i+1}: {commit['hash'][:7]} - {commit['message']} ({len(commit['files'])}个文件)"
437
+ for i, commit in enumerate(commits_info)
438
+ )
439
+ project_info.append(f"最近提交:\n{commits_str}")
440
+
441
+ enhanced_input = f"{user_input}\n\n项目概况:\n" + "\n\n".join(project_info) if project_info else user_input
442
+
332
443
  try:
333
- self.agent.run(user_input)
444
+ self.agent.run(enhanced_input)
334
445
  except RuntimeError as e:
335
446
  PrettyOutput.print(f"执行失败: {str(e)}", OutputType.WARNING)
336
447
  return str(e)
@@ -10,10 +10,8 @@ from jarvis.jarvis_tools.read_code import ReadCodeTool
10
10
  from jarvis.jarvis_tools.registry import ToolRegistry
11
11
  from jarvis.jarvis_agent import Agent
12
12
 
13
- from jarvis.jarvis_utils.config import INPUT_WINDOW_REVERSE_SIZE, get_max_input_token_count
14
- from jarvis.jarvis_utils.embedding import get_context_token_count
15
13
  from jarvis.jarvis_utils.output import OutputType, PrettyOutput
16
- from jarvis.jarvis_utils.utils import init_env, chat_with_files
14
+ from jarvis.jarvis_utils.utils import init_env, is_context_overflow
17
15
  from jarvis.jarvis_utils.tag import ot, ct
18
16
  from jarvis.jarvis_code_analysis.checklists.loader import get_language_checklist
19
17
 
@@ -587,28 +585,27 @@ class CodeReviewTool:
587
585
  temp_file.flush()
588
586
 
589
587
  try:
590
- # 检查文件大小
591
- is_large_file = get_context_token_count(diff_output) > get_max_input_token_count() - INPUT_WINDOW_REVERSE_SIZE
588
+ upload_success = False
589
+ # Check if content is too large
590
+ is_large_content = is_context_overflow(diff_output)
592
591
 
593
- if is_large_file:
594
- # 文件较大,尝试上传
595
- upload_success = False
596
- with yaspin(text="正在上传代码差异文件...", color="cyan") as spinner:
597
- if agent.model and hasattr(agent.model, 'upload_files'):
598
- upload_success = agent.model.upload_files([temp_file_path])
599
- if upload_success:
600
- spinner.ok("✅")
601
- PrettyOutput.print(f"已成功上传代码差异文件", OutputType.SUCCESS)
602
- else:
603
- spinner.fail("❌")
604
- PrettyOutput.print(f"文件上传失败,将使用chat_with_files处理", OutputType.WARNING)
592
+ # Upload the file to the agent's model
593
+ with yaspin(text="正在上传代码差异文件...", color="cyan") as spinner:
594
+ if is_large_content and agent.model and hasattr(agent.model, 'upload_files'):
595
+ upload_success = agent.model.upload_files([temp_file_path])
596
+ if upload_success:
597
+ spinner.ok("✅")
598
+ PrettyOutput.print(f"已成功上传代码差异文件", OutputType.SUCCESS)
605
599
  else:
606
600
  spinner.fail("❌")
607
- PrettyOutput.print(f"模型不支持文件上传,将使用chat_with_files处理", OutputType.WARNING)
608
-
609
- if upload_success:
610
- # 文件上传成功,使用上传的文件
611
- complete_prompt = user_prompt + f"""
601
+ PrettyOutput.print(f"上传代码差异文件失败,将使用分块处理", OutputType.WARNING)
602
+ else:
603
+ upload_success = False
604
+
605
+ # Prepare the prompt based on upload status
606
+ if upload_success:
607
+ # When file is uploaded, reference it in the prompt
608
+ complete_prompt = user_prompt + f"""
612
609
 
613
610
  我已上传了一个包含代码差异的文件。该文件包含:
614
611
  - 审查类型: {review_type}
@@ -616,20 +613,17 @@ class CodeReviewTool:
616
613
  - 检测到的编程语言: {', '.join(detected_languages) if detected_languages else '未检测到特定语言'}
617
614
 
618
615
  请基于上传的代码差异文件进行全面审查,并生成详细的代码审查报告。"""
619
- result = agent.run(complete_prompt)
620
- else:
621
- # 文件上传失败,使用chat_with_files
622
- PrettyOutput.print("使用chat_with_files处理大文件...", OutputType.INFO)
623
- result = chat_with_files(
624
- [temp_file_path],
625
- agent.model,
626
- user_prompt,
627
- "请基于以上代码差异进行全面审查,并生成详细的代码审查报告。"
628
- )
629
- else:
630
- # 文件较小,直接包含在prompt中
631
- complete_prompt = user_prompt + "\n\n代码差异内容:\n```diff\n" + diff_output + "\n```"
616
+ # Run the agent with the prompt
632
617
  result = agent.run(complete_prompt)
618
+ else:
619
+ # If upload failed or not needed, handle based on context size
620
+ if is_large_content and agent.model and hasattr(agent.model, 'chat_big_content'):
621
+ # Use chat_big_content for large content when upload fails
622
+ result = agent.model.chat_big_content(diff_output, user_prompt)
623
+ else:
624
+ # Include the diff directly in the prompt for smaller content
625
+ complete_prompt = user_prompt + "\n\n代码差异内容:\n```diff\n" + diff_output + "\n```"
626
+ result = agent.run(complete_prompt)
633
627
  finally:
634
628
  # Clean up the temporary file
635
629
  if os.path.exists(temp_file_path):