### Application Setup and Running (Bash) Source: https://context7.com/valueriver/chatnext-agents/llms.txt Provides essential bash commands for setting up and running the application. This includes installing dependencies using npm, starting the application, and running it in development mode with auto-reload. It also specifies the required Node.js version. ```bash # Install dependencies npm install # Start application npm start # Development mode with auto-reload npm run dev # Required Node.js version: >= 18.0.0 ``` -------------------------------- ### Install Dependencies and Configure API Source: https://github.com/valueriver/chatnext-agents/blob/main/README.md This section details the steps to set up the project, including installing dependencies via npm and configuring API keys and URLs for OpenAI-compatible models. It highlights that any model supporting Tool Calling (Function Calling) with Chat Completions can be used. ```bash npm install export OPENAI_API_KEY=your_key export OPENAI_API_URL=https://api.openai.com # 可选,默认为官方地址 ``` -------------------------------- ### Agent Tool Definition Example (JavaScript) Source: https://context7.com/valueriver/chatnext-agents/llms.txt An example JavaScript file ('agents/memory_manager/tools.js') defining the tools for the 'memory_manager' agent. It includes functions for creating and reading memory, specifying their parameters and descriptions, following a structured format for tool definitions. ```javascript // Example: agents/memory_manager/tools.js const tools = [ { type: 'function', function: { name: 'create_memory', description: '创建新的记忆条目', parameters: { type: 'object', properties: { title: { type: 'string', description: '记忆标题' }, content: { type: 'string', description: '记忆内容' } }, required: ['title', 'content'] } } }, { type: 'function', function: { name: 'read_memory', description: '读取/搜索记忆内容', parameters: { type: 'object', properties: { keyword: { type: 'string', description: '搜索关键词(可选)' }, limit: { type: 'number', description: '返回结果数量限制,默认10条' }, memoryId: { type: 'number', description: '指定记忆ID(可选)' } }, required: [] } } } ]; export default tools ``` -------------------------------- ### Start AI Assistant CLI Application Source: https://context7.com/valueriver/chatnext-agents/llms.txt Initiates the AI assistant CLI application using Node.js. It imports the necessary runAgent function and utility functions for loading and saving messages and overviews. The output shows a welcome message and feature highlights. ```javascript import { runAgent } from './agents/handle.js' import { loadMessages, saveMessage, loadOverview } from './utils.js' // Start the CLI node app.js // Output: // 🚀 欢迎使用 AI 智能助手! // 💡 功能特点: // • 🧠 长期记忆 - 会记住重要信息 // • 🔍 历史搜索 - 可以查找之前的对话 // ... // 👤 您: ``` -------------------------------- ### Run CLI Application Source: https://github.com/valueriver/chatnext-agents/blob/main/README.md Instructions on how to launch the Chatnext Agents application from the command line. This assumes that dependencies have been installed and API configurations are set. ```bash node app.js ``` -------------------------------- ### Agent Development: Structure and Tools Source: https://github.com/valueriver/chatnext-agents/blob/main/README.md This guide outlines the conventional directory structure for developing new agents, including essential files like `model.js`, `prompt.js`, `tools.js`, and `map.js`. It also explains how to declare and map tools for agent execution. ```plaintext Agent Structure: - agents// - model.js - prompt.js - tools.js - map.js - functions/ (optional) Tool Declaration in tools.js: - List tool names, descriptions, and parameters. Tool Mapping in map.js: - Map tools to specific implementations (functions or sub-agents). ``` -------------------------------- ### Run Agent with Tool Calling and Recursive Execution Source: https://context7.com/valueriver/chatnext-agents/llms.txt Executes a specified agent with a given set of messages. The function orchestrates a multi-step process involving OpenAI API calls, tool execution (direct function calls or recursive agent calls), and message history updates. The example demonstrates an agent calling another agent which then calls a tool. ```javascript import { runAgent } from './agents/handle.js' // Basic agent execution const response = await runAgent({ agentName: 'main_manager', messages: [ { role: 'user', content: '查看我有多少条记忆' } ] }) // Execution flow: // 1. Load agent config: prompt, tools, map, model // 2. Prepend system prompt to messages // 3. Loop: // a. Call OpenAI API with messages and tools // b. If no tool_calls: return message.content // c. If tool_calls exist: // - For type='function': execute function directly // - For type='agent': recursively call runAgent() // - Append tool results to messages // - Continue loop // In this case: // - main_manager receives request // - Decides to call memory_manager agent // - memory_manager calls read_memory function // - SQL: SELECT COUNT(*) FROM memories // - Result returned to user ``` -------------------------------- ### Process User Message and Orchestrate Agent Response Source: https://context7.com/valueriver/chatnext-agents/llms.txt Handles incoming user messages by loading conversation history and AI's understanding. It constructs a message context including system and historical messages, saves the user's message, and then calls the main orchestrator agent to get an AI response. Finally, it logs the AI's response and saves it. ```javascript // User input: "记住我喜欢咖啡" async function handleUserMessage(userMessage) { // Load conversation history (last 20 messages) const history = await loadMessages(20) // Load AI's current understanding of user const overview = await loadOverview() // Build message context const messages = [] // Add system context if (overview) { messages.push({ role: 'system', content: `当前对用户的认知状态: ${overview}` }) } // Add conversation history for context messages.push(...history) // Add current user message messages.push({ role: 'user', content: userMessage }) // Save user message to database await saveMessage('user', userMessage) // Call main orchestrator agent const aiResponse = await runAgent({ agentName: 'main_manager', messages: [...messages] }) console.log(`🤖 AI助手: ${aiResponse}`) // Save AI response await saveMessage('assistant', aiResponse) } // Result: AI analyzes request, calls update_overview tool // Database: INSERT INTO overviews (overview) VALUES ('用户喜欢咖啡') ``` -------------------------------- ### Initialize SQLite Database Connection with JavaScript Source: https://context7.com/valueriver/chatnext-agents/llms.txt Manages SQLite database connections using a singleton pattern via the `sqlite` function. Initializes the database file (`database/app.db`), executes schema definition (`database/schema.sql`), and enables foreign key constraints on the first call. Provides methods for running queries like INSERT, SELECT ALL, and SELECT ONE. ```javascript import { sqlite } from './database/sqlite.js' // Get database connection (singleton pattern) const db = await sqlite() // Using the connection db.run('INSERT INTO messages (role, content) VALUES (?, ?)', ['user', 'Hello'], function(err) { if (err) console.error(err) console.log('Inserted ID:', this.lastID) } ) db.all('SELECT * FROM messages LIMIT 5', [], (err, rows) => { if (err) console.error(err) console.log('Messages:', rows) }) db.get('SELECT COUNT(*) as count FROM memories', [], (err, row) => { if (err) console.error(err) console.log('Total memories:', row.count) }) // Database schema includes: // - overviews: AI's understanding of user // - messages: conversation history // - memories: long-term knowledge base // - activities: agent execution logs ``` -------------------------------- ### Environment Configuration: API Credentials (.env) Source: https://context7.com/valueriver/chatnext-agents/llms.txt Shows how to set up environment variables for API credentials, specifically the OpenAI API key and URL. This file is crucial for the application to authenticate with external services and can be configured to support various OpenAI-compatible APIs. ```bash # Create .env file in project root OPENAI_API_KEY=sk-your-api-key-here OPENAI_API_URL=https://api.openai.com # Supports OpenAI-compatible APIs: # - OpenAI: https://api.openai.com # - DeepSeek: https://api.deepseek.com # - Kimi: https://api.moonshot.cn # - Gemini: (via compatible endpoint) # - Grok: (via compatible endpoint) # - Doubao: (via compatible endpoint) ``` -------------------------------- ### Create a New Agent with Tools (JavaScript) Source: https://context7.com/valueriver/chatnext-agents/llms.txt Demonstrates how to create a new agent, 'weather_checker', with defined tools for checking weather and forecasts. This involves specifying tool names, descriptions, and parameters. The function returns a success message and a detailed list of created files. ```javascript import { createAgent } from './agents/agent_builder/functions/createAgent.js'; // Create a weather checking agent const result = await createAgent({ agentName: 'weather_checker', description: '天气查询专家', tools: [ { name: 'get_weather', description: '获取指定城市的天气信息', parameters: { type: 'object', properties: { city: { type: 'string', description: '城市名称' }, unit: { type: 'string', description: '温度单位:celsius或fahrenheit', enum: ['celsius', 'fahrenheit'] } }, required: ['city'] } }, { name: 'get_forecast', description: '获取未来天气预报', parameters: { type: 'object', properties: { city: { type: 'string', description: '城市名称' }, days: { type: 'number', description: '预报天数' } }, required: ['city', 'days'] } } ] }); // Returns: // "✅ Agent "weather_checker" 创建成功! // // 📁 路径: agents/weather_checker/ // 📝 描述: 天气查询专家 // 🔧 工具数量: 2 // // 📋 创建的文件: // - prompt.js # Agent提示词 // - model.js # 模型配置 // - tools.js # 工具定义 // - map.js # 工具映射 // - functions/get_weather.js # 获取指定城市的天气信息 // - functions/get_forecast.js # 获取未来天气预报 // // ✅ Agent已创建完成,系统会自动发现并加载该Agent" // Generated structure: // agents/weather_checker/ // ├── prompt.js (system prompt with tool descriptions) // ├── model.js (export default 'gpt-4o-mini') // ├── tools.js (OpenAI tool definitions) // ├── map.js (tool-to-function mappings) // └── functions/ // ├── get_weather.js (stub implementation) // └── get_forecast.js (stub implementation) // Agent can now be used immediately: // await runAgent({ // agentName: 'weather_checker', // messages: [ // { role: 'user', content: '北京今天天气怎么样?' } // ] // }) ``` -------------------------------- ### Load AI Knowledge Overview from Database (SQL) Source: https://context7.com/valueriver/chatnext-agents/llms.txt Retrieves the AI's latest understanding or overview of the user from the SQLite database. This overview is a string summarizing key user information. The SQL query executed to fetch this data is provided. ```javascript import { loadOverview } from './utils.js' // Get AI's latest understanding of user const overview = await loadOverview() // Returns: string // Example: "用户喜欢咖啡,不加糖;正在学习Python编程;项目截止日期是下周五" // SQL executed: // SELECT overview FROM overviews // ORDER BY created_at DESC LIMIT 1 ``` -------------------------------- ### Call OpenAI Chat Completions with JavaScript Source: https://context7.com/valueriver/chatnext-agents/llms.txt Integrates with the OpenAI API to perform chat completions using the `handleChat` function. Supports basic chat interactions and advanced features like function calling. Requires `OPENAI_API_KEY` environment variable. Optionally configures `OPENAI_API_URL`. ```javascript import { handleChat } from './agents/openai.js' // Basic chat completion const response = await handleChat({ model: 'gpt-4o-mini', messages: [ { role: 'system', content: '你是一个有用的AI助手' }, { role: 'user', content: '你好' } ] }) // With function calling const toolResponse = await handleChat({ model: 'gpt-4o-mini', messages: [ { role: 'user', content: '帮我创建一个记忆:明天开会' } ], tools: [ { type: 'function', function: { name: 'create_memory', description: '创建新的记忆条目', parameters: { type: 'object', properties: { title: { type: 'string', description: '记忆标题' }, content: { type: 'string', description: '记忆内容' } }, required: ['title', 'content'] } } } ] }) // Environment configuration: // OPENAI_API_KEY=sk-... // OPENAI_API_URL=https://api.openai.com (optional, defaults to OpenAI) ``` -------------------------------- ### Load Agent Configuration by Name (JavaScript) Source: https://context7.com/valueriver/chatnext-agents/llms.txt Loads an agent's configuration based on its name using a convention-based loader. It shows the expected structure of the returned agent object, including model, prompt, tools, and mapped functions, and the file structure of an agent. ```javascript import { loadAgent } from './agents/loader.js' // Load agent by name const agent = await loadAgent('memory_manager') // Returns: // { // model: 'gpt-4o-mini', // prompt: '你是记忆管理专家...', // tools: [ // { type: 'function', function: { name: 'create_memory', ... } }, // { type: 'function', function: { name: 'read_memory', ... } } // ], // map: [ // { name: 'create_memory', type: 'function', execute: fn }, // { name: 'read_memory', type: 'function', execute: fn } // ] // } // Agent structure expected: // agents/memory_manager/ // ├── model.js (export default 'gpt-4o-mini') // ├── prompt.js (export default 'You are...') // ├── tools.js (export default [...]) // ├── map.js (export default [...]) // └── functions/ // ├── create.js // └── read.js ``` -------------------------------- ### List All Agents (JavaScript) Source: https://context7.com/valueriver/chatnext-agents/llms.txt Provides a JavaScript function to retrieve and display a list of all available agents in the system. The output includes the agent's name, description, and the number of tools it possesses, along with a total count. ```javascript import { listAgents } from './agents/agent_builder/functions/listAgents.js'; const agentList = await listAgents(); // Returns formatted list: // "📋 系统中的所有 Agents: // // 1. main_manager // 描述: 主管理Agent,负责分析用户需求并调用合适的工具 // 工具数: 6 // // 2. memory_manager // 描述: 记忆管理专家 // 工具数: 4 // // 3. history_seeker // 描述: 对话历史搜索专家 // 工具数: 1 // // 4. weather_checker // 描述: 天气查询专家 // 工具数: 3 // // 总计: 4 个 Agents" ``` -------------------------------- ### Map Memory Management Functions to Tools (JavaScript) Source: https://context7.com/valueriver/chatnext-agents/llms.txt This Javascript code snippet demonstrates how memory management functions (create, read, update, delete) are imported and mapped to tool definitions. Each tool has a name, type, and an 'execute' property pointing to the corresponding function. This map is used for agent delegation. ```javascript import { createMemory } from './functions/create.js' import { readMemory } from './functions/read.js' import { updateMemory } from './functions/update.js' import { deleteMemory } from './functions/delete.js' const toolMap = [ { name: 'create_memory', type: 'function', execute: createMemory }, { name: 'read_memory', type: 'function', execute: readMemory }, { name: 'update_memory', type: 'function', execute: updateMemory }, { name: 'delete_memory', type: 'function', execute: deleteMemory } ] export default toolMap ``` -------------------------------- ### Run Recursive Agent Delegation (JavaScript) Source: https://context7.com/valueriver/chatnext-agents/llms.txt Demonstrates how to run a recursive agent delegation flow. The main manager agent analyzes user input and delegates tasks to other agents like history_seeker. It shows the input message and the expected internal calls and SQL queries. ```javascript // User asks: "我之前说过什么关于学习的?" // Flow: const result = await runAgent({ agentName: 'main_manager', messages: [ { role: 'user', content: '我之前说过什么关于学习的?' } ] }) // main_manager analyzes and delegates to history_seeker // Internally calls: // runAgent({ // agentName: 'history_seeker', // messages: [ // { role: 'user', content: '搜索关键词:学习' } // ] // }) // history_seeker executes search_messages tool: // SELECT role, content, created_at FROM messages // WHERE content LIKE '%学习%' // ORDER BY created_at DESC LIMIT 10 // Returns formatted results ``` -------------------------------- ### Execute Shell Commands with JavaScript Source: https://context7.com/valueriver/chatnext-agents/llms.txt Executes system shell commands using the `executeShell` function. It can list files, check versions, and handle command errors. Supports setting command timeouts and output buffer limits. Assumes the existence of a `shell_executor` module. ```javascript import { executeShell } from './agents/shell_executor/functions/executeShell.js' // List files const lsResult = await executeShell({ command: 'ls -la /tmp' }) // Check Node.js version const nodeVersion = await executeShell({ command: 'node --version' }) // Command with error const errorResult = await executeShell({ command: 'cat /nonexistent/file.txt' }) // Timeout after 30 seconds for long-running commands // maxBuffer: 1MB for command output ``` -------------------------------- ### Discover Available Agents (JavaScript) Source: https://context7.com/valueriver/chatnext-agents/llms.txt Scans the agents directory to discover and return a list of all available agent names. This function helps in identifying which agents can be loaded and utilized within the system. ```javascript import { discoverAgents } from './agents/loader.js' // Scan agents directory const agents = await discoverAgents() // Returns: ['main_manager', 'memory_manager', 'history_seeker', // 'sqlite_manager', 'shell_executor', 'agent_manager', // 'agent_builder'] ``` -------------------------------- ### Add a Tool to an Existing Agent (JavaScript) Source: https://context7.com/valueriver/chatnext-agents/llms.txt Illustrates how to add a new tool, 'get_air_quality', to an already created agent, 'weather_checker'. This function updates the agent's tool list by specifying the new tool's name, description, and parameters, returning a confirmation message. ```javascript import { addTool } from './agents/agent_builder/functions/addTool.js'; // Add a new tool to weather_checker const result = await addTool({ agentName: 'weather_checker', toolName: 'get_air_quality', toolDescription: '获取城市空气质量指数', toolParameters: { type: 'object', properties: { city: { type: 'string', description: '城市名称' } }, required: ['city'] } }); // Returns: "✅ 工具 'get_air_quality' 已添加到 Agent 'weather_checker'" // Updates: // - tools.js: adds new tool definition // - map.js: adds import and mapping // - functions/get_air_quality.js: creates stub implementation ``` -------------------------------- ### Agent Development: Extension Process Source: https://github.com/valueriver/chatnext-agents/blob/main/README.md This describes the workflow for extending agent capabilities by adding or modifying tools, implementing function logic, and updating the `map.js` file. It emphasizes ensuring the `main_manager` or other relevant agents can access the new tools. ```plaintext 1. Add/modify tool definitions in `tools.js`. 2. Implement function logic in `functions/` if it's a function-based tool. 3. Update the current Agent's `map.js` to point to the new function or target Agent. 4. Ensure the tool is referenced in the `main_manager`'s (or other orchestrator's) `map.js` for automatic scheduling. ``` -------------------------------- ### Read Memory Records (JavaScript) Source: https://context7.com/valueriver/chatnext-agents/llms.txt A tool function to retrieve memory records from the database. It supports fetching all memories (with a default limit), searching by keyword in title or content, or retrieving a specific memory by its ID. It demonstrates the expected return format and the SQL queries used for keyword search. ```javascript import { readMemory } from './agents/memory_manager/functions/read.js' // List all memories (default limit: 10) const allMemories = await readMemory({}) // Search by keyword const coffeeMemories = await readMemory({ keyword: '咖啡', limit: 5 }) // Get specific memory by ID const specificMemory = await readMemory({ memoryId: 15 }) // Returns formatted string: // "找到 2 条记忆记录: // // 1. [ID:15] 项目截止日期 (2024/10/31 13:45:22) // 内容: 新功能开发截止日期是2024年12月31日,需要完成用户认证模块 // // 2. [ID:23] 咖啡偏好 (2024/10/31 14:20:11) // 内容: 用户喜欢喝咖啡,不加糖,偏好美式咖啡" // SQL for keyword search: // SELECT id, title, content, created_at FROM memories // WHERE title LIKE '%咖啡%' OR content LIKE '%咖啡%' // ORDER BY created_at DESC LIMIT 5 ``` -------------------------------- ### Execute SQL Queries with JavaScript Source: https://context7.com/valueriver/chatnext-agents/llms.txt Executes SQL queries against a SQLite database using the `executeSql` function. It supports SELECT, INSERT, UPDATE, DELETE, and aggregate queries, returning formatted results or affected row counts. Assumes the existence of an `sqlite_manager` module. ```javascript import { executeSql } from './agents/sqlite_manager/functions/executeSql.js' // SELECT query - returns formatted table const queryResult = await executeSql({ sql: 'SELECT title, created_at FROM memories ORDER BY created_at DESC LIMIT 5' }) // INSERT/UPDATE/DELETE - returns affected rows const insertResult = await executeSql({ sql: "INSERT INTO memories (title, content) VALUES ('测试', '这是测试内容')" }) // Aggregate query const countResult = await executeSql({ sql: 'SELECT COUNT(*) as total FROM memories' }) ``` -------------------------------- ### Create Memory Record (JavaScript) Source: https://context7.com/valueriver/chatnext-agents/llms.txt A tool function used by the memory_manager agent to create a new memory record in the database. It takes a title and content, inserts them into the 'memories' table, and returns a success message with the new memory ID. It also shows the corresponding SQL INSERT statement. ```javascript // Tool call from memory_manager agent import { createMemory } from './agents/memory_manager/functions/create.js' const result = await createMemory({ title: '项目截止日期', content: '新功能开发截止日期是2024年12月31日,需要完成用户认证模块' }) // Returns: "记忆创建成功,记忆ID: 15" // SQL executed: // INSERT INTO memories (title, content) VALUES (?, ?) ``` -------------------------------- ### Load Conversation History from Database (SQL) Source: https://context7.com/valueriver/chatnext-agents/llms.txt Retrieves conversation history from the SQLite database. It allows loading a default number of messages (20) or a specified count. The function returns an array of message objects, each with a role and content. The SQL query executed for this operation is also provided. ```javascript import { loadMessages } from './utils.js' // Load last 20 messages (default) const messages = await loadMessages() // Load last 50 messages const moreMessages = await loadMessages(50) // Returns: Array<{role: 'user' | 'assistant', content: string}> // Example: // [ // { role: 'user', content: '你好' }, // { role: 'assistant', content: '您好!有什么可以帮您的吗?' }, // { role: 'user', content: '记住我喜欢咖啡' } // ] // SQL executed: // SELECT role, content FROM messages // ORDER BY created_at DESC LIMIT 20 ``` -------------------------------- ### Save Messages to Database (SQL) Source: https://context7.com/valueriver/chatnext-agents/llms.txt Saves user or assistant messages to the SQLite database. It takes the message role ('user' or 'assistant') and content as input and returns the ID of the newly inserted message. The SQL INSERT statement used for this operation is included. ```javascript import { saveMessage } from './utils.js' // Save user message const userResult = await saveMessage('user', '我想创建一个记忆') // Returns: { id: 42 } // Save assistant response const aiResult = await saveMessage('assistant', '好的,我来帮您创建记忆') // SQL executed: // INSERT INTO messages (role, content) VALUES (?, ?) ``` -------------------------------- ### Update Memory Record (JavaScript) Source: https://context7.com/valueriver/chatnext-agents/llms.txt A tool function to update an existing memory record. It allows modification of the title, content, or both, identified by memoryId. The function returns a success message and shows the corresponding SQL UPDATE statement. ```javascript import { updateMemory } from './agents/memory_manager/functions/update.js' // Update title only await updateMemory({ memoryId: 15, title: '项目重要截止日期' }) // Update content only await updateMemory({ memoryId: 15, content: '新功能开发截止日期延期到2025年1月15日' }) // Update both await updateMemory({ memoryId: 15, title: '项目新截止日期', content: '经过讨论,截止日期调整为2025年1月15日,包含完整测试' }) // Returns: "记忆 15 更新成功" // SQL executed: // UPDATE memories // SET title = ?, content = ?, updated_at = CURRENT_TIMESTAMP // WHERE id = ? ``` -------------------------------- ### Validate Agent Structure (JavaScript) Source: https://context7.com/valueriver/chatnext-agents/llms.txt Checks if a given agent name corresponds to a valid agent structure, ensuring all required files (model.js, prompt.js, tools.js, map.js, and functions directory) are present. Returns a boolean indicating validity. ```javascript import { validateAgentStructure } from './agents/loader.js' // Check if agent has all required files const isValid = await validateAgentStructure('memory_manager') // Returns: true const isInvalid = await validateAgentStructure('nonexistent_agent') // Returns: false ``` -------------------------------- ### Delete Memory Record (JavaScript) Source: https://context7.com/valueriver/chatnext-agents/llms.txt A tool function to delete a memory record from the database using its unique memoryId. It returns a success message indicating the deleted memory ID and shows the corresponding SQL DELETE statement. ```javascript import { deleteMemory } from './agents/memory_manager/functions/delete.js' await deleteMemory({ memoryId: 15 }) // Returns: "记忆 15 删除成功" // SQL executed: // DELETE FROM memories WHERE id = 15 ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.