Coverage for aipyapp/cli/command/cmd_context.py: 0%

1#!/usr/bin/env python

2# -*- coding: utf-8 -*-

3

4 from rich.console import Console

5 from rich.table import Table

6 from rich.panel import Panel

7 from rich.text import Text

8

9 from .base import CommandMode

10 from .base_parser import ParserCommand

11 from ... import T

12

13 class ContextCommand(ParserCommand):

14 """上下文管理命令"""

15 name = "context"

16 description = T("Manage LLM conversation context")

17 modes = [CommandMode.TASK]

18

19 def add_subcommands(self, subparsers):

20 subparsers.add_parser('show', help=T('Show context'))

21 subparsers.add_parser('clear', help=T('Clear context'))

22 subparsers.add_parser('stats', help=T('Show context stats'))

23 parser = subparsers.add_parser('config', help=T('Show context config'))

24 parser.add_argument('--strategy', choices=['sliding_window', 'importance_filter', 'summary_compression', 'hybrid'], help=T('Set compression strategy'))

25 parser.add_argument('--max-tokens', type=int, help=T('Set max tokens'))

26 parser.add_argument('--max-rounds', type=int, help=T('Set max rounds'))

27 parser.add_argument('--auto-compress', action='store_true', help=T('Set auto compress'))

28

29 def cmd(self, args, ctx):

30 self.cmd_show(args, ctx)

31

32 def cmd_show(self, args, ctx):

33 """显示当前上下文"""

34 messages = ctx.task.client.context_manager.get_messages()

35 console = ctx.console

36

37 if not messages:

38 console.print(T("No conversation history"), style="yellow")

39 return

40

41 table = Table(title=T("Conversation context"))

42 table.add_column(T("Role"), style="cyan")

43 table.add_column(T("Content"), style="white")

44

45 for msg in messages:

46 content = msg.get('content', '')

47 if isinstance(content, str) and len(content) > 100:

48 content = content[:100] + "..."

49 table.add_row(msg.get('role', ''), content)

50

51 console.print(table)

52

53 def cmd_clear(self, args, ctx):

54 """清空上下文"""

55 task = ctx.task

56 console = ctx.console

57

58 task.client.context_manager.clear()

59 console.print(T("Context cleared"), style="green")

60

61 def cmd_stats(self, args, ctx):

62 """显示上下文统计信息"""

63 task = ctx.task

64 console = ctx.console

65

66 stats = task.client.context_manager.get_stats()

67

68 if not stats:

69 console.print(T("Context manager not enabled"), style="yellow")

70 return

71

72 table = Table(title=T("Context stats"))

73 table.add_column(T("Metric"), style="cyan")

74 table.add_column(T("Value"), style="white")

75

76 table.add_row(T("Message count"), str(stats['message_count']))

77 table.add_row(T("Current token"), str(stats['total_tokens']))

78 table.add_row(T("Max tokens"), str(stats['max_tokens']))

79 table.add_row(T("Compression ratio"), f"{stats['compression_ratio']:.2f}")

80

81 console.print(table)

82

83 def cmd_config(self, args, ctx):

84 """显示上下文配置"""

85 if args.strategy or args.max_tokens or args.max_rounds:

86 return self._update_config(args, ctx)

87

88 task = ctx.task

89 console = ctx.console

90 config = task.client.context_manager.config

91

92 table = Table(title=T("Context config"))

93 table.add_column(T("Config item"), style="cyan")

94 table.add_column(T("Value"), style="white")

95

96 table.add_row(T("Strategy"), config.strategy.value)

97 table.add_row(T("Max tokens"), str(config.max_tokens))

98 table.add_row(T("Max rounds"), str(config.max_rounds))

99 table.add_row(T("Auto compress"), str(config.auto_compress))

100 table.add_row(T("Compression ratio"), str(config.compression_ratio))

101 table.add_row(T("Importance threshold"), str(config.importance_threshold))

102 table.add_row(T("Summary max length"), str(config.summary_max_length))

103 table.add_row(T("Preserve system message"), str(config.preserve_system))

104 table.add_row(T("Preserve recent rounds"), str(config.preserve_recent))

105

106 console.print(table)

107

108 def _update_config(self, args, ctx):

109 """更新上下文配置"""

110 task = ctx.task

111 console = ctx.console

112

113 current_config = task.client.context_manager.config

114

115 # 更新配置

116 if args.strategy:

117 if not current_config.set_strategy(args.strategy):

118 console.print(T("Invalid strategy: {}, using default strategy", args.strategy), style="red")

119

120 if args.max_tokens:

121 current_config.max_tokens = args.max_tokens

122

123 if args.max_rounds:

124 current_config.max_rounds = args.max_rounds

125

126 # 应用新配置

127 task.client.context_manager.update_config(current_config)

128 console.print(T("Config updated"), style="green")