aibash-wx 0.1.0__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.
@@ -0,0 +1,22 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2024 github/W1412X
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
22
+
@@ -0,0 +1,239 @@
1
+ Metadata-Version: 2.4
2
+ Name: aibash-wx
3
+ Version: 0.1.0
4
+ Summary: AI-powered shell command generator
5
+ Author: github/W1412X
6
+ License: MIT
7
+ Project-URL: Homepage, https://github.com/W1412X/aibash
8
+ Project-URL: Repository, https://github.com/W1412X/aibash
9
+ Keywords: ai,bash,shell,command,generator
10
+ Classifier: Development Status :: 3 - Alpha
11
+ Classifier: Intended Audience :: Developers
12
+ Classifier: Topic :: Utilities
13
+ Classifier: License :: OSI Approved :: MIT License
14
+ Classifier: Programming Language :: Python :: 3
15
+ Classifier: Programming Language :: Python :: 3.7
16
+ Classifier: Programming Language :: Python :: 3.8
17
+ Classifier: Programming Language :: Python :: 3.9
18
+ Classifier: Programming Language :: Python :: 3.10
19
+ Classifier: Programming Language :: Python :: 3.11
20
+ Classifier: Operating System :: OS Independent
21
+ Requires-Python: >=3.7
22
+ Description-Content-Type: text/markdown
23
+ License-File: LICENSE
24
+ Requires-Dist: pyyaml>=5.4.1
25
+ Requires-Dist: requests>=2.25.1
26
+ Requires-Dist: urllib3>=1.26.0
27
+ Dynamic: license-file
28
+
29
+ # AIBash
30
+
31
+ AI 驱动的 Shell 命令生成工具
32
+
33
+ ## 简介
34
+
35
+ AIBash 是一个智能命令行工具,能够根据自然语言描述生成对应的 Shell 命令。支持 OpenAI API 和本地 Ollama 模型。
36
+
37
+ **注意**: 命令行内的所有提示信息均为英文,以避免字符编码问题。文档提供中英文两种版本。
38
+
39
+ ## 功能特性
40
+
41
+ - 🤖 **AI 命令生成**: 根据自然语言描述生成 Shell 命令
42
+ - 🔄 **交互式选择**: 支持执行、修改或放弃生成的命令
43
+ - 📝 **历史记录**: 保存命令执行历史和输出,提供上下文支持
44
+ - ⚙️ **灵活配置**: 支持多种配置选项(模型、密钥、系统信息等)
45
+ - 🌐 **多平台支持**: 支持 macOS、Windows、Linux
46
+ - 🔌 **多模型支持**: 支持 OpenAI API 和 Ollama 本地模型
47
+
48
+ ## 安装
49
+
50
+ ### 从源码安装
51
+
52
+ ```bash
53
+ git clone https://github.com/W1412X/aibash.git
54
+ cd aibash
55
+ pip install -e .
56
+ ```
57
+
58
+ ### 使用 pip 安装
59
+
60
+ ```bash
61
+ pip install aibash
62
+ ```
63
+
64
+ ## 快速开始
65
+
66
+ ### 1. 配置
67
+
68
+ 首次使用前需要配置模型连接信息。配置文件位于 `~/.aibash/config.yaml`。
69
+
70
+ #### OpenAI API 配置示例
71
+
72
+ ```yaml
73
+ model:
74
+ provider: openai
75
+ api_base: https://api.openai.com/v1
76
+ api_key: your-api-key-here
77
+ model_name: gpt-3.5-turbo
78
+
79
+ history:
80
+ enabled: true
81
+ max_records: 50
82
+ include_output: true
83
+
84
+ system_info: "Linux 5.15.0 (x86_64)"
85
+ use_default_prompt: true
86
+ ```
87
+
88
+ #### Ollama 配置示例
89
+
90
+ ```yaml
91
+ model:
92
+ provider: ollama
93
+ api_base: http://localhost:11434
94
+ api_key: "" # Ollama 不需要密钥
95
+ model_name: llama2
96
+
97
+ history:
98
+ enabled: true
99
+ max_records: 50
100
+ include_output: true
101
+
102
+ system_info: "Linux 5.15.0 (x86_64)"
103
+ use_default_prompt: true
104
+ ```
105
+
106
+ ### 2. 使用
107
+
108
+ ```bash
109
+ # 基本用法
110
+ aibash -l "列出当前目录下的所有文件"
111
+
112
+ # 指定配置文件
113
+ aibash --config /path/to/config.yaml -l "查找包含test的文件"
114
+
115
+ # 查看帮助
116
+ aibash -h
117
+
118
+ # 初始化配置(首次使用)
119
+ aibash --init
120
+
121
+ # 查看命令历史
122
+ aibash --history
123
+
124
+ # 清空命令历史
125
+ aibash --clear-history
126
+
127
+ # 测试 AI 连接
128
+ aibash --test
129
+ ```
130
+
131
+ ## 命令行选项
132
+
133
+ - `-l, --lang QUERY`: 自然语言描述,用于生成 shell 命令
134
+ - `--config PATH`: 指定配置文件路径(默认: ~/.aibash/config.yaml)
135
+ - `--init`: 交互式初始化配置文件
136
+ - `--history`: 查看命令执行历史
137
+ - `--clear-history`: 清空命令执行历史
138
+ - `--test`: 测试 AI 连接
139
+ - `-h, --help`: 显示帮助信息
140
+ - `-v, --version`: 显示版本信息
141
+
142
+ 生成命令后,你可以选择:
143
+
144
+ - `[e]` 执行命令 - 直接执行生成的命令
145
+ - `[c]` 复制到剪贴板 - 将命令复制到剪贴板
146
+ - `[m]` 修改命令 - 修改命令后再执行
147
+ - `[s]` 跳过/放弃 - 不执行命令
148
+ - `[h]` 显示帮助 - 显示帮助信息
149
+
150
+ ## 配置说明
151
+
152
+ ### 模型配置
153
+
154
+ - `provider`: 模型提供商 (`openai` 或 `ollama`)
155
+ - `api_base`: API 基础 URL
156
+ - `api_key`: API 密钥(Ollama 可为空)
157
+ - `model_name`: 模型名称
158
+
159
+ ### 历史记录配置
160
+
161
+ - `enabled`: 是否启用历史记录
162
+ - `max_records`: 最大记录数
163
+ - `include_output`: 是否包含命令输出
164
+ - `history_file`: 历史记录文件路径(自动设置)
165
+
166
+ ### 其他配置
167
+
168
+ - `system_info`: 系统信息(用于生成更准确的命令)
169
+ - `custom_prompt`: 自定义 prompt 模板
170
+ - `use_default_prompt`: 是否使用默认 prompt
171
+
172
+ ## 自定义 Prompt
173
+
174
+ 你可以自定义 prompt 模板来更好地控制 AI 的行为。在配置文件中设置 `custom_prompt`,并使用以下占位符:
175
+
176
+ - `{system_info}`: 系统信息
177
+ - `{history_context}`: 历史上下文
178
+ - `{user_query}`: 用户查询
179
+
180
+ 示例:
181
+
182
+ ```yaml
183
+ custom_prompt: |
184
+ 你是一个专业的命令行助手。
185
+ 系统: {system_info}
186
+ {history_context}
187
+ 用户需求: {user_query}
188
+ 请生成对应的shell命令:
189
+ use_default_prompt: false
190
+ ```
191
+
192
+ ## 项目结构
193
+
194
+ ```
195
+ aibash/
196
+ ├── aibash/
197
+ │ ├── __init__.py
198
+ │ ├── config.py # 配置管理
199
+ │ ├── ai_client.py # AI 模型客户端
200
+ │ ├── history.py # 历史记录管理
201
+ │ ├── interactive.py # 交互式选择
202
+ │ ├── prompt.py # Prompt 管理
203
+ │ └── main.py # 主程序入口
204
+ ├── setup.py
205
+ ├── requirements.txt
206
+ └── README.md
207
+ ```
208
+
209
+ ## 开发
210
+
211
+ ### 运行测试
212
+
213
+ ```bash
214
+ python -m aibash.main -l "测试命令"
215
+ ```
216
+
217
+ ### 构建分发包
218
+
219
+ ```bash
220
+ python setup.py sdist bdist_wheel
221
+ ```
222
+
223
+ ## 文档
224
+
225
+ - [中文文档](README.md) - 本文档
226
+ - [English Documentation](README_EN.md) - English version
227
+
228
+ ## 许可证
229
+
230
+ MIT License
231
+
232
+ ## 作者
233
+
234
+ github/W1412X
235
+
236
+ ## 贡献
237
+
238
+ 欢迎提交 Issue 和 Pull Request!
239
+
@@ -0,0 +1,211 @@
1
+ # AIBash
2
+
3
+ AI 驱动的 Shell 命令生成工具
4
+
5
+ ## 简介
6
+
7
+ AIBash 是一个智能命令行工具,能够根据自然语言描述生成对应的 Shell 命令。支持 OpenAI API 和本地 Ollama 模型。
8
+
9
+ **注意**: 命令行内的所有提示信息均为英文,以避免字符编码问题。文档提供中英文两种版本。
10
+
11
+ ## 功能特性
12
+
13
+ - 🤖 **AI 命令生成**: 根据自然语言描述生成 Shell 命令
14
+ - 🔄 **交互式选择**: 支持执行、修改或放弃生成的命令
15
+ - 📝 **历史记录**: 保存命令执行历史和输出,提供上下文支持
16
+ - ⚙️ **灵活配置**: 支持多种配置选项(模型、密钥、系统信息等)
17
+ - 🌐 **多平台支持**: 支持 macOS、Windows、Linux
18
+ - 🔌 **多模型支持**: 支持 OpenAI API 和 Ollama 本地模型
19
+
20
+ ## 安装
21
+
22
+ ### 从源码安装
23
+
24
+ ```bash
25
+ git clone https://github.com/W1412X/aibash.git
26
+ cd aibash
27
+ pip install -e .
28
+ ```
29
+
30
+ ### 使用 pip 安装
31
+
32
+ ```bash
33
+ pip install aibash
34
+ ```
35
+
36
+ ## 快速开始
37
+
38
+ ### 1. 配置
39
+
40
+ 首次使用前需要配置模型连接信息。配置文件位于 `~/.aibash/config.yaml`。
41
+
42
+ #### OpenAI API 配置示例
43
+
44
+ ```yaml
45
+ model:
46
+ provider: openai
47
+ api_base: https://api.openai.com/v1
48
+ api_key: your-api-key-here
49
+ model_name: gpt-3.5-turbo
50
+
51
+ history:
52
+ enabled: true
53
+ max_records: 50
54
+ include_output: true
55
+
56
+ system_info: "Linux 5.15.0 (x86_64)"
57
+ use_default_prompt: true
58
+ ```
59
+
60
+ #### Ollama 配置示例
61
+
62
+ ```yaml
63
+ model:
64
+ provider: ollama
65
+ api_base: http://localhost:11434
66
+ api_key: "" # Ollama 不需要密钥
67
+ model_name: llama2
68
+
69
+ history:
70
+ enabled: true
71
+ max_records: 50
72
+ include_output: true
73
+
74
+ system_info: "Linux 5.15.0 (x86_64)"
75
+ use_default_prompt: true
76
+ ```
77
+
78
+ ### 2. 使用
79
+
80
+ ```bash
81
+ # 基本用法
82
+ aibash -l "列出当前目录下的所有文件"
83
+
84
+ # 指定配置文件
85
+ aibash --config /path/to/config.yaml -l "查找包含test的文件"
86
+
87
+ # 查看帮助
88
+ aibash -h
89
+
90
+ # 初始化配置(首次使用)
91
+ aibash --init
92
+
93
+ # 查看命令历史
94
+ aibash --history
95
+
96
+ # 清空命令历史
97
+ aibash --clear-history
98
+
99
+ # 测试 AI 连接
100
+ aibash --test
101
+ ```
102
+
103
+ ## 命令行选项
104
+
105
+ - `-l, --lang QUERY`: 自然语言描述,用于生成 shell 命令
106
+ - `--config PATH`: 指定配置文件路径(默认: ~/.aibash/config.yaml)
107
+ - `--init`: 交互式初始化配置文件
108
+ - `--history`: 查看命令执行历史
109
+ - `--clear-history`: 清空命令执行历史
110
+ - `--test`: 测试 AI 连接
111
+ - `-h, --help`: 显示帮助信息
112
+ - `-v, --version`: 显示版本信息
113
+
114
+ 生成命令后,你可以选择:
115
+
116
+ - `[e]` 执行命令 - 直接执行生成的命令
117
+ - `[c]` 复制到剪贴板 - 将命令复制到剪贴板
118
+ - `[m]` 修改命令 - 修改命令后再执行
119
+ - `[s]` 跳过/放弃 - 不执行命令
120
+ - `[h]` 显示帮助 - 显示帮助信息
121
+
122
+ ## 配置说明
123
+
124
+ ### 模型配置
125
+
126
+ - `provider`: 模型提供商 (`openai` 或 `ollama`)
127
+ - `api_base`: API 基础 URL
128
+ - `api_key`: API 密钥(Ollama 可为空)
129
+ - `model_name`: 模型名称
130
+
131
+ ### 历史记录配置
132
+
133
+ - `enabled`: 是否启用历史记录
134
+ - `max_records`: 最大记录数
135
+ - `include_output`: 是否包含命令输出
136
+ - `history_file`: 历史记录文件路径(自动设置)
137
+
138
+ ### 其他配置
139
+
140
+ - `system_info`: 系统信息(用于生成更准确的命令)
141
+ - `custom_prompt`: 自定义 prompt 模板
142
+ - `use_default_prompt`: 是否使用默认 prompt
143
+
144
+ ## 自定义 Prompt
145
+
146
+ 你可以自定义 prompt 模板来更好地控制 AI 的行为。在配置文件中设置 `custom_prompt`,并使用以下占位符:
147
+
148
+ - `{system_info}`: 系统信息
149
+ - `{history_context}`: 历史上下文
150
+ - `{user_query}`: 用户查询
151
+
152
+ 示例:
153
+
154
+ ```yaml
155
+ custom_prompt: |
156
+ 你是一个专业的命令行助手。
157
+ 系统: {system_info}
158
+ {history_context}
159
+ 用户需求: {user_query}
160
+ 请生成对应的shell命令:
161
+ use_default_prompt: false
162
+ ```
163
+
164
+ ## 项目结构
165
+
166
+ ```
167
+ aibash/
168
+ ├── aibash/
169
+ │ ├── __init__.py
170
+ │ ├── config.py # 配置管理
171
+ │ ├── ai_client.py # AI 模型客户端
172
+ │ ├── history.py # 历史记录管理
173
+ │ ├── interactive.py # 交互式选择
174
+ │ ├── prompt.py # Prompt 管理
175
+ │ └── main.py # 主程序入口
176
+ ├── setup.py
177
+ ├── requirements.txt
178
+ └── README.md
179
+ ```
180
+
181
+ ## 开发
182
+
183
+ ### 运行测试
184
+
185
+ ```bash
186
+ python -m aibash.main -l "测试命令"
187
+ ```
188
+
189
+ ### 构建分发包
190
+
191
+ ```bash
192
+ python setup.py sdist bdist_wheel
193
+ ```
194
+
195
+ ## 文档
196
+
197
+ - [中文文档](README.md) - 本文档
198
+ - [English Documentation](README_EN.md) - English version
199
+
200
+ ## 许可证
201
+
202
+ MIT License
203
+
204
+ ## 作者
205
+
206
+ github/W1412X
207
+
208
+ ## 贡献
209
+
210
+ 欢迎提交 Issue 和 Pull Request!
211
+
@@ -0,0 +1,9 @@
1
+ """
2
+ AIBash - AI-powered shell command generator
3
+
4
+ Author: github/W1412X
5
+ """
6
+
7
+ __version__ = "0.1.0"
8
+ __author__ = "github/W1412X"
9
+
@@ -0,0 +1,11 @@
1
+ """
2
+ Agent 模块
3
+
4
+ 提供各种 AI Agent 实现
5
+ """
6
+
7
+ from .openai_agent import OpenAIAgent
8
+ from .ollama_agent import OllamaAgent
9
+ from .agent_builder import AgentBuilder
10
+
11
+ __all__ = ['OpenAIAgent', 'OllamaAgent', 'AgentBuilder']
@@ -0,0 +1,48 @@
1
+ """
2
+ Agent Builder - 工厂模式创建 Agent
3
+ """
4
+
5
+ from typing import Optional
6
+ from ..interfaces.ai_agent import AIAgent
7
+ from ..config import ModelConfig
8
+ from .openai_agent import OpenAIAgent
9
+ from .ollama_agent import OllamaAgent
10
+
11
+
12
+ class AgentBuilder:
13
+ """Agent 构建器"""
14
+
15
+ @staticmethod
16
+ def build_agent(config: ModelConfig, **kwargs) -> Optional[AIAgent]:
17
+ """
18
+ 根据配置构建 Agent
19
+
20
+ Args:
21
+ config: 模型配置
22
+ **kwargs: 额外参数(temperature, max_tokens, timeout)
23
+
24
+ Returns:
25
+ AIAgent 实例
26
+ """
27
+ provider = config.provider.lower()
28
+
29
+ if provider == "openai":
30
+ return OpenAIAgent(
31
+ api_base=config.api_base,
32
+ api_key=config.api_key,
33
+ model_name=config.model_name,
34
+ temperature=kwargs.get('temperature', 0.3),
35
+ max_tokens=kwargs.get('max_tokens', 500),
36
+ timeout=kwargs.get('timeout', 30)
37
+ )
38
+ elif provider == "ollama":
39
+ return OllamaAgent(
40
+ api_base=config.api_base,
41
+ model_name=config.model_name,
42
+ temperature=kwargs.get('temperature', 0.3),
43
+ max_tokens=kwargs.get('max_tokens', 500),
44
+ timeout=kwargs.get('timeout', 30)
45
+ )
46
+ else:
47
+ raise ValueError(f"Unsupported provider: {provider}")
48
+
@@ -0,0 +1,158 @@
1
+ """
2
+ Agent 实现 - Ollama
3
+ """
4
+
5
+ from typing import Dict, Any
6
+ import requests
7
+ from requests.adapters import HTTPAdapter
8
+ from urllib3.util.retry import Retry
9
+
10
+ from ..interfaces.ai_agent import AIAgent
11
+
12
+
13
+ class OllamaAgent(AIAgent):
14
+ """Ollama API Agent"""
15
+
16
+ def __init__(
17
+ self,
18
+ api_base: str,
19
+ model_name: str,
20
+ temperature: float = 0.3,
21
+ max_tokens: int = 500,
22
+ timeout: int = 30
23
+ ):
24
+ """
25
+ 初始化 Ollama Agent
26
+
27
+ Args:
28
+ api_base: API 基础 URL
29
+ model_name: 模型名称
30
+ temperature: 温度参数
31
+ max_tokens: 最大 token 数
32
+ timeout: 超时时间
33
+ """
34
+ self.api_base = api_base.rstrip('/')
35
+ self.model_name = model_name
36
+ self.temperature = temperature
37
+ self.max_tokens = max_tokens
38
+ self.timeout = timeout
39
+
40
+ # 创建带重试的 session
41
+ self.session = requests.Session()
42
+ retry_strategy = Retry(
43
+ total=3,
44
+ backoff_factor=1,
45
+ status_forcelist=[429, 500, 502, 503, 504]
46
+ )
47
+ adapter = HTTPAdapter(max_retries=retry_strategy)
48
+ self.session.mount("http://", adapter)
49
+ self.session.mount("https://", adapter)
50
+
51
+ def generate_command(self, prompt: str, **kwargs) -> str:
52
+ """生成命令"""
53
+ # 优先尝试 OpenAI 兼容 API
54
+ openai_compat_url = f"{self.api_base}/v1/chat/completions"
55
+
56
+ temperature = kwargs.get('temperature', self.temperature)
57
+ max_tokens = kwargs.get('max_tokens', self.max_tokens)
58
+ timeout = kwargs.get('timeout', self.timeout)
59
+
60
+ try:
61
+ data = {
62
+ "model": self.model_name,
63
+ "messages": [
64
+ {"role": "user", "content": prompt}
65
+ ],
66
+ "temperature": temperature,
67
+ "max_tokens": max_tokens
68
+ }
69
+
70
+ response = self.session.post(
71
+ openai_compat_url,
72
+ json=data,
73
+ timeout=timeout
74
+ )
75
+
76
+ if response.status_code == 200:
77
+ result = response.json()
78
+ content = result.get("choices", [{}])[0].get("message", {}).get("content", "")
79
+ if content:
80
+ return self._extract_command(content)
81
+ except Exception:
82
+ pass # 回退到传统 API
83
+
84
+ # 使用传统 Ollama API
85
+ url = f"{self.api_base}/api/generate"
86
+
87
+ data = {
88
+ "model": self.model_name,
89
+ "prompt": prompt,
90
+ "stream": False,
91
+ "options": {
92
+ "temperature": temperature,
93
+ "num_predict": max_tokens
94
+ }
95
+ }
96
+
97
+ try:
98
+ response = self.session.post(
99
+ url,
100
+ json=data,
101
+ timeout=timeout
102
+ )
103
+ response.raise_for_status()
104
+
105
+ result = response.json()
106
+ content = result.get("response", "")
107
+
108
+ if not content:
109
+ raise Exception("AI returned empty content")
110
+
111
+ return self._extract_command(content)
112
+
113
+ except requests.exceptions.RequestException as e:
114
+ raise Exception(f"Ollama API request failed: {e}")
115
+ except Exception as e:
116
+ raise Exception(f"Failed to generate command: {e}")
117
+
118
+ def test_connection(self) -> bool:
119
+ """测试连接"""
120
+ try:
121
+ # 检查模型是否存在
122
+ url = f"{self.api_base}/api/tags"
123
+ response = self.session.get(url, timeout=5)
124
+ if response.status_code == 200:
125
+ models = response.json().get("models", [])
126
+ model_names = [m.get("name", "") for m in models]
127
+ return self.model_name in model_names
128
+ return False
129
+ except Exception:
130
+ return False
131
+
132
+ def get_model_info(self) -> Dict[str, Any]:
133
+ """获取模型信息"""
134
+ return {
135
+ "provider": "ollama",
136
+ "model": self.model_name,
137
+ "api_base": self.api_base
138
+ }
139
+
140
+ def _extract_command(self, content: str) -> str:
141
+ """从 AI 输出中提取命令"""
142
+ content = content.strip()
143
+
144
+ # 移除 markdown 代码块
145
+ if content.startswith("```"):
146
+ lines = content.split("\n")
147
+ if len(lines) > 1:
148
+ content = "\n".join(lines[1:])
149
+ if content.endswith("```"):
150
+ content = content[:-3]
151
+
152
+ content = content.strip()
153
+ lines = content.split("\n")
154
+ command = lines[0].strip()
155
+ command = command.lstrip("$").lstrip(">").strip()
156
+
157
+ return command
158
+