### Automatic Package Installation with國內 PyPI Source Source: https://github.com/knownsec/aipyapp/blob/main/dev/ChangeLog.md Enhances automatic package installation to support configuring domestic PyPI sources, potentially speeding up installations in certain regions. ```Python import aipy aipy.config.set_pypi_source("https://pypi.tuna.tsinghua.edu.cn/simple") aipy.install_packages(["numpy", "pandas"]) ``` -------------------------------- ### Test Plugin Functionality Source: https://github.com/knownsec/aipyapp/blob/main/dev/Plugin.md Provides an example of how to test the Plugin class, including enabling debug mode and simulating a task start event. ```python # 测试插件文件 if __name__ == '__main__': plugin = Plugin({'debug': True}) # 测试事件处理 test_event = Event('task_start', {'instruction': 'test task'}) plugin.on_task_start(test_event) ``` -------------------------------- ### Start AIPython Agent Mode Source: https://github.com/knownsec/aipyapp/blob/main/dev/Agent.md Command to start the AIPython Agent Mode server with specified host and port. Enables agent functionality for API integration. ```bash python -m aipyapp --agent --host 127.0.0.1 --port 8848 ``` -------------------------------- ### Runtime Package Installation Definition Source: https://github.com/knownsec/aipyapp/blob/main/dev/ChangeLog.md Modifies the definition of `runtime.install_packages` for clarity and consistency in package management. ```Python import aipy.runtime # Updated definition for installing packages aipy.runtime.install_packages(package_list: list[str]) ``` -------------------------------- ### cURL Examples for AIPython API Source: https://github.com/knownsec/aipyapp/blob/main/dev/Agent.md Command-line examples using cURL to interact with the AIPython API. Demonstrates submitting tasks, checking task status, retrieving task results, listing all tasks, and performing a health check. ```bash # Submit task curl -X POST http://127.0.0.1:8848/tasks \ -H "Content-Type: application/json" \ -d '{ "instruction": "Write a Python function to calculate fibonacci numbers", "metadata": {"source": "curl", "user": "developer"} }' # Check status curl http://127.0.0.1:8848/tasks/550e8400-e29b-41d4-a716-446655440000 # Get results curl http://127.0.0.1:8848/tasks/550e8400-e29b-41d4-a716-446655440000/result # List all tasks curl http://127.0.0.1:8848/tasks # Health check curl http://127.0.0.1:8848/health ``` -------------------------------- ### LLM Configuration Wizard Source: https://github.com/knownsec/aipyapp/blob/main/dev/ChangeLog.md Introduces a GUI-based wizard for configuring Large Language Models (LLMs), simplifying the setup process for users. ```APIDOC LLMConfigWizard: description: Provides a graphical interface for configuring LLM parameters. features: - Model selection - API key input - Parameter tuning (temperature, max tokens, etc.) - Provider selection (OpenAI, Azure, etc.) ``` -------------------------------- ### LLM Configuration Example (DeepSeek) Source: https://github.com/knownsec/aipyapp/blob/main/dev/CONFIG.md An example of configuring the DeepSeek LLM, including type, model, API key, and other parameters like timeout and max tokens. It also explains the `params` field for model-specific configurations. ```toml [llm.deepseek] type = "deepseek" model = "deepseek-chat" api_key = "你的 DeepSeek API Key" enable = true default = false timeout = 10 max_tokens = 8192 params = {} # Example of model-specific parameters: # params = {thinking = {type = “enabled”, budget_tokens = 1024}} ``` -------------------------------- ### LiveDisplay Class for Real-time Streaming Source: https://github.com/knownsec/aipyapp/blob/main/dev/Display.md Provides an example of how to use the `LiveDisplay` class within a custom display plugin to manage and update real-time streaming content, including handling stream start, data updates, and stream end events. ```python from aipyapp.display import LiveDisplay class MyDisplayPlugin(BaseDisplayPlugin): def __init__(self, console: Console, quiet: bool = False): super().__init__(console, quiet) self.live_display = None def on_stream_start(self, event): """流式开始事件处理""" if not self.quiet: self.live_display = LiveDisplay() self.live_display.__enter__() def on_stream(self, event): """流式响应事件处理""" response = event.data lines = response.get('lines', []) reason = response.get('reason', False) if self.live_display: self.live_display.update_display(lines, reason=reason) def on_stream_end(self, event): """流式结束事件处理""" if self.live_display: self.live_display.__exit__(None, None, None) self.live_display = None ``` -------------------------------- ### Default Automatic Python Package Installation Source: https://github.com/knownsec/aipyapp/blob/main/dev/ChangeLog.md The system now defaults to automatically installing required Python packages, simplifying dependency management. ```APIDOC DependencyManagement: auto_install_python_packages: true description: Automatically installs necessary Python packages to ensure all features are available. ``` -------------------------------- ### Structured Logging Example Source: https://github.com/knownsec/aipyapp/blob/main/dev/Agent.md Demonstrates the format of structured logs used in agent mode, including task submission and completion with unique task IDs. ```log INFO | aipyapp.aipy.agent_taskmgr:81 - Task submitted: 550e8400-e29b-41d4-a716-446655440000 INFO | aipyapp.aipy.agent_taskmgr:129 - Task 550e8400-e29b-41d4-a716-446655440000 completed ``` -------------------------------- ### Input/Output and Console Independence Source: https://github.com/knownsec/aipyapp/blob/main/dev/FEATURES.md This section details requirements for unifying input/output interfaces to prepare for use outside of a console environment. It also addresses automatic confirmation for LLM package installations or environment access. ```python # Requirements for I/O and console independence: # - Automatically confirm LLM requests to install packages or access env # - Unify input/output interfaces for non-console usage # - Resolve client certificate path issues ``` -------------------------------- ### AIPython Python Mode - Automatic Library Installation Source: https://github.com/knownsec/aipyapp/blob/main/README.zh.md Illustrates AIPython's capability to automatically detect and prompt for the installation of necessary third-party libraries. Here, the user requests a task requiring 'psutil', and AIPython prompts for confirmation to install it. ```Python Python use - AIPython (Quit with 'exit()') >>> ai("使用psutil列出当前MacOS所有进程列表") 📦 LLM 申请安装第三方包: ['psutil'] 如果同意且已安装,请输入 'y [y/n] (n): y ``` -------------------------------- ### Automatic Package Installation Fix Source: https://github.com/knownsec/aipyapp/blob/main/dev/ChangeLog.md Corrects issues related to the automatic installation of packages, ensuring it functions as expected. ```APIDOC AutoPackageInstaller: status: Fixed description: Resolved bugs in the automatic package installation process. ``` -------------------------------- ### DisplayManager Class Usage Source: https://github.com/knownsec/aipyapp/blob/main/dev/Display.md Demonstrates how to initialize and use the DisplayManager for managing display plugins and styles in AiPy. It covers setting styles, getting the current plugin, and retrieving available styles. ```python from aipyapp.display import DisplayManager from rich.console import Console # 创建显示管理器 console = Console() display_manager = DisplayManager( style='classic', # 显示风格 console=console, # 控制台对象 record=True, # 是否记录输出 quiet=False # 是否安静模式 ) # 获取当前插件 plugin = display_manager.get_current_plugin() # 切换显示风格 display_manager.set_style('modern') # 获取可用风格列表 styles = display_manager.get_available_styles() ``` -------------------------------- ### Basic DisplayManager Usage Source: https://github.com/knownsec/aipyapp/blob/main/dev/Display.md Demonstrates the basic usage of `DisplayManager` to get the current display plugin and print messages with specific styles. ```python from aipyapp.display import DisplayManager from rich.console import Console # 创建显示管理器 console = Console() display_manager = DisplayManager('classic', console=console) # 获取显示插件 plugin = display_manager.get_current_plugin() # 使用插件 plugin.print("Hello, World!", style="green") ``` -------------------------------- ### BaseDisplayPlugin Class Structure Source: https://github.com/knownsec/aipyapp/blob/main/dev/Display.md Illustrates the structure of a custom display plugin by inheriting from BaseDisplayPlugin. It shows the constructor and example event handler methods for task lifecycle and execution events. ```python from aipyapp.display import BaseDisplayPlugin from rich.console import Console class MyDisplayPlugin(BaseDisplayPlugin): def __init__(self, console: Console, quiet: bool = False): super().__init__(console, quiet) # 初始化代码 # 事件处理方法 def on_task_start(self, event): """任务开始事件处理""" pass def on_exception(self, event): """异常事件处理""" pass # ... 其他事件方法 ``` -------------------------------- ### AIPython Task Mode (Alternative Prompt) Source: https://github.com/knownsec/aipyapp/blob/main/README.zh.md Another example of initiating AIPython and entering task mode. This shows the initial prompt and how a user might input a task. It also indicates the version and URL of AIPython. ```Shell pip install aipyapp -> % aipy 🚀 Python use - AIPython (0.1.22) [https://aipy.app] 请输入需要 AI 处理的任务 (输入 /use <下述 LLM> 切换) >> 获取Reddit r/LocalLLaMA 最新帖子 ...... >> ``` -------------------------------- ### Custom Display Plugin Implementation Source: https://github.com/knownsec/aipyapp/blob/main/dev/Display.md Implements a custom display style for the aipyapp project, handling events like task start, code execution, results, responses, and exceptions using Rich components for enhanced terminal output. ```python # -*- coding: utf-8 -*- from rich.console import Console from rich.panel import Panel from rich.text import Text from .base import BaseDisplayPlugin from .. import T class DisplayCustom(BaseDisplayPlugin): """Custom display style - 自定义显示风格""" def __init__(self, console: Console, quiet: bool = False): super().__init__(console, quiet) # 初始化自定义属性 self.custom_buffer = [] def on_task_start(self, event): """任务开始事件处理""" data = event.data instruction = data.get('instruction', '') # 自定义显示逻辑 title = Text("🚀 任务开始", style="bold blue") content = Text(instruction, style="white") panel = Panel(content, title=title, border_style="blue") self.console.print(panel) def on_exec(self, event): """代码执行事件处理""" block = event.data.get('block') if block and hasattr(block, 'code'): # 自定义代码显示 code_text = Text(block.code, style="green") self.console.print(f"💻 执行代码:\n{code_text}") def on_exec_result(self, event): """代码执行结果事件处理""" data = event.data result = data.get('result', {}) if 'traceback' in result: # 错误显示 error_text = Text(result['traceback'], style="red") self.console.print(f"❌ 执行错误:\n{error_text}") else: # 成功显示 output = result.get('output', '') if output: output_text = Text(output, style="green") self.console.print(f"✅ 执行成功:\n{output_text}") def on_response_complete(self, event): """LLM 响应完成事件处理""" data = event.data msg = data.get('msg') if msg and hasattr(msg, 'content'): # 自定义响应显示 response_text = Text(msg.content, style="cyan") panel = Panel(response_text, title="🤖 AI 回复", border_style="cyan") self.console.print(panel) # 实现其他需要的事件方法... def on_exception(self, event): """异常事件处理""" data = event.data msg = data.get('msg', '') exception = data.get('exception') error_text = Text(f"{msg}: {exception}", style="red") self.console.print(f"💥 异常: {error_text}") ``` -------------------------------- ### AiPy 插件基本类结构 Source: https://github.com/knownsec/aipyapp/blob/main/dev/Plugin.md 定义了 AiPy 插件的基本类 `Plugin`,包含初始化方法 `__init__` 和一系列可选的事件处理方法,如 `on_exception`、`on_task_start`、`on_exec`、`on_exec_result` 等。 ```python class Plugin: def __init__(self, config=None): """插件初始化 Args: config: 插件配置参数(来自角色配置) """ self.config = config print("[+] 插件已加载") # 事件处理方法(可选实现) def on_exception(self, event): """异常事件处理""" pass def on_task_start(self, event): """任务开始事件处理""" pass def on_exec(self, event): """代码执行事件处理""" pass def on_exec_result(self, event): """代码执行结果事件处理""" pass # ... 其他事件方法 ``` -------------------------------- ### Minimum Configuration Source: https://github.com/knownsec/aipyapp/blob/main/dev/CONFIG.md This snippet shows the minimal configuration required to set up a Trustoken LLM. ```toml [llm.trustoken] api_key = "你的Trustoken API Key" ``` -------------------------------- ### Test MyDisplayPlugin Functionality Source: https://github.com/knownsec/aipyapp/blob/main/dev/Display.md This code snippet provides a basic test case for the MyDisplayPlugin. It initializes the plugin with a Console instance and simulates a 'task_start' event to verify the debug output. This requires the Event class from aipyapp.aipy. ```python # 测试插件文件 if __name__ == '__main__': from rich.console import Console console = Console() plugin = MyDisplayPlugin(console) # 测试事件处理 from aipyapp.aipy import Event test_event = Event('task_start', {'instruction': 'test task'}) plugin.on_task_start(test_event) ``` -------------------------------- ### Python Mode - Third-Party Library Installation (Python) Source: https://github.com/knownsec/aipyapp/blob/main/README.md Illustrates AIPython's capability to automatically detect and request installation of necessary third-party libraries for a given task. The user is prompted to confirm the installation. ```Python Python use - AIPython (Quit with 'exit()') >>> ai("Use psutil to list all processes on MacOS") 📦 LLM requests to install third-party packages: ['psutil'] If you agree and have installed, please enter 'y [y/n] (n): y ``` -------------------------------- ### 提示词修改插件实现 Source: https://github.com/knownsec/aipyapp/blob/main/dev/Plugin.md 一个示例插件,实现了 `on_task_start` 事件处理方法,用于在任务开始时根据配置的模板修改用户提示词。 ```python class Plugin: def __init__(self, config=None): self.config = config or {} self.template = self.config.get('template', '') print("[+] 提示词修改插件已加载") def on_task_start(self, event): """任务开始事件处理""" data = event.data task = data.get('instruction', '') # 修改任务提示词 if self.template: modified_task = f"{self.template}\n\n{task}" data['instruction'] = modified_task print(f"[i] 提示词已修改") ``` -------------------------------- ### CLI命令管理LLM上下文 Source: https://github.com/knownsec/aipyapp/blob/main/dev/ContextManage.md 使用 `/context` 命令管理LLM对话上下文,包括显示当前上下文、统计信息、配置、清空上下文以及更新配置参数。 ```bash # 显示当前上下文 /context show # 显示上下文统计信息 /context stats # 显示上下文配置 /context config # 清空上下文 /context clear # 更新配置 /context config --strategy sliding_window --max-tokens 4096 ``` -------------------------------- ### Plugin Initialization and Logging Source: https://github.com/knownsec/aipyapp/blob/main/dev/Plugin.md Initializes a Plugin class, sets up a logger for the plugin, and logs an initialization message. It depends on the standard Python `logging` module. ```python import logging class Plugin: def __init__(self, config=None): self.logger = logging.getLogger(__name__) self.config = config self.logger.info("插件已初始化") ``` -------------------------------- ### Debug Mode Execution Source: https://github.com/knownsec/aipyapp/blob/main/dev/Agent.md Starts the aipyapp in debug mode with specified host and port. This is useful for detailed logging and troubleshooting. ```bash python -m aipyapp --agent --debug --host 127.0.0.1 --port 8848 ``` -------------------------------- ### Unified Entry Point: AiPy Source: https://github.com/knownsec/aipyapp/blob/main/docs/README.zh.md Introduces AiPy as the single, unified entry point for AI execution within the Python-Use paradigm, simplifying the user experience by consolidating all interactions within the Python interpreter. ```APIDOC Unified Entry Point: AiPy - Purpose: To serve as the sole entry point for AI execution, eliminating the need for complex clients and wrapper applications. - Interaction Model: All user interactions are consolidated within a Python environment. - Key Features: - Unified Terminal: All interactions converge to the Python interpreter. - Minimalist Path: Avoids installation of multiple Agents or plugins. - Consistent Experience: Provides a uniform user experience. - Access: AiPy is available at https://www.aipy.app/ ``` -------------------------------- ### JavaScript for Theme Loading and Code Block Handling Source: https://github.com/knownsec/aipyapp/blob/main/aipyapp/res/chatroom_zh.html This JavaScript code dynamically loads syntax highlighting themes (GitHub light and dark) based on the user's system color scheme preference. It also includes functionality to wrap code blocks, adding interactive elements like 'View Code'/'Hide Code' toggles and a copy button, enhancing the user experience for code display. ```javascript // 检测系统主题并加载对应的代码高亮主题 function loadHighlightTheme() { const isDarkMode = window.matchMedia('(prefers-color-scheme: dark)').matches; const themeLink = document.createElement('link'); themeLink.rel = 'stylesheet'; themeLink.href = isDarkMode ? 'css/github-dark.min.css' : 'css/github.min.css'; document.head.appendChild(themeLink); } // 监听系统主题变化 window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', loadHighlightTheme); // 初始加载主题 document.addEventListener('DOMContentLoaded', loadHighlightTheme); const renderer = new marked.Renderer(); // 把非代码块里的 HTML(如
const details = document.createElement('details');
details.classList.add('code-wrapper');
// 创建 元素作为可折叠的标题
const summary = document.createElement('summary');
summary.textContent = '▼ 查看代码'; // 初始显示“查看代码”
// 复制 的内容到 的 ::after 伪元素中,以便在折叠时显示代码语言(如果可用)
const codeElement = pre.querySelector('code');
if (codeElement) {
const lang = codeElement.getAttribute('class')?.replace('language-', '') || 'plaintext';
summary.style.setProperty('--code-language', `'${lang}'`);
}
// 将 移动到 中
details.appendChild(pre.cloneNode(true)); // 克隆以保留原始
pre.parentNode.replaceChild(details, pre);
details.prepend(summary);
// 添加点击事件监听器来切换 summary 的文本
details.addEventListener('toggle', () => {
summary.textContent = details.open ? '▲ 隐藏代码' : '▼ 查看代码';
});
// 添加复制按钮
const copyButton = document.createElement('button');
copyButton.textContent = '复制';
copyButton.classList.add('copy-button');
copyButton.style.cssText = `
position: absolute;
top: 8px;
right: 16px;
padding: 4px 8px;
background-color: var(--code-header-bg);
border: 1px solid var(--code-border);
border-radius: 3px;
cursor: pointer;
font-size: 12px;
transition: background-color 0.2s ease;
`;
summary.style.position = 'relative'; // 为 summary 定位子元素
summary.appendChild(copyButton);
copyButton.addEventListener('click', () => {
const codeToCopy = details.querySelector('pre code')?.textContent;
if (codeToCopy) {
navigator.clipboard.writeText(codeToCopy).then(() => {
copyButton.textContent = '已复制!';
setTimeout(() => {
copyButton.textContent = '复制';
}, 2000);
}).catch(err => {
console.error('Failed to copy code: ', err);
copyButton.textContent = '复制失败';
});
}
});
});
}
// 假设 marked 和 hljs 已经全局可用
// 在 DOM 加载完成后调用 wrapCodeBlocks
document.addEventListener('DOMContentLoaded', () => {
// ... 其他 DOMContentLoaded 逻辑 ...
wrapCodeBlocks();
});
```
--------------------------------
### Enable Debug Mode
Source: https://github.com/knownsec/aipyapp/blob/main/dev/Plugin.md
Enables or disables debug mode based on the 'debug' key in the configuration. When debug mode is active, it prints debug messages for task start events.
```python
class Plugin:
def __init__(self, config=None):
self.debug = config.get('debug', False)
def on_task_start(self, event):
if self.debug:
print(f"[DEBUG] 任务开始事件: {event.data}")
```
--------------------------------
### Registering New Display Plugin
Source: https://github.com/knownsec/aipyapp/blob/main/dev/Display.md
Demonstrates how to register a new display plugin, `DisplayCustom`, within the `DisplayManager` by adding it to the `DISPLAY_PLUGINS` dictionary.
```python
from .style_custom import DisplayCustom
class DisplayManager:
# 可用的显示效果插件
DISPLAY_PLUGINS = {
'classic': DisplayClassic,
'modern': DisplayModern,
'minimal': DisplayMinimal,
'custom': DisplayCustom, # 添加新插件
}
```
--------------------------------
### Configuration Management with Dynaconf
Source: https://github.com/knownsec/aipyapp/blob/main/dev/FEATURES.md
This section describes a strategy for simplifying configuration management using Dynaconf. It involves splitting configurations into default and local files to reduce complexity and avoid maintaining multiple versions during development.
```toml
# Default configuration file, committed to git
default.toml
# Local configuration file, for user-specific settings like API keys
local.toml
```
--------------------------------
### Updating Module Exports
Source: https://github.com/knownsec/aipyapp/blob/main/dev/Display.md
Shows how to update the `__all__` list in the `aipyapp/display/__init__.py` file to include the newly added `DisplayCustom` plugin, making it available for import.
```python
from .style_custom import DisplayCustom
__all__ = [
'BaseDisplayPlugin',
'DisplayClassic',
'DisplayModern',
'DisplayMinimal',
'DisplayCustom', # 添加新插件
'DisplayManager',
'LiveDisplay'
]
```
--------------------------------
### wxGUI Interface Implementation
Source: https://github.com/knownsec/aipyapp/blob/main/dev/ChangeLog.md
The implementation of the wxGUI (Graphical User Interface) has been completed, providing a visual front-end for the application.
```Python
import wx
from aipy.gui import MainFrame
app = wx.App()
frame = MainFrame(None, title="aipyapp")
frame.Show()
app.MainLoop()
```
--------------------------------
### Project Features Overview
Source: https://github.com/knownsec/aipyapp/blob/main/dev/FEATURES.md
This section provides a high-level overview of the project's features, including support for tips, custom LLM API parameters, removal of specific variables, API file, and status message notifications.
```python
# Project Features:
# - Support for tips
# - Support for custom LLM API parameters
# - Removal of __storage__ and __retval__ variables
# - api.py
# - Status message notifications
```
--------------------------------
### AIPython Task Mode Usage
Source: https://github.com/knownsec/aipyapp/blob/main/README.zh.md
Example of using AIPython in task mode to fetch the latest posts from a Reddit subreddit. The user inputs a natural language request, and AIPython processes it. The '/done' command is used to exit.
```Shell
uv run aipy
>>> 获取Reddit r/LocalLLaMA 最新帖子
......
......
>>> /done
```
--------------------------------
### AIPython Python Mode - Natural Language Task
Source: https://github.com/knownsec/aipyapp/blob/main/README.zh.md
Demonstrates using AIPython in Python mode to execute a natural language request. The `ai()` function is used to process the request, which in this case is to get the title of the Google homepage.
```Python
>>> ai("获取Google官网首页标题")
```
--------------------------------
### BaseDisplayPlugin API
Source: https://github.com/knownsec/aipyapp/blob/main/dev/Display.md
API documentation for the BaseDisplayPlugin class, outlining the core methods available for custom display plugins.
```APIDOC
BaseDisplayPlugin:
__init__(console: Console, quiet: bool = False)
console: A rich.console.Console object.
quiet: Whether the plugin should run in quiet mode.
print(message: str, style: str = None)
Prints a message to the console with an optional style.
Parameters:
message: The message to print.
style: An optional style name (e.g., 'info', 'warning').
input(prompt: str) -> str
Prompts the user for input.
Parameters:
prompt: The input prompt message.
Returns: The user's input string.
confirm(prompt: str, default: str = 'n', auto: bool = None) -> bool
Asks the user for confirmation.
Parameters:
prompt: The confirmation prompt.
default: The default answer ('y' or 'n').
auto: Automatically answer based on default if True.
Returns: True if confirmed, False otherwise.
save(path: str, clear: bool = False, code_format: str = None)
Saves output to a file.
Parameters:
path: The path to save the file.
clear: Whether to clear the output after saving.
code_format: The format for code blocks if applicable.
```
--------------------------------
### Enable Debug Mode in MyDisplayPlugin
Source: https://github.com/knownsec/aipyapp/blob/main/dev/Display.md
This snippet demonstrates how to enable and utilize debug mode within a custom display plugin. It shows the initialization of the plugin with debugging enabled and how to log debug messages during task start events. Dependencies include the Console class from the rich library and the BaseDisplayPlugin.
```python
class MyDisplayPlugin(BaseDisplayPlugin):
def __init__(self, console: Console, quiet: bool = False):
super().__init__(console, quiet)
self.debug = True # 启用调试模式
def on_task_start(self, event):
if self.debug:
self.console.print(f"[DEBUG] Task start event: {event.data}")
# 正常处理逻辑
```
--------------------------------
### AiPy: Unified AI Client
Source: https://github.com/knownsec/aipyapp/blob/main/docs/README.md
Introduces AiPy as the single entry point for interacting with the Python-Use paradigm, offering a unified and clutter-free interface.
```APIDOC
AiPy: Unified AI Client
- Single Entry Point: Interact with AI through AiPy.
- Unified Interface: All interactions are managed via Python.
- Zero Clutter: Eliminates plugin mess and bloated clients.
- Official Website: https://www.aipy.app/
```
--------------------------------
### Shiv Packaging Support
Source: https://github.com/knownsec/aipyapp/blob/main/dev/FEATURES.md
This section indicates that the project supports packaging using Shiv.
```python
# Support shiv packaging
```
--------------------------------
### Role and Plugin Support
Source: https://github.com/knownsec/aipyapp/blob/main/dev/FEATURES.md
This section highlights the addition of role support for tasks and the integration of plugin capabilities within the project.
```python
# Task role support
# Plugin support
```
--------------------------------
### Customizable Prompts
Source: https://github.com/knownsec/aipyapp/blob/main/dev/ChangeLog.md
Allows users to customize system prompts, enabling better control over AI behavior and responses.
```Python
from aipy import AI
ai = AI()
ai.set_system_prompt("You are a helpful assistant.")
```
--------------------------------
### Python-Use Execution Loop
Source: https://github.com/knownsec/aipyapp/blob/main/docs/README.md
Illustrates the core execution loop of the Python-Use paradigm, which involves a task being decomposed into planning, coding, execution, and feedback stages.
```APIDOC
Python-Use Execution Loop:
Task -> Plan -> Code -> Execute -> Feedback
- Task: User describes the desired outcome.
- Plan: The AI model decomposes the task and creates a strategic plan.
- Code: An optimal Python strategy is generated based on the plan.
- Execute: The generated Python code interacts directly with the environment.
- Feedback: The output of the execution is evaluated and used to refine the plan.
```
--------------------------------
### Python API管理LLM上下文
Source: https://github.com/knownsec/aipyapp/blob/main/dev/ContextManage.md
使用 `aipyapp.aipy.context_manager` 中的 `ContextManager` 和 `ContextConfig` 类来配置和管理LLM对话上下文。支持添加消息、获取压缩后的消息以及获取统计信息。
```python
from aipyapp.aipy.context_manager import ContextManager, ContextConfig, ContextStrategy
# 创建配置
config = ContextConfig(
max_tokens=4096,
strategy=ContextStrategy.HYBRID,
preserve_recent=3
)
# 创建管理器
manager = ContextManager(config)
# 添加消息
message = ChatMessage(role="user", content="你好")
manager.add_message(message)
# 获取压缩后的消息
messages = manager.get_messages()
# 获取统计信息
stats = manager.get_stats()
```
--------------------------------
### Help Description Update
Source: https://github.com/knownsec/aipyapp/blob/main/dev/ChangeLog.md
The help descriptions within the application have been updated to provide more accurate and comprehensive information to users.
```APIDOC
HelpSystem:
command_help:
aipy:
description: Main command-line interface for AI tasks.
usage: "aipy [options] "
```
--------------------------------
### aipyapp Configuration Initialization
Source: https://github.com/knownsec/aipyapp/blob/main/dev/ChangeLog.md
The `aipy/config.py` file has been modified to remove `default.toml` from the `__init__` parameters, with configuration now being fetched internally.
```Python
class Config:
def __init__(self):
# Configuration is fetched internally
pass
```
--------------------------------
### Configuration Window
Source: https://github.com/knownsec/aipyapp/blob/main/dev/ChangeLog.md
Adds a dedicated window for managing application settings and configurations.
```APIDOC
ConfigurationWindow:
description: Allows users to view and modify application settings.
sections:
- General Settings
- API Keys
- Model Configuration
```
--------------------------------
### MCP 命令行管理 - 服务器级别控制
Source: https://github.com/knownsec/aipyapp/blob/main/dev/MCP.md
展示了如何使用命令行启用或禁用特定的 MCP 服务器,以及如何使用通配符 `*` 对所有服务器执行批量操作。
```bash
/mcp enable
/mcp disable
/mcp enable *
/mcp disable *
```
--------------------------------
### 使用 MCP 工具的示例请求
Source: https://github.com/knownsec/aipyapp/blob/main/dev/MCP.md
提供了在 aipyapp 中与 AI 助手交互以使用 MCP 工具的示例用户请求,包括搜索文件和列出可用工具。
```bash
搜索我的文档里含有"人工智能"的文件
请列出所有可用的工具及其用途
```
--------------------------------
### AiPy 事件参数格式
Source: https://github.com/knownsec/aipyapp/blob/main/dev/Plugin.md
展示了插件事件处理方法中 `event` 参数的结构,说明如何通过 `event.data` 访问具体的事件数据,例如任务指令 (`instruction`) 和用户提示词 (`user_prompt`)。
```python
def on_task_start(self, event):
"""任务开始事件处理"""
data = event.data
instruction = data.get('instruction')
user_prompt = data.get('user_prompt')
# 处理事件数据
```
--------------------------------
### 命令行使用示例
Source: https://github.com/knownsec/aipyapp/blob/main/dev/Role.md
通过命令行切换角色和查看当前角色信息。
```bash
# 切换角色
/use @role.aipy
# 查看当前角色
/role info
```
--------------------------------
### MCP 命令行管理 - 查看状态
Source: https://github.com/knownsec/aipyapp/blob/main/dev/MCP.md
展示了如何使用 `/mcp` 命令查看全局 MCP 状态以及所有服务器的启用状态和工具数量。
```bash
/mcp
```
--------------------------------
### Python-Use Paradigm Overview
Source: https://github.com/knownsec/aipyapp/blob/main/docs/README.zh.md
Illustrates the core concept of Python-Use, where Large Language Models (LLMs) are deeply integrated with Python interpreters to create a closed-loop process for task execution. This paradigm emphasizes direct code generation and execution over traditional agent frameworks.
```APIDOC
Python-Use Paradigm:
Core Concept: LLM + Python Interpreter
Process Flow:
- Task: User expresses intent in natural language.
- Plan: Model automatically decomposes and plans execution path.
- Code: Generates optimal Python solution.
- Execute: Directly interacts with the real environment and performs actions.
- Feedback: Obtains results, analyzes deviations, and self-corrects.
Key Capabilities:
- API Calling: Model automatically writes and executes Python code to call APIs.
- Packages Calling: Model autonomously selects and calls rich libraries from the Python ecosystem.
Philosophy: No Agents, Code is Agent
- Rejects reliance on external tools, protocols, and execution layers.
- Enables models to control the environment directly through code.
Benefits:
- Eliminates high barriers, costs, and reliance on developer ecosystems.
- Overcomes limitations of cloud-based sandboxes for AI actions.
- Facilitates deep AI-environment connection and native execution potential.
- Simplifies user interaction to 'describe task -> auto-complete -> return result'.
```
--------------------------------
### DisplayManager API
Source: https://github.com/knownsec/aipyapp/blob/main/dev/Display.md
API documentation for the DisplayManager class, detailing its methods for managing display styles and plugins.
```APIDOC
DisplayManager:
__init__(style: str = 'classic', console: Console = None, record: bool = False, quiet: bool = False)
style: The display style to use (e.g., 'classic', 'modern').
console: A rich.console.Console object for output.
record: Whether to record output.
quiet: Whether to run in quiet mode.
get_available_styles() -> list[str]
Returns a list of available display style names.
set_style(style_name: str)
Sets the current display style.
Parameters:
style_name: The name of the style to set.
get_current_plugin()
Returns the current display plugin instance.
register_plugin(name: str, plugin_class: type)
Registers a new display plugin.
Parameters:
name: The name of the plugin.
plugin_class: The plugin class to register.
```