Skip to content

开发者指南

欢迎来到 AnythingLLM 开发者指南!本指南将帮助您了解如何扩展、定制和集成 AnythingLLM。

概述

AnythingLLM 是一个功能强大的开源 AI 知识管理平台,为开发者提供了丰富的扩展和定制选项。无论您是想要集成新的 LLM 模型、开发自定义插件,还是构建基于 AnythingLLM 的应用程序,本指南都将为您提供详细的技术文档和示例。

快速开始

开发环境设置

在开始开发之前,请确保您的环境满足以下要求:

  • Node.js: 版本 18.0 或更高
  • npm: 版本 8.0 或更高
  • Git: 用于版本控制
  • Docker: (可选)用于容器化部署

获取源代码

bash
# 克隆仓库
git clone https://github.com/Mintplex-Labs/anything-llm.git
cd anything-llm

# 安装依赖
npm install

# 启动开发服务器
npm run dev

核心概念

架构概览

AnythingLLM 采用模块化架构设计,主要包含以下核心组件:

  • 前端界面: React + Vite 构建的现代化 Web 界面
  • 后端 API: Node.js + Express 提供的 RESTful API
  • 数据库层: 支持多种数据库(SQLite、PostgreSQL、MySQL)
  • 向量数据库: 用于文档嵌入和相似性搜索
  • LLM 集成层: 支持多种大语言模型的统一接口

数据流

  1. 文档处理: 文档上传 → 文本提取 → 分块处理 → 向量化 → 存储
  2. 对话流程: 用户输入 → 上下文检索 → LLM 推理 → 响应生成 → 结果返回

开发指南

API 开发

创建自定义端点

javascript
// server/endpoints/custom.js
const express = require('express');
const router = express.Router();

router.post('/custom-endpoint', async (req, res) => {
  try {
    // 您的自定义逻辑
    const result = await processCustomRequest(req.body);
    res.json({ success: true, data: result });
  } catch (error) {
    res.status(500).json({ success: false, error: error.message });
  }
});

module.exports = router;

数据库操作

javascript
// 使用内置的数据库模型
const { Workspace } = require('../models/workspace');

// 创建工作空间
const workspace = await Workspace.create({
  name: 'My Workspace',
  slug: 'my-workspace'
});

// 查询工作空间
const workspaces = await Workspace.findAll();

前端开发

创建自定义组件

jsx
// frontend/src/components/CustomComponent/index.jsx
import React, { useState, useEffect } from 'react';
import './index.css';

export default function CustomComponent({ data }) {
  const [state, setState] = useState(null);

  useEffect(() => {
    // 组件初始化逻辑
    initializeComponent();
  }, []);

  const initializeComponent = async () => {
    // 异步初始化
    const result = await fetchData();
    setState(result);
  };

  return (
    <div className="custom-component">
      <h3>自定义组件</h3>
      {state && (
        <div className="content">
          {/* 组件内容 */}
        </div>
      )}
    </div>
  );
}

LLM 集成

添加新的 LLM 提供商

javascript
// server/utils/AiProviders/custom-llm/index.js
class CustomLLMProvider {
  constructor(config) {
    this.config = config;
    this.client = this.initializeClient();
  }

  async chat(messages, options = {}) {
    try {
      const response = await this.client.chat({
        messages,
        ...options
      });
      return response;
    } catch (error) {
      throw new Error(`CustomLLM Error: ${error.message}`);
    }
  }

  initializeClient() {
    // 初始化 LLM 客户端
    return new CustomLLMClient(this.config);
  }
}

module.exports = CustomLLMProvider;

插件开发

插件架构

AnythingLLM 支持插件系统,允许开发者扩展平台功能:

javascript
// plugins/my-plugin/index.js
class MyPlugin {
  constructor() {
    this.name = 'my-plugin';
    this.version = '1.0.0';
  }

  async initialize(app) {
    // 插件初始化逻辑
    this.registerRoutes(app);
    this.registerHooks();
  }

  registerRoutes(app) {
    app.use('/api/my-plugin', require('./routes'));
  }

  registerHooks() {
    // 注册生命周期钩子
    app.hooks.register('before-chat', this.beforeChat.bind(this));
  }

  async beforeChat(context) {
    // 聊天前的处理逻辑
    return context;
  }
}

module.exports = MyPlugin;

部署指南

Docker 部署

dockerfile
# Dockerfile.custom
FROM node:18-alpine

WORKDIR /app
COPY package*.json ./
RUN npm ci --only=production

COPY . .
RUN npm run build

EXPOSE 3001
CMD ["npm", "start"]

环境配置

bash
# .env.production
NODE_ENV=production
SERVER_PORT=3001
JWT_SECRET=your-jwt-secret
DATABASE_URL=postgresql://user:pass@localhost:5432/anythingllm

# LLM 配置
OPENAI_API_KEY=your-openai-key
ANTHROPIC_API_KEY=your-anthropic-key

# 向量数据库配置
VECTOR_DB=pinecone
PINECONE_API_KEY=your-pinecone-key
PINECONE_INDEX=anythingllm-index

测试

单元测试

javascript
// tests/unit/workspace.test.js
const { Workspace } = require('../../server/models/workspace');

describe('Workspace Model', () => {
  test('should create workspace with valid data', async () => {
    const workspace = await Workspace.create({
      name: 'Test Workspace',
      slug: 'test-workspace'
    });
    
    expect(workspace.name).toBe('Test Workspace');
    expect(workspace.slug).toBe('test-workspace');
  });
});

API 测试

javascript
// tests/api/endpoints.test.js
const request = require('supertest');
const app = require('../../server/app');

describe('API Endpoints', () => {
  test('GET /api/workspaces should return workspaces', async () => {
    const response = await request(app)
      .get('/api/workspaces')
      .expect(200);
    
    expect(response.body.workspaces).toBeDefined();
  });
});

贡献指南

代码规范

  • 使用 ESLint 和 Prettier 进行代码格式化
  • 遵循 JavaScript Standard Style
  • 编写清晰的注释和文档
  • 提交前运行测试套件

提交流程

  1. Fork 项目仓库
  2. 创建功能分支:git checkout -b feature/new-feature
  3. 提交更改:git commit -m "Add new feature"
  4. 推送分支:git push origin feature/new-feature
  5. 创建 Pull Request

常见问题

开发环境问题

Q: 如何解决依赖安装失败? A: 尝试清除 npm 缓存:npm cache clean --force,然后重新安装依赖。

Q: 开发服务器启动失败? A: 检查端口是否被占用,确保环境变量配置正确。

集成问题

Q: 如何添加自定义 LLM 模型? A: 参考 LLM 集成章节,实现相应的提供商接口。

Q: 如何扩展数据库模型? A: 创建新的迁移文件,定义模型关系和字段。

AnythingLLM 是一个功能强大的开源 AI 知识管理平台,支持多种 LLM 模型,让您轻松构建智能对话系统和知识库。