yaicli 0.0.1__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.
- yaicli-0.0.1.dist-info/METADATA +14 -0
- yaicli-0.0.1.dist-info/RECORD +6 -0
- yaicli-0.0.1.dist-info/WHEEL +4 -0
- yaicli-0.0.1.dist-info/entry_points.txt +2 -0
- yaicli-0.0.1.dist-info/licenses/LICENSE +201 -0
- yaicli.py +405 -0
@@ -0,0 +1,14 @@
|
|
1
|
+
Metadata-Version: 2.4
|
2
|
+
Name: yaicli
|
3
|
+
Version: 0.0.1
|
4
|
+
Summary: A simple CLI tool to interact with LLM
|
5
|
+
License-File: LICENSE
|
6
|
+
Requires-Python: >=3.8
|
7
|
+
Requires-Dist: jmespath>=1.0.1
|
8
|
+
Requires-Dist: prompt-toolkit>=3.0.50
|
9
|
+
Requires-Dist: requests>=2.32.3
|
10
|
+
Requires-Dist: rich>=13.9.4
|
11
|
+
Requires-Dist: typer>=0.15.2
|
12
|
+
Description-Content-Type: text/markdown
|
13
|
+
|
14
|
+
# llmcli
|
@@ -0,0 +1,6 @@
|
|
1
|
+
yaicli.py,sha256=ODlhfiH3uqgcep1WElGCSWv5HIelZGKXeH9EI3qgHrA,14895
|
2
|
+
yaicli-0.0.1.dist-info/METADATA,sha256=CKiylTH_4iI1V5LXKy6kzBAR09p6pKHjvDwC7m33ork,350
|
3
|
+
yaicli-0.0.1.dist-info/WHEEL,sha256=qtCwoSJWgHk21S1Kb4ihdzI2rlJ1ZKaIurTj_ngOhyQ,87
|
4
|
+
yaicli-0.0.1.dist-info/entry_points.txt,sha256=gdduQwAuu_LeDqnDU81Fv3NPmD2tRQ1FffvolIP3S1Q,34
|
5
|
+
yaicli-0.0.1.dist-info/licenses/LICENSE,sha256=xx0jnfkXJvxRnG63LTGOxlggYnIysveWIZ6H3PNdCrQ,11357
|
6
|
+
yaicli-0.0.1.dist-info/RECORD,,
|
@@ -0,0 +1,201 @@
|
|
1
|
+
Apache License
|
2
|
+
Version 2.0, January 2004
|
3
|
+
http://www.apache.org/licenses/
|
4
|
+
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
6
|
+
|
7
|
+
1. Definitions.
|
8
|
+
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
11
|
+
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
13
|
+
the copyright owner that is granting the License.
|
14
|
+
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
16
|
+
other entities that control, are controlled by, or are under common
|
17
|
+
control with that entity. For the purposes of this definition,
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
19
|
+
direction or management of such entity, whether by contract or
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
22
|
+
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
24
|
+
exercising permissions granted by this License.
|
25
|
+
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
27
|
+
including but not limited to software source code, documentation
|
28
|
+
source, and configuration files.
|
29
|
+
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
31
|
+
transformation or translation of a Source form, including but
|
32
|
+
not limited to compiled object code, generated documentation,
|
33
|
+
and conversions to other media types.
|
34
|
+
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
36
|
+
Object form, made available under the License, as indicated by a
|
37
|
+
copyright notice that is included in or attached to the work
|
38
|
+
(an example is provided in the Appendix below).
|
39
|
+
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
46
|
+
the Work and Derivative Works thereof.
|
47
|
+
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
49
|
+
the original version of the Work and any modifications or additions
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
61
|
+
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
64
|
+
subsequently incorporated within the Work.
|
65
|
+
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
72
|
+
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
78
|
+
where such license applies only to those patent claims licensable
|
79
|
+
by such Contributor that are necessarily infringed by their
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
82
|
+
institute patent litigation against any entity (including a
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
85
|
+
or contributory patent infringement, then any patent licenses
|
86
|
+
granted to You under this License for that Work shall terminate
|
87
|
+
as of the date such litigation is filed.
|
88
|
+
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
91
|
+
modifications, and in Source or Object form, provided that You
|
92
|
+
meet the following conditions:
|
93
|
+
|
94
|
+
(a) You must give any other recipients of the Work or
|
95
|
+
Derivative Works a copy of this License; and
|
96
|
+
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
98
|
+
stating that You changed the files; and
|
99
|
+
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
102
|
+
attribution notices from the Source form of the Work,
|
103
|
+
excluding those notices that do not pertain to any part of
|
104
|
+
the Derivative Works; and
|
105
|
+
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
108
|
+
include a readable copy of the attribution notices contained
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
111
|
+
of the following places: within a NOTICE text file distributed
|
112
|
+
as part of the Derivative Works; within the Source form or
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
114
|
+
within a display generated by the Derivative Works, if and
|
115
|
+
wherever such third-party notices normally appear. The contents
|
116
|
+
of the NOTICE file are for informational purposes only and
|
117
|
+
do not modify the License. You may add Your own attribution
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
120
|
+
that such additional attribution notices cannot be construed
|
121
|
+
as modifying the License.
|
122
|
+
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
124
|
+
may provide additional or different license terms and conditions
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
128
|
+
the conditions stated in this License.
|
129
|
+
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
133
|
+
this License, without any additional terms or conditions.
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
135
|
+
the terms of any separate license agreement you may have executed
|
136
|
+
with Licensor regarding such Contributions.
|
137
|
+
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
140
|
+
except as required for reasonable and customary use in describing the
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
142
|
+
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
152
|
+
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
158
|
+
incidental, or consequential damages of any character arising as a
|
159
|
+
result of this License or out of the use or inability to use the
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
162
|
+
other commercial damages or losses), even if such Contributor
|
163
|
+
has been advised of the possibility of such damages.
|
164
|
+
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
168
|
+
or other liability obligations and/or rights consistent with this
|
169
|
+
License. However, in accepting such obligations, You may act only
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
174
|
+
of your accepting any such warranty or additional liability.
|
175
|
+
|
176
|
+
END OF TERMS AND CONDITIONS
|
177
|
+
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
179
|
+
|
180
|
+
To apply the Apache License to your work, attach the following
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
182
|
+
replaced with your own identifying information. (Don't include
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
184
|
+
comment syntax for the file format. We also recommend that a
|
185
|
+
file or class name and description of purpose be included on the
|
186
|
+
same "printed page" as the copyright notice for easier
|
187
|
+
identification within third-party archives.
|
188
|
+
|
189
|
+
Copyright [yyyy] [name of copyright owner]
|
190
|
+
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
192
|
+
you may not use this file except in compliance with the License.
|
193
|
+
You may obtain a copy of the License at
|
194
|
+
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
196
|
+
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
200
|
+
See the License for the specific language governing permissions and
|
201
|
+
limitations under the License.
|
yaicli.py
ADDED
@@ -0,0 +1,405 @@
|
|
1
|
+
import configparser
|
2
|
+
import json
|
3
|
+
import subprocess
|
4
|
+
import time
|
5
|
+
from enum import StrEnum
|
6
|
+
from os import getenv
|
7
|
+
from os.path import basename, pathsep
|
8
|
+
from pathlib import Path
|
9
|
+
from typing import Annotated, Optional
|
10
|
+
|
11
|
+
import jmespath
|
12
|
+
import requests
|
13
|
+
import typer
|
14
|
+
from prompt_toolkit import PromptSession
|
15
|
+
from prompt_toolkit.key_binding import KeyBindings, KeyPressEvent
|
16
|
+
from prompt_toolkit.keys import Keys
|
17
|
+
from rich.console import Console
|
18
|
+
from rich.live import Live
|
19
|
+
from rich.markdown import Markdown
|
20
|
+
from rich.prompt import Confirm
|
21
|
+
|
22
|
+
|
23
|
+
class ModeEnum(StrEnum):
|
24
|
+
CHAT = "chat"
|
25
|
+
EXECUTE = "exec"
|
26
|
+
TEMP = "temp"
|
27
|
+
|
28
|
+
|
29
|
+
class CasePreservingConfigParser(configparser.RawConfigParser):
|
30
|
+
def optionxform(self, optionstr):
|
31
|
+
return optionstr
|
32
|
+
|
33
|
+
|
34
|
+
class ShellAI:
|
35
|
+
# Configuration file path
|
36
|
+
CONFIG_PATH = Path("~/.config/llmcli/config.ini").expanduser()
|
37
|
+
|
38
|
+
# Default configuration template
|
39
|
+
DEFAULT_CONFIG_INI = """[core]
|
40
|
+
BASE_URL=https://api.openai.com/v1
|
41
|
+
API_KEY=
|
42
|
+
MODEL=gpt-4o
|
43
|
+
|
44
|
+
# default run mode, default: temp
|
45
|
+
# chat: interactive chat mode
|
46
|
+
# exec: shell command generation mode
|
47
|
+
# temp: one-shot mode
|
48
|
+
DEFAULT_MODE=temp
|
49
|
+
|
50
|
+
# auto detect shell and os
|
51
|
+
SHELL_NAME=auto
|
52
|
+
OS_NAME=auto
|
53
|
+
|
54
|
+
# if you want to use custom completions path, you can set it here
|
55
|
+
COMPLETION_PATH=/chat/completions
|
56
|
+
# if you want to use custom answer path, you can set it here
|
57
|
+
ANSWER_PATH=choices[0].message.content
|
58
|
+
|
59
|
+
# true: streaming response
|
60
|
+
# false: non-streaming response
|
61
|
+
STREAM=true"""
|
62
|
+
|
63
|
+
def __init__(self, verbose: bool = False):
|
64
|
+
# Initialize terminal components
|
65
|
+
self.verbose = verbose
|
66
|
+
self.console = Console()
|
67
|
+
self.bindings = KeyBindings()
|
68
|
+
self.session = PromptSession(key_bindings=self.bindings)
|
69
|
+
self.current_mode = ModeEnum.CHAT.value
|
70
|
+
self.config = {}
|
71
|
+
|
72
|
+
# Setup key bindings
|
73
|
+
self._setup_key_bindings()
|
74
|
+
|
75
|
+
def _setup_key_bindings(self):
|
76
|
+
"""Setup keyboard shortcuts"""
|
77
|
+
|
78
|
+
@self.bindings.add(Keys.ControlI) # Bind Ctrl+I to switch modes
|
79
|
+
def _(event: KeyPressEvent):
|
80
|
+
self.current_mode = (
|
81
|
+
ModeEnum.CHAT.value
|
82
|
+
if self.current_mode == ModeEnum.EXECUTE.value
|
83
|
+
else ModeEnum.EXECUTE.value
|
84
|
+
)
|
85
|
+
|
86
|
+
def get_os(self):
|
87
|
+
"""Detect operating system"""
|
88
|
+
if self.config.get("OS_NAME") != "auto":
|
89
|
+
return self.config.get("OS_NAME")
|
90
|
+
import platform
|
91
|
+
|
92
|
+
return platform.system()
|
93
|
+
|
94
|
+
def get_shell(self):
|
95
|
+
"""Detect shell"""
|
96
|
+
if self.config.get("SHELL_NAME") != "auto":
|
97
|
+
return self.config.get("SHELL_NAME")
|
98
|
+
import platform
|
99
|
+
|
100
|
+
current_platform = platform.system()
|
101
|
+
if current_platform in ("Windows", "nt"):
|
102
|
+
is_powershell = len(getenv("PSModulePath", "").split(pathsep)) >= 3
|
103
|
+
return "powershell.exe" if is_powershell else "cmd.exe"
|
104
|
+
return basename(getenv("SHELL", "/bin/sh"))
|
105
|
+
|
106
|
+
def get_default_config(self):
|
107
|
+
"""Get default configuration"""
|
108
|
+
config = CasePreservingConfigParser()
|
109
|
+
try:
|
110
|
+
config.read_string(self.DEFAULT_CONFIG_INI)
|
111
|
+
config_dict = {k.upper(): v for k, v in config["core"].items()}
|
112
|
+
config_dict["STREAM"] = str(config_dict.get("STREAM", "true")).lower()
|
113
|
+
return config_dict
|
114
|
+
except configparser.Error as e:
|
115
|
+
self.console.print(f"[red]Error parsing config: {e}[/red]")
|
116
|
+
raise typer.Exit(code=1) from None
|
117
|
+
|
118
|
+
def load_config(self):
|
119
|
+
"""Load LLM API configuration"""
|
120
|
+
if not self.CONFIG_PATH.exists():
|
121
|
+
self.console.print(
|
122
|
+
"[bold yellow]Configuration file not found. Creating default configuration file.[/bold yellow]"
|
123
|
+
)
|
124
|
+
self.CONFIG_PATH.parent.mkdir(parents=True, exist_ok=True)
|
125
|
+
with open(self.CONFIG_PATH, "w") as f:
|
126
|
+
f.write(self.DEFAULT_CONFIG_INI)
|
127
|
+
return self.config
|
128
|
+
config = CasePreservingConfigParser()
|
129
|
+
config.read(self.CONFIG_PATH)
|
130
|
+
self.config = dict(config["core"])
|
131
|
+
self.config["STREAM"] = str(self.config.get("STREAM", "true")).lower()
|
132
|
+
return self.config
|
133
|
+
|
134
|
+
def _call_api(self, url, headers, data):
|
135
|
+
"""Generic API call method"""
|
136
|
+
response = requests.post(url, headers=headers, json=data)
|
137
|
+
response.raise_for_status() # Raise an exception for non-200 status codes
|
138
|
+
return response
|
139
|
+
|
140
|
+
def call_llm_api(self, prompt):
|
141
|
+
"""Call LLM API, return streaming output"""
|
142
|
+
base = self.config.get("BASE_URL", "").rstrip("/")
|
143
|
+
if not base:
|
144
|
+
self.console.print(
|
145
|
+
"[red]Base URL not found. Please set it in the configuration file. Default: https://api.openai.com/v1[/red]"
|
146
|
+
)
|
147
|
+
return
|
148
|
+
COMPLETION_PATH = self.config.get("COMPLETION_PATH", "").lstrip("/")
|
149
|
+
if not COMPLETION_PATH:
|
150
|
+
self.console.print(
|
151
|
+
"[red]Completions path not set. Please set it in the configuration file. Default: `/chat/completions`[/red]"
|
152
|
+
)
|
153
|
+
return
|
154
|
+
url = f"{base}/{COMPLETION_PATH}"
|
155
|
+
headers = {"Authorization": f"Bearer {self.config['API_KEY']}"}
|
156
|
+
data = {
|
157
|
+
"model": self.config["MODEL"],
|
158
|
+
"messages": [{"role": "user", "content": prompt}],
|
159
|
+
"stream": self.config.get("STREAM", "true") == "true",
|
160
|
+
}
|
161
|
+
try:
|
162
|
+
response = self._call_api(url, headers, data)
|
163
|
+
except requests.exceptions.RequestException as e:
|
164
|
+
self.console.print(f"[red]Error calling API: {e}[/red]")
|
165
|
+
return
|
166
|
+
if not response:
|
167
|
+
return
|
168
|
+
|
169
|
+
self.console.print("\n[bold green]Assistant:[/bold green]")
|
170
|
+
full_completion = ""
|
171
|
+
# Streaming response loop
|
172
|
+
with Live(console=self.console) as live:
|
173
|
+
for line in response.iter_lines():
|
174
|
+
if not line:
|
175
|
+
continue
|
176
|
+
decoded_line = line.decode("utf-8")
|
177
|
+
if decoded_line.startswith("data: "):
|
178
|
+
decoded_line = decoded_line[6:]
|
179
|
+
if decoded_line == "[DONE]":
|
180
|
+
break
|
181
|
+
try:
|
182
|
+
json_data = json.loads(decoded_line)
|
183
|
+
content = json_data["choices"][0]["delta"].get("content", "")
|
184
|
+
full_completion += content
|
185
|
+
markdown = Markdown(markup=full_completion)
|
186
|
+
live.update(markdown, refresh=True)
|
187
|
+
except json.JSONDecodeError:
|
188
|
+
self.console.print("[red]Error decoding response JSON[/red]")
|
189
|
+
if self.verbose:
|
190
|
+
self.console.print(f"[red]Error decoding JSON: {decoded_line}[/red]")
|
191
|
+
time.sleep(0.05)
|
192
|
+
|
193
|
+
self.console.print() # Add a newline after the completion
|
194
|
+
|
195
|
+
def get_command_from_llm(self, prompt):
|
196
|
+
"""Request Shell command from LLM"""
|
197
|
+
url = f"{self.config['BASE_URL']}/chat/completions"
|
198
|
+
headers = {"Authorization": f"Bearer {self.config['API_KEY']}"}
|
199
|
+
data = {
|
200
|
+
"model": self.config["MODEL"],
|
201
|
+
"messages": [
|
202
|
+
{
|
203
|
+
"role": "system",
|
204
|
+
"content": "You are a command line assistant, return one Linux/macOS shell commands only, without explanation and triple-backtick code blocks.",
|
205
|
+
},
|
206
|
+
{"role": "user", "content": prompt},
|
207
|
+
],
|
208
|
+
"stream": False, # Always use non-streaming for command generation
|
209
|
+
}
|
210
|
+
|
211
|
+
try:
|
212
|
+
response = self._call_api(url, headers, data)
|
213
|
+
except requests.exceptions.RequestException as e:
|
214
|
+
self.console.print(f"[red]Error calling API: {e}[/red]")
|
215
|
+
return None
|
216
|
+
if not response:
|
217
|
+
return None
|
218
|
+
ANSWER_PATH = self.config.get("ANSWER_PATH", None)
|
219
|
+
if not ANSWER_PATH:
|
220
|
+
ANSWER_PATH = "choices[0].message.content"
|
221
|
+
if self.verbose:
|
222
|
+
self.console.print(
|
223
|
+
"[bold yellow]Answer path not set. Using default: `choices[0].message.content`[/bold yellow]"
|
224
|
+
)
|
225
|
+
content = jmespath.search(ANSWER_PATH, response.json())
|
226
|
+
return content.strip()
|
227
|
+
|
228
|
+
def execute_shell_command(self, command):
|
229
|
+
"""Execute shell command"""
|
230
|
+
self.console.print(f"\n[bold green]Executing command: [/bold green] {command}\n")
|
231
|
+
result = subprocess.run(command, shell=True)
|
232
|
+
if result.returncode != 0:
|
233
|
+
self.console.print(
|
234
|
+
f"\n[bold red]Command failed with return code: {result.returncode}[/bold red]"
|
235
|
+
)
|
236
|
+
|
237
|
+
def get_prompt_tokens(self):
|
238
|
+
"""Get prompt tokens based on current mode"""
|
239
|
+
if self.current_mode == ModeEnum.CHAT.value:
|
240
|
+
qmark = "💬"
|
241
|
+
elif self.current_mode == ModeEnum.EXECUTE.value:
|
242
|
+
qmark = "🚀"
|
243
|
+
else:
|
244
|
+
qmark = ""
|
245
|
+
return [("class:qmark", qmark), ("class:question", " {} ".format(">"))]
|
246
|
+
|
247
|
+
def chat_mode(self, user_input: str):
|
248
|
+
"""Interactive chat mode"""
|
249
|
+
if self.current_mode != ModeEnum.CHAT.value:
|
250
|
+
return self.current_mode
|
251
|
+
|
252
|
+
self.call_llm_api(user_input)
|
253
|
+
return ModeEnum.CHAT.value
|
254
|
+
|
255
|
+
def _filter_command(self, command):
|
256
|
+
"""Filter out unwanted characters from command
|
257
|
+
|
258
|
+
The LLM may return commands in markdown format with code blocks.
|
259
|
+
This method removes markdown formatting from the command.
|
260
|
+
It handles various formats including:
|
261
|
+
- Commands surrounded by ``` (plain code blocks)
|
262
|
+
- Commands with language specifiers like ```bash, ```zsh, etc.
|
263
|
+
- Commands with specific examples like ```ls -al```
|
264
|
+
|
265
|
+
example:
|
266
|
+
```bash\nls -la\n``` ==> ls -al
|
267
|
+
```zsh\nls -la\n``` ==> ls -al
|
268
|
+
```ls -al``` ==> ls -al
|
269
|
+
ls -al ==> ls -al
|
270
|
+
```\ncd /tmp\nls -la\n``` ==> cd /tmp\nls -la
|
271
|
+
```bash\ncd /tmp\nls -la\n``` ==> cd /tmp\nls -la
|
272
|
+
"""
|
273
|
+
if not command or not command.strip():
|
274
|
+
return ""
|
275
|
+
|
276
|
+
# Handle commands that are already without code blocks
|
277
|
+
if "```" not in command:
|
278
|
+
return command.strip()
|
279
|
+
|
280
|
+
# Handle code blocks with or without language specifiers
|
281
|
+
lines = command.strip().split("\n")
|
282
|
+
|
283
|
+
# Check if it's a single-line code block like ```ls -al```
|
284
|
+
if len(lines) == 1 and lines[0].startswith("```") and lines[0].endswith("```"):
|
285
|
+
return lines[0][3:-3].strip()
|
286
|
+
|
287
|
+
# Handle multi-line code blocks
|
288
|
+
if lines[0].startswith("```"):
|
289
|
+
# Remove the opening ``` line (with or without language specifier)
|
290
|
+
content_lines = lines[1:]
|
291
|
+
|
292
|
+
# If the last line is a closing ```, remove it
|
293
|
+
if content_lines and content_lines[-1].strip() == "```":
|
294
|
+
content_lines = content_lines[:-1]
|
295
|
+
|
296
|
+
# Join the remaining lines and strip any extra whitespace
|
297
|
+
return "\n".join(line.strip() for line in content_lines if line.strip())
|
298
|
+
|
299
|
+
def execute_mode(self, user_input: str):
|
300
|
+
"""Execute mode"""
|
301
|
+
if user_input == "" or self.current_mode != ModeEnum.EXECUTE.value:
|
302
|
+
return self.current_mode
|
303
|
+
|
304
|
+
command = self.get_command_from_llm(user_input)
|
305
|
+
command = self._filter_command(command)
|
306
|
+
if not command:
|
307
|
+
self.console.print("[bold red]No command generated[/bold red]")
|
308
|
+
return self.current_mode
|
309
|
+
self.console.print(f"\n[bold magenta]Generated command:[/bold magenta] {command}")
|
310
|
+
confirm = Confirm.ask("Execute this command?")
|
311
|
+
if confirm:
|
312
|
+
self.execute_shell_command(command)
|
313
|
+
return ModeEnum.EXECUTE.value
|
314
|
+
|
315
|
+
def run_repl_loop(self):
|
316
|
+
while True:
|
317
|
+
user_input = self.session.prompt(self.get_prompt_tokens)
|
318
|
+
# Skip empty input
|
319
|
+
if not user_input.strip():
|
320
|
+
continue
|
321
|
+
|
322
|
+
if user_input.lower() in ("exit", "quit"):
|
323
|
+
break
|
324
|
+
|
325
|
+
if self.current_mode == ModeEnum.CHAT.value:
|
326
|
+
self.chat_mode(user_input)
|
327
|
+
elif self.current_mode == ModeEnum.EXECUTE.value:
|
328
|
+
self.execute_mode(user_input)
|
329
|
+
|
330
|
+
self.console.print("[bold green]Exiting...[/bold green]")
|
331
|
+
|
332
|
+
def run_one_shot(self, prompt: str):
|
333
|
+
"""Run one-shot mode with given prompt"""
|
334
|
+
if self.current_mode == ModeEnum.EXECUTE.value:
|
335
|
+
self.execute_mode(prompt) # Execute mode for one-shot prompt
|
336
|
+
else:
|
337
|
+
self.call_llm_api(prompt)
|
338
|
+
|
339
|
+
def run(self, chat=False, shell=False, prompt: Optional[str] = None):
|
340
|
+
"""Run the CLI application"""
|
341
|
+
# Load configuration
|
342
|
+
self.config = self.load_config()
|
343
|
+
if not self.config.get("API_KEY", None):
|
344
|
+
self.console.print(
|
345
|
+
"[red]API key not found. Please set it in the configuration file.[/red]"
|
346
|
+
)
|
347
|
+
return
|
348
|
+
|
349
|
+
# Set initial mode
|
350
|
+
self.current_mode = self.config["DEFAULT_MODE"]
|
351
|
+
|
352
|
+
# Check run mode from command line arguments
|
353
|
+
if all([chat, shell]):
|
354
|
+
self.console.print("[red]Cannot use both --chat and --shell[/red]")
|
355
|
+
return
|
356
|
+
elif chat:
|
357
|
+
self.current_mode = ModeEnum.CHAT.value
|
358
|
+
elif shell:
|
359
|
+
self.current_mode = ModeEnum.EXECUTE.value
|
360
|
+
|
361
|
+
if self.verbose:
|
362
|
+
self.console.print("[bold yellow]Verbose mode enabled[/bold yellow]")
|
363
|
+
self.console.print(f"[bold yellow]Current mode: {self.current_mode}[/bold yellow]")
|
364
|
+
self.console.print(f"[bold yellow]Using model: {self.config['MODEL']}[/bold yellow]")
|
365
|
+
|
366
|
+
if self.current_mode in (ModeEnum.TEMP.value, ModeEnum.EXECUTE.value) and prompt:
|
367
|
+
self.run_one_shot(prompt)
|
368
|
+
elif self.current_mode == ModeEnum.CHAT.value:
|
369
|
+
self.run_repl_loop()
|
370
|
+
|
371
|
+
|
372
|
+
# CLI application setup
|
373
|
+
CONTEXT_SETTINGS = {
|
374
|
+
"help_option_names": ["-h", "--help"],
|
375
|
+
"show_default": True,
|
376
|
+
}
|
377
|
+
|
378
|
+
app = typer.Typer(
|
379
|
+
name="ShellAI",
|
380
|
+
context_settings=CONTEXT_SETTINGS,
|
381
|
+
pretty_exceptions_enable=False,
|
382
|
+
short_help="ShellAI Command Line Tool",
|
383
|
+
no_args_is_help=True,
|
384
|
+
invoke_without_command=True,
|
385
|
+
)
|
386
|
+
|
387
|
+
|
388
|
+
@app.command()
|
389
|
+
def main(
|
390
|
+
prompt: Annotated[str, typer.Argument(show_default=False, help="The prompt send to the LLM")],
|
391
|
+
verbose: Annotated[
|
392
|
+
bool, typer.Option("--verbose", "-V", help="Show verbose information")
|
393
|
+
] = False,
|
394
|
+
chat: Annotated[bool, typer.Option("--chat", "-c", help="Start in chat mode")] = False,
|
395
|
+
shell: Annotated[
|
396
|
+
bool, typer.Option("--shell", "-s", help="Generate and execute shell command")
|
397
|
+
] = False,
|
398
|
+
):
|
399
|
+
"""LLM CLI Tool"""
|
400
|
+
cli = ShellAI()
|
401
|
+
cli.run(chat=chat, shell=shell, prompt=prompt)
|
402
|
+
|
403
|
+
|
404
|
+
if __name__ == "__main__":
|
405
|
+
app()
|