Coverage for aipyapp/cli/cli_python.py: 0%

1#!/usr/bin/env python

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

3 import code

4 import builtins

5

6 from rich.console import Console

7 from prompt_toolkit import PromptSession

8 from prompt_toolkit.formatted_text import HTML

9 from prompt_toolkit.auto_suggest import AutoSuggestFromHistory

10 from prompt_toolkit.completion import WordCompleter

11 from prompt_toolkit.lexers import PygmentsLexer

12 from prompt_toolkit.history import FileHistory

13 from pygments.lexers.python import PythonLexer

14

15 from ..aipy import TaskManager

16 from .. import T, __version__

17

18 class PythonCompleter(WordCompleter):

19 def __init__(self, ai):

20 names = ['exit()']

21 names += [name for name in dir(builtins)]

22 names += [f"ai.{attr}" for attr in dir(ai) if not attr.startswith('_')]

23 super().__init__(names, ignore_case=True)

24

25 def main(settings):

26 console = Console(record=True)

27 console.print(f"[bold cyan]🚀 Python use - AIPython ({__version__}) [[green]https://aipy.app[/green]]")

28

29 try:

30 ai = TaskManager(settings, console=console)

31 except Exception as e:

32 console.print_exception(e)

33 return

34

35 update = ai.get_update(True)

36 if update and update.get('has_update'):

37 console.print(f"[bold red]🔔 号外❗ {T('Update available')}: {update.get('latest_version')}")

38

39 if not ai.client_manager:

40 console.print(f"[bold red]{T('No available LLM, please check the configuration file')}")

41 return

42

43 names = ai.client_manager.names

44 console.print(f"{T('Please use ai(task) to enter the task to be processed by AI (enter ai.use(llm) to switch to the following LLM:')}", style="green")

45 console.print(f"[cyan]{T('Default')}: [green]{names['default']}，[cyan]{T('Enabled')}: [yellow]{' '.join(names['enabled'])}")

46

47 interp = code.InteractiveConsole({'ai': ai})

48

49 completer = PythonCompleter(ai)

50 lexer = PygmentsLexer(PythonLexer)

51 auto_suggest = AutoSuggestFromHistory()

52 history = FileHistory(str(settings['config_dir'] / '.history.py'))

53 session = PromptSession(history=history, completer=completer, lexer=lexer, auto_suggest=auto_suggest)

54 while True:

55 try:

56 user_input = session.prompt(HTML('<ansiblue>>> </ansiblue>'))

57 if user_input.strip() in {"exit()", "quit()"}:

58 break

59 interp.push(user_input)

60 except EOFError:

61 console.print("[bold yellow]Exiting...")

62 break

63 except Exception as e:

64 console.print(f"[bold red]Error: {e}")