Skip to content

Commit

Permalink
Next AI (#4)
Browse files Browse the repository at this point in the history
* feat: replace openai with langchain

* refactor: almost all codes

* fix: improve ux

* refactor(index.js): remove send text prefix

* feat: add index page
  • Loading branch information
supersonictw authored Nov 7, 2024
1 parent 7287ce4 commit d42ce61
Show file tree
Hide file tree
Showing 66 changed files with 1,813 additions and 523 deletions.
2 changes: 1 addition & 1 deletion .devcontainer/Dockerfile
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
FROM mcr.microsoft.com/devcontainers/javascript-node:0-18
FROM mcr.microsoft.com/devcontainers/javascript-node:0-20
ARG MONGO_TOOLS_VERSION=6.0
RUN . /etc/os-release \
&& curl -sSL "https://www.mongodb.org/static/pgp/server-${MONGO_TOOLS_VERSION}.asc" | gpg --dearmor > /usr/share/keyrings/mongodb-archive-keyring.gpg \
Expand Down
2 changes: 1 addition & 1 deletion .devcontainer/devcontainer.json
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,6 @@
]
}
},
"forwardPorts": [3000, 3500, 8081],
"forwardPorts": [3000, 3500],
"postCreateCommand": "npm install"
}
16 changes: 6 additions & 10 deletions .devcontainer/docker-compose.yml
Original file line number Diff line number Diff line change
Expand Up @@ -5,23 +5,19 @@ services:
build:
context: .
dockerfile: Dockerfile
container_name: local-app
volumes:
- ../..:/workspaces:cached
command: sleep infinity
network_mode: service:mongo

mongo:
image: mongo:latest
container_name: local-mongo
restart: unless-stopped

express:
image: mongo-express:latest
container_name: local-express
redis:
image: redis:latest
restart: unless-stopped

chroma:
image: chromadb/chroma:latest
restart: unless-stopped
environment:
ME_CONFIG_BASICAUTH_USERNAME: developer
ME_CONFIG_BASICAUTH_PASSWORD: developer
ME_CONFIG_MONGODB_SERVER: local-mongo
network_mode: service:mongo
41 changes: 36 additions & 5 deletions .env.sample
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,44 @@
NODE_ENV="development"

# general
TRUST_PROXY="loopback" # empty to disable, ('loopback', 'linklocal', 'uniquelocal' or ip addresses)
ENABLED_PROTOCOLS="http,https" # ('http', 'https')
ENABLED_REDIRECT_HTTP_HTTPS="no" # redirect http to https ('yes' or 'no')

# http
HTTP_PORT="3000"
MONGODB_URI="mongodb://local-mongo:27017/app"
HTTP_HOSTNAME="127.0.0.1"

# https
HTTPS_PORT="3500"
HTTPS_HOSTNAME="127.0.0.1"
HTTPS_KEY_PATH="/some/where.key"
HTTPS_CERT_PATH="/some/where.crt"

# database
MONGODB_URI="mongodb://mongo:27017/app"
CHROMA_URI="http://chroma:8000"
REDIS_URI="redis://redis:6379"

# cors
ENABLED_CORS="no" # cors ('yes' or 'no'), CORS_ORIGIN is required
ENABLED_CORS_ORIGIN_CHECK="no" # is the API public to every client ('yes' or 'no')
CORS_ORIGIN="https://example.org"

# api docs server
ENABLED_SWAGGER="yes" # swagger ('yes' or 'no')
SWAGGER_SERVER_DESCRIPTION="default"
SWAGGER_CORS_ORIGIN="http://127.0.0.1:3000"
SWAGGER_SERVER_URL="http://127.0.0.1:3000"

# sara config
SARA_RECV_HOST="http://127.0.0.1:3000" # replace the field with your sara.recv entrypoint
SARA_AUDIENCE_URL="https://example.org"

# openai integration
OPENAI_BASE_URL="https://web-tech-tw.eu.org/openai/v1"
OPENAI_API_KEY="your_gemini_api_key"
OPENAI_CHAT_MODEL="gpt-3.5-turbo"
# gemini integration
GEMINI_API_KEY="your_gemini_api_key"
GEMINI_MODEL_NAME="gemini-1.0-pro"
GEMINI_SYSTEM_PROMPT="這是一場角色扮演,但請您不要向我再次透漏這是一場扮演,並以一般交談方式溝通。溝通請使用正體中文交談,您的正體中文名字是「寧芙」,英文名字是「Nymph」。你來自於「臺灣網際網路技術推廣組織」,該組織英文名稱為「Taiwan Web Technology Promotion Organization」,該組織主旨為:在臺灣推廣網際網路技術,如JavaScript、資訊安全素養、網路通訊觀念......等。溝通方式將以 Discord 通訊軟體的方式進行,你可以任意使用Markdown語法。若有人使用「@」標注任何人,請勿不要再次重複標注。"

# discord integration
DISCORD_APP_ID="00000"
Expand Down
17 changes: 3 additions & 14 deletions .github/workflows/main.yml
Original file line number Diff line number Diff line change
Expand Up @@ -22,33 +22,22 @@ jobs:
uses: actions/checkout@v3

- name: Log in to the Container registry
uses: docker/login-action@f4ef78c080cd8ba55a85445d5b36e214a81df20a
uses: docker/login-action@v3
with:
registry: ${{ env.REGISTRY }}
username: ${{ github.actor }}
password: ${{ secrets.GITHUB_TOKEN }}

- name: Extract metadata (tags, labels) for Docker
id: meta
uses: docker/metadata-action@507c2f2dc502c992ad446e3d7a5dfbe311567a96
uses: docker/metadata-action@v5
with:
images: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}

- name: Build and push Docker image
uses: docker/build-push-action@3b5e8027fcad23fda98b2e3ac259d8d67585f671
uses: docker/build-push-action@v6
with:
context: .
push: true
tags: ${{ steps.meta.outputs.tags }}
labels: ${{ steps.meta.outputs.labels }}

deploy-service:
name: Deploy application as service
needs: build-and-push-image
runs-on: ubuntu-latest

steps:
- name: Trigger deploy webhook
uses: wei/curl@master
with:
args: ${{ secrets.DEPLOY_WEBHOOK_URL }}
10 changes: 7 additions & 3 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
# App config files
keypair_*
.env
prompts.json
relay.json
Expand All @@ -10,7 +11,12 @@ data/
# Finder config file
.DS_Store

# OpenAPI exported file
openapi_exported.json

# Directories
.nyc_output
coverage
node_modules
ssl_keys
dist
Expand All @@ -22,8 +28,6 @@ yarn-error.log*
pnpm-debug.log*

# Editor directories and files
coverage
.nyc_output
.idea
.vscode
*.suo
Expand All @@ -33,4 +37,4 @@ coverage
*.sw?

# Lock file
package-lock.json
package-lock.json
File renamed without changes.
13 changes: 5 additions & 8 deletions Dockerfile
Original file line number Diff line number Diff line change
@@ -1,22 +1,19 @@
FROM node:18
FROM node:20-alpine

ENV RUNTIME_ENV container

RUN useradd -u 3000 recv

RUN mkdir -p \
/home/recv \
/workplace
RUN adduser -u 3000 -D recv

RUN mkdir -p /.npm /workplace
WORKDIR /workplace
ADD . /workplace

RUN chown -R \
3000:3000 \
/home/recv \
/workplace
/.npm /workplace

USER 3000
RUN npm install

EXPOSE 3000
CMD ["npm", "start"]
2 changes: 1 addition & 1 deletion LICENSE
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
MIT License

Copyright (c) 2021 Taiwan Web Technology Promotion Organization (https://github.com/web-tech-tw)
Copyright (c) 2024 Taiwan Web Technology Promotion Organization (https://web-tech.tw)

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
Expand Down
85 changes: 79 additions & 6 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,10 +1,83 @@
# Nymph
# Template RECV

Automate resource management tasks, monitor activity, and provide support with this AI-powered bot.
[網頁客戶端](https://github.com/web-tech-tw/template.inte) | 伺服器端

![nymph](avatar.png)
一個小型卻強大的微服務框架。 A tiny but powerful microservice framework.

## Features
本系統為本組織的通用伺服器端範本,為敏捷開發而生。

- [ ] Roles assignment automatically
- [ ] Link Discord users with their ID of [Sara System](https://web-tech-tw.github.io/sara.inte)
本系統提供了一個簡單的架構,讓開發者可以快速開發出一個微服務。

本系統架構預設為 **單機模式** 設計。若有需求可自行擴充修改為 **分散式模式**

## 系統架構

本系統採用 node.js 打造,使用 express.js 作為基礎框架,並擴充了許多功能。

推薦運行於 `node.js 20` 以上版本。自帶 docker 範本,可快速部署。

- 基於 express.js 擴充的微服務框架,可相容 express.js 的所有功能及生態系統。
- 採用 commonjs 模組系統,可相容大部分 npm 套件及快速引用模組。
- 內建 node-cache 作為快取系統,可快速存取資料。
- 內建 mongoose 作為資料庫系統,可快速存取資料庫。
- 內建 jsonwebtoken 作為授權系統,可快速授權。
- 內建 mocha 作為自動化測試系統,可快速進行自動化測試。
- 內建 nodemon 作為開發除錯系統,可快速進行開發除錯。
- 內建 dotenv 作為環境變數系統,可快速設定環境變數。
- 內建 cors 作為跨來源資源共用系統,可快速設定跨來源資源共用。
- 內建 swagger 作為 API 文件系統,可快速產生 API 文件。
- 自帶 GitHub Actions 範本,可快速進行自動化測試、組建容器、部署容器等功能。
- 自帶 VScode DevContainer 範本,可快速進行開發、測試等功能。
- 具有快速驗證、快速授權、快速存取資料庫、快速存取快取等功能。
- 具有快速開發、快速測試、快速部署等功能。
- 高擴充性,可自行擴充功能。

## 系統設定

### 安裝相依套件

本專案使用 Node.js 作為開發環境,請先安裝 Node.js。

該指令會安裝專案所需的相依套件。

```sh
npm install
```

### 自動化測試

本專案採用 Mocha 作為自動化測試框架。

該指令會執行所有測試案例。

```sh
npm run test
```

### 開發除錯模式

本專案採用 Nodemon 作為開發除錯工具。

該指令會啟動伺服器,並在程式碼變更時自動重啟伺服器。

```sh
npm run dev
```

### 正式產品模式

該指令會啟動伺服器。

```sh
npm start
```

## 開放原始碼授權

本專案採用 MIT 開放原始碼授權。

詳細可參閱 [LICENSE](LICENSE) 檔案。

---

© [Taiwan Web Technology Promotion Organization](https://web-tech.tw)
81 changes: 52 additions & 29 deletions app.js
Original file line number Diff line number Diff line change
@@ -1,39 +1,62 @@
"use strict";

// Import config
const {
runLoader,
getMust,
get,
getEnvironmentOverview,
} = require("./src/config");
const {
prepare,
} = require("./src/clients/database");
const express = require("express");

// Load config
runLoader();

const app = express();

const runners = [];
if (get("LINE_CHANNEL_SECRET")) {
app.use("/line", require("./src/line")());
}
if (get("DISCORD_BOT_TOKEN")) {
runners.push(require("./src/discord"));
}
if (get("MATRIX_USERNAME")) {
runners.push(require("./src/matrix"));
}

(async () => {
await prepare();
await Promise.all(runners.map(
(runner) => runner(),
)).then(() => {
console.info("Nymph 系統 成功啟動");
}).catch((e) => {
console.error("Nymph 系統 啟動失敗:", e);
});
// Import constants
const constant = require("./src/init/const");

// Import useApp
const {useApp} = require("./src/init/express");

// Initialize application
const app = useApp();

// Initialize prepare handlers
const {
prepare: prepareDatabase,
} = require("./src/init/database");
const {
prepare: prepareListener,
} = require("./src/init/listener");

const prepareHandlers = [
prepareDatabase,
prepareListener,
];

// Render index page
app.get("/", (_, res) => {
res.render("index");
});

// The handler for robots.txt (deny all friendly robots)
app.get("/robots.txt", (_, res) => {
res.type("txt").send("User-agent: *\nDisallow: /");
});

// Load router dispatcher
const routerDispatcher = require("./src/routes");
routerDispatcher.load();

// Show banner message
(() => {
const {APP_NAME: appName} = constant;
const {node, runtime} = getEnvironmentOverview();
const statusMessage = `(environment: ${node}, ${runtime})`;
console.info(appName, statusMessage, "\n====");
})();

app.listen(getMust("HTTP_PORT"));
// Mount application and execute it
require("./src/execute")(app, prepareHandlers,
({protocol, hostname, port}) => {
console.info(`Protocol "${protocol}" is listening at`);
console.info(`${protocol}://${hostname}:${port}`);
},
);
Loading

0 comments on commit d42ce61

Please sign in to comment.