├── libs.d.ts ├── .gitignore ├── src ├── api │ ├── routes │ │ ├── ping.ts │ │ ├── token.ts │ │ ├── models.ts │ │ ├── index.ts │ │ └── chat.ts │ ├── consts │ │ └── exceptions.ts │ └── controllers │ │ └── chat.ts ├── lib │ ├── interfaces │ │ └── ICompletionMessage.ts │ ├── exceptions │ │ ├── APIException.ts │ │ └── Exception.ts │ ├── consts │ │ └── exceptions.ts │ ├── config.ts │ ├── response │ │ ├── SuccessfulBody.ts │ │ ├── Body.ts │ │ ├── FailureBody.ts │ │ └── Response.ts │ ├── initialize.ts │ ├── environment.ts │ ├── http-status-codes.ts │ ├── configs │ │ ├── service-config.ts │ │ └── system-config.ts │ ├── request │ │ └── Request.ts │ ├── logger.ts │ ├── server.ts │ └── util.ts ├── index.ts └── daemon.ts ├── .dockerignore ├── configs └── dev │ ├── service.yml │ └── system.yml ├── public └── welcome.html ├── README.md ├── tsconfig.json ├── Dockerfile ├── vercel.json ├── .github └── workflows │ ├── docker-image.yml │ └── sync.yml ├── package.json └── LICENSE /libs.d.ts: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | dist/ 2 | node_modules/ 3 | logs/ 4 | .vercel 5 | -------------------------------------------------------------------------------- /src/api/routes/ping.ts: -------------------------------------------------------------------------------- 1 | export default { 2 | prefix: '/ping', 3 | get: { 4 | '': async () => "pong" 5 | } 6 | } 7 | -------------------------------------------------------------------------------- /.dockerignore: -------------------------------------------------------------------------------- 1 | logs 2 | dist 3 | doc 4 | node_modules 5 | .vscode 6 | .git 7 | .gitignore 8 | README.md 9 | *.tar.gz 10 | -------------------------------------------------------------------------------- /configs/dev/service.yml: -------------------------------------------------------------------------------- 1 | # service name 2 | name: deepseek-free-api 3 | # Service binding host address 4 | host: '0.0.0.0' 5 | # Service binding port 6 | port: 8000 7 | -------------------------------------------------------------------------------- /src/lib/interfaces/ICompletionMessage.ts: -------------------------------------------------------------------------------- 1 | export default interface ICompletionMessage { 2 | role: 'system' | 'assistant' | 'user' | 'function'; 3 | content: string; 4 | } 5 | -------------------------------------------------------------------------------- /src/lib/exceptions/APIException.ts: -------------------------------------------------------------------------------- 1 | import Exception from './Exception.js'; 2 | 3 | export default class APIException extends Exception { 4 | 5 | 6 | constructor(exception: (string | number)[], errmsg?: string) { 7 | super(exception, errmsg); 8 | } 9 | 10 | } 11 | -------------------------------------------------------------------------------- /src/lib/consts/exceptions.ts: -------------------------------------------------------------------------------- 1 | export default { 2 | SYSTEM_ERROR: [-1000, 'System exception'], 3 | SYSTEM_REQUEST_VALIDATION_ERROR: [-1001, 'Request parameter verification error'], 4 | SYSTEM_NOT_ROUTE_MATCHING: [-1002, 'No matching route'] 5 | } as Record 6 | -------------------------------------------------------------------------------- /src/lib/config.ts: -------------------------------------------------------------------------------- 1 | import serviceConfig from "./configs/service-config.ts"; 2 | import systemConfig from "./configs/system-config.ts"; 3 | 4 | class Config { 5 | 6 | 7 | service = serviceConfig; 8 | 9 | 10 | system = systemConfig; 11 | 12 | } 13 | 14 | export default new Config(); 15 | -------------------------------------------------------------------------------- /public/welcome.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 🚀 Service has started 6 | 7 | 8 |

deepseek-free-api has been launched!
Please access through clients such as LobeChat / NextChat / Dify or OpenAI SDK!

9 | 10 | 11 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # deepseek-free-api 2 | 3 | 4 | ## Original Repo CN Version: 5 | 6 | ### https://github.com/LLM-Red-Team/deepseek-free-api 7 | 8 | 🚀 DeepSeek-V2 large model reverse API prostitution test [Specialty: GPT4 replacement], supports high-speed streaming output, multiple rounds of dialogue, zero-configuration deployment, and multi-channel token support. 9 | -------------------------------------------------------------------------------- /configs/dev/system.yml: -------------------------------------------------------------------------------- 1 | # Whether to enable request logs 2 | requestLog: true 3 | # Temporary directory path 4 | tmpDir: ./tmp 5 | # Log directory path 6 | logDir: ./logs 7 | # Log writing interval (milliseconds) 8 | logWriteInterval: 200 9 | # Log file validity period (milliseconds) 10 | logFileExpires: 2626560000 11 | # public directory path 12 | publicDir: ./public 13 | # Temporary file validity period (milliseconds) 14 | tmpFileExpires: 86400000 15 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "baseUrl": ".", 4 | "module": "NodeNext", 5 | "moduleResolution": "NodeNext", 6 | "allowImportingTsExtensions": true, 7 | "allowSyntheticDefaultImports": true, 8 | "noEmit": true, 9 | "paths": { 10 | "@/*": ["src/*"] 11 | }, 12 | "outDir": "./dist" 13 | }, 14 | "include": ["src/**/*", "libs.d.ts"], 15 | "exclude": ["node_modules", "dist"] 16 | } 17 | -------------------------------------------------------------------------------- /src/lib/response/SuccessfulBody.ts: -------------------------------------------------------------------------------- 1 | import _ from 'lodash'; 2 | 3 | import Body from './Body.ts'; 4 | 5 | export default class SuccessfulBody extends Body { 6 | 7 | constructor(data: any, message?: string) { 8 | super({ 9 | code: 0, 10 | message: _.defaultTo(message, "OK"), 11 | data 12 | }); 13 | } 14 | 15 | static isInstance(value) { 16 | return value instanceof SuccessfulBody; 17 | } 18 | 19 | } 20 | -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | FROM node:lts AS BUILD_IMAGE 2 | 3 | WORKDIR /app 4 | 5 | COPY . /app 6 | 7 | RUN yarn install --registry https://registry.npmmirror.com/ && yarn run build 8 | 9 | FROM node:lts-alpine 10 | 11 | COPY --from=BUILD_IMAGE /app/configs /app/configs 12 | COPY --from=BUILD_IMAGE /app/package.json /app/package.json 13 | COPY --from=BUILD_IMAGE /app/dist /app/dist 14 | COPY --from=BUILD_IMAGE /app/public /app/public 15 | COPY --from=BUILD_IMAGE /app/node_modules /app/node_modules 16 | 17 | WORKDIR /app 18 | 19 | EXPOSE 8000 20 | 21 | CMD ["npm", "start"] 22 | -------------------------------------------------------------------------------- /src/api/routes/token.ts: -------------------------------------------------------------------------------- 1 | import _ from 'lodash'; 2 | 3 | import Request from '@/lib/request/Request.ts'; 4 | import Response from '@/lib/response/Response.ts'; 5 | import chat from '@/api/controllers/chat.ts'; 6 | import logger from '@/lib/logger.ts'; 7 | 8 | export default { 9 | 10 | prefix: '/token', 11 | 12 | post: { 13 | 14 | '/check': async (request: Request) => { 15 | request 16 | .validate('body.token', _.isString) 17 | const live = await chat.getTokenLiveStatus(request.body.token); 18 | return { 19 | live 20 | } 21 | } 22 | 23 | } 24 | 25 | } 26 | -------------------------------------------------------------------------------- /src/api/consts/exceptions.ts: -------------------------------------------------------------------------------- 1 | export default { 2 | API_TEST: [-9999, 'API exception error'], 3 | API_REQUEST_PARAMS_INVALID: [-2000, 'The request parameter is illegal'], 4 | API_REQUEST_FAILED: [-2001, 'Request failed'], 5 | API_TOKEN_EXPIRES: [-2002, 'Token has expired'], 6 | API_FILE_URL_INVALID: [-2003, 'The remote file URL is illegal'], 7 | API_FILE_EXECEEDS_SIZE: [-2004, 'Remote file exceeds size'], 8 | API_CHAT_STREAM_PUSHING: [-2005, 'There is already a conversation flow being output'], 9 | API_CONTENT_FILTERED: [-2006, 'Content has been blocked due to compliance issues'], 10 | API_IMAGE_GENERATION_FAILED: [-2007, 'Image generation failed'] 11 | } 12 | -------------------------------------------------------------------------------- /src/api/routes/models.ts: -------------------------------------------------------------------------------- 1 | import _ from 'lodash'; 2 | 3 | export default { 4 | 5 | prefix: '/nai/v1', 6 | 7 | get: { 8 | '/models': async () => { 9 | return { 10 | "data": [ 11 | { 12 | "id": "deepseek-chat", 13 | "object": "model", 14 | "owned_by": "deepseek-free-api" 15 | }, 16 | { 17 | "id": "deepseek-coder", 18 | "object": "model", 19 | "owned_by": "deepseek-free-api" 20 | } 21 | ] 22 | }; 23 | } 24 | 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /src/api/routes/index.ts: -------------------------------------------------------------------------------- 1 | import fs from 'fs-extra'; 2 | 3 | import Response from '@/lib/response/Response.ts'; 4 | import chat from "./chat.ts"; 5 | import ping from "./ping.ts"; 6 | import token from './token.js'; 7 | import models from './models.ts'; 8 | 9 | export default [ 10 | { 11 | get: { 12 | '/': async () => { 13 | const content = await fs.readFile('public/welcome.html'); 14 | return new Response(content, { 15 | type: 'html', 16 | headers: { 17 | Expires: '-1' 18 | } 19 | }); 20 | } 21 | } 22 | }, 23 | chat, 24 | ping, 25 | token, 26 | models 27 | ]; 28 | -------------------------------------------------------------------------------- /src/lib/initialize.ts: -------------------------------------------------------------------------------- 1 | import logger from './logger.js'; 2 | 3 | 4 | process.setMaxListeners(Infinity); 5 | 6 | process.on("uncaughtException", (err, origin) => { 7 | logger.error(`An unhandled error occurred: ${origin}`, err); 8 | }); 9 | 10 | process.on("unhandledRejection", (_, promise) => { 11 | promise.catch(err => logger.error("An unhandled rejection occurred:", err)); 12 | }); 13 | 14 | process.on("warning", warning => logger.warn("System warning: ", warning)); 15 | 16 | process.on("exit", () => { 17 | logger.info("Service exit"); 18 | logger.footer(); 19 | }); 20 | 21 | process.on("SIGTERM", () => { 22 | logger.warn("received kill signal"); 23 | process.exit(2); 24 | }); 25 | 26 | process.on("SIGINT", () => { 27 | process.exit(0); 28 | }); 29 | -------------------------------------------------------------------------------- /vercel.json: -------------------------------------------------------------------------------- 1 | { 2 | "builds": [ 3 | { 4 | "src": "./dist/*.html", 5 | "use": "@vercel/static" 6 | }, 7 | { 8 | "src": "./dist/index.js", 9 | "use": "@vercel/node" 10 | } 11 | ], 12 | "routes": [ 13 | { 14 | "src": "/", 15 | "dest": "/dist/welcome.html" 16 | }, 17 | { 18 | "src": "/(.*)", 19 | "dest": "/dist", 20 | "headers": { 21 | "Access-Control-Allow-Credentials": "true", 22 | "Access-Control-Allow-Methods": "GET,OPTIONS,PATCH,DELETE,POST,PUT", 23 | "Access-Control-Allow-Headers": "X-CSRF-Token, X-Requested-With, Accept, Accept-Version, Content-Length, Content-MD5, Content-Type, Date, X-Api-Version, Content-Type, Authorization" 24 | } 25 | } 26 | ] 27 | } 28 | -------------------------------------------------------------------------------- /src/lib/response/Body.ts: -------------------------------------------------------------------------------- 1 | import _ from 'lodash'; 2 | 3 | export interface BodyOptions { 4 | code?: number; 5 | message?: string; 6 | data?: any; 7 | statusCode?: number; 8 | } 9 | 10 | export default class Body { 11 | 12 | 13 | code: number; 14 | 15 | message: string; 16 | 17 | data: any; 18 | 19 | statusCode: number; 20 | 21 | constructor(options: BodyOptions = {}) { 22 | const { code, message, data, statusCode } = options; 23 | this.code = Number(_.defaultTo(code, 0)); 24 | this.message = _.defaultTo(message, 'OK'); 25 | this.data = _.defaultTo(data, null); 26 | this.statusCode = Number(_.defaultTo(statusCode, 200)); 27 | } 28 | 29 | toObject() { 30 | return { 31 | code: this.code, 32 | message: this.message, 33 | data: this.data 34 | }; 35 | } 36 | 37 | static isInstance(value) { 38 | return value instanceof Body; 39 | } 40 | 41 | } 42 | -------------------------------------------------------------------------------- /src/index.ts: -------------------------------------------------------------------------------- 1 | "use strict"; 2 | 3 | import environment from "@/lib/environment.ts"; 4 | import config from "@/lib/config.ts"; 5 | import "@/lib/initialize.ts"; 6 | import server from "@/lib/server.ts"; 7 | import routes from "@/api/routes/index.ts"; 8 | import logger from "@/lib/logger.ts"; 9 | 10 | const startupTime = performance.now(); 11 | 12 | (async () => { 13 | logger.header(); 14 | 15 | logger.info("<<<< deepseek free server >>>>"); 16 | logger.info("Version:", environment.package.version); 17 | logger.info("Process id:", process.pid); 18 | logger.info("Environment:", environment.env); 19 | logger.info("Service name:", config.service.name); 20 | 21 | server.attachRoutes(routes); 22 | await server.listen(); 23 | 24 | config.service.bindAddress && 25 | logger.success("Service bind address:", config.service.bindAddress); 26 | })() 27 | .then(() => 28 | logger.success( 29 | `Service startup completed (${Math.floor(performance.now() - startupTime)}ms)` 30 | ) 31 | ) 32 | .catch((err) => console.error(err)); 33 | -------------------------------------------------------------------------------- /src/lib/exceptions/Exception.ts: -------------------------------------------------------------------------------- 1 | import assert from 'assert'; 2 | 3 | import _ from 'lodash'; 4 | 5 | export default class Exception extends Error { 6 | 7 | 8 | errcode: number; 9 | 10 | errmsg: string; 11 | 12 | data: any; 13 | 14 | httpStatusCode: number; 15 | 16 | 17 | constructor(exception: (string | number)[], _errmsg?: string) { 18 | assert(_.isArray(exception), 'Exception must be Array'); 19 | const [errcode, errmsg] = exception as [number, string]; 20 | assert(_.isFinite(errcode), 'Exception errcode invalid'); 21 | assert(_.isString(errmsg), 'Exception errmsg invalid'); 22 | super(_errmsg || errmsg); 23 | this.errcode = errcode; 24 | this.errmsg = _errmsg || errmsg; 25 | } 26 | 27 | compare(exception: (string | number)[]) { 28 | const [errcode] = exception as [number, string]; 29 | return this.errcode == errcode; 30 | } 31 | 32 | setHTTPStatusCode(value: number) { 33 | this.httpStatusCode = value; 34 | return this; 35 | } 36 | 37 | setData(value: any) { 38 | this.data = _.defaultTo(value, null); 39 | return this; 40 | } 41 | 42 | } 43 | -------------------------------------------------------------------------------- /src/lib/response/FailureBody.ts: -------------------------------------------------------------------------------- 1 | import _ from 'lodash'; 2 | 3 | import Body from './Body.ts'; 4 | import Exception from '../exceptions/Exception.ts'; 5 | import APIException from '../exceptions/APIException.ts'; 6 | import EX from '../consts/exceptions.ts'; 7 | import HTTP_STATUS_CODES from '../http-status-codes.ts'; 8 | 9 | export default class FailureBody extends Body { 10 | 11 | constructor(error: APIException | Exception | Error, _data?: any) { 12 | let errcode, errmsg, data = _data, httpStatusCode = HTTP_STATUS_CODES.OK;; 13 | if(_.isString(error)) 14 | error = new Exception(EX.SYSTEM_ERROR, error); 15 | else if(error instanceof APIException || error instanceof Exception) 16 | ({ errcode, errmsg, data, httpStatusCode } = error); 17 | else if(_.isError(error)) 18 | ({ errcode, errmsg, data, httpStatusCode } = new Exception(EX.SYSTEM_ERROR, error.message)); 19 | super({ 20 | code: errcode || -1, 21 | message: errmsg || 'Internal error', 22 | data, 23 | statusCode: httpStatusCode 24 | }); 25 | } 26 | 27 | static isInstance(value) { 28 | return value instanceof FailureBody; 29 | } 30 | 31 | } 32 | -------------------------------------------------------------------------------- /src/lib/environment.ts: -------------------------------------------------------------------------------- 1 | import path from 'path'; 2 | 3 | import fs from 'fs-extra'; 4 | import minimist from 'minimist'; 5 | import _ from 'lodash'; 6 | 7 | const cmdArgs = minimist(process.argv.slice(2)); 8 | const envVars = process.env; 9 | 10 | class Environment { 11 | 12 | 13 | cmdArgs: any; 14 | 15 | envVars: any; 16 | 17 | env?: string; 18 | 19 | name?: string; 20 | 21 | host?: string; 22 | 23 | port?: number; 24 | 25 | package: any; 26 | 27 | constructor(options: any = {}) { 28 | const { cmdArgs, envVars, package: _package } = options; 29 | this.cmdArgs = cmdArgs; 30 | this.envVars = envVars; 31 | this.env = _.defaultTo(cmdArgs.env || envVars.SERVER_ENV, 'dev'); 32 | this.name = cmdArgs.name || envVars.SERVER_NAME || undefined; 33 | this.host = cmdArgs.host || envVars.SERVER_HOST || undefined; 34 | this.port = Number(cmdArgs.port || envVars.SERVER_PORT) ? Number(cmdArgs.port || envVars.SERVER_PORT) : undefined; 35 | this.package = _package; 36 | } 37 | 38 | } 39 | 40 | export default new Environment({ 41 | cmdArgs, 42 | envVars, 43 | package: JSON.parse(fs.readFileSync(path.join(path.resolve(), "package.json")).toString()) 44 | }); 45 | -------------------------------------------------------------------------------- /.github/workflows/docker-image.yml: -------------------------------------------------------------------------------- 1 | name: Build and Push Docker Image 2 | 3 | on: 4 | release: 5 | types: [created] 6 | workflow_dispatch: 7 | inputs: 8 | tag: 9 | description: 'Tag Name' 10 | required: true 11 | 12 | jobs: 13 | build-and-push: 14 | runs-on: ubuntu-latest 15 | steps: 16 | - uses: actions/checkout@v2 17 | 18 | - name: Set up Docker Buildx 19 | uses: docker/setup-buildx-action@v1 20 | 21 | - name: Login to Docker Hub 22 | uses: docker/login-action@v1 23 | with: 24 | username: ${{ secrets.DOCKERHUB_USERNAME }} 25 | password: ${{ secrets.DOCKERHUB_PASSWORD }} 26 | 27 | - name: Set tag name 28 | id: tag_name 29 | run: | 30 | if [ "${{ github.event_name }}" = "release" ]; then 31 | echo "::set-output name=tag::${GITHUB_REF#refs/tags/}" 32 | elif [ "${{ github.event_name }}" = "workflow_dispatch" ]; then 33 | echo "::set-output name=tag::${{ github.event.inputs.tag }}" 34 | fi 35 | 36 | - name: Build and push Docker image with Release tag 37 | uses: docker/build-push-action@v2 38 | with: 39 | context: . 40 | file: ./Dockerfile 41 | push: true 42 | tags: | 43 | niansuh/deepseek-free-api:${{ steps.tag_name.outputs.tag }} 44 | niansuh/deepseek-free-api:latest 45 | platforms: linux/amd64,linux/arm64 46 | build-args: TARGETPLATFORM=${{ matrix.platform }} 47 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "deepseek-free-api", 3 | "version": "0.0.6", 4 | "description": "DeepSeek Free API Server", 5 | "type": "module", 6 | "main": "dist/index.js", 7 | "module": "dist/index.mjs", 8 | "types": "dist/index.d.ts", 9 | "directories": { 10 | "dist": "dist" 11 | }, 12 | "files": [ 13 | "dist/" 14 | ], 15 | "scripts": { 16 | "dev": "tsup src/index.ts --format cjs,esm --sourcemap --dts --publicDir public --watch --onSuccess \"node dist/index.js\"", 17 | "start": "node dist/index.js", 18 | "build": "tsup src/index.ts --format cjs,esm --sourcemap --dts --clean --publicDir public" 19 | }, 20 | "author": "Vinlic", 21 | "license": "ISC", 22 | "dependencies": { 23 | "@types/async-lock": "^1.4.2", 24 | "async-lock": "^1.4.1", 25 | "axios": "^1.6.7", 26 | "colors": "^1.4.0", 27 | "crc-32": "^1.2.2", 28 | "cron": "^3.1.6", 29 | "date-fns": "^3.3.1", 30 | "eventsource-parser": "^1.1.2", 31 | "fs-extra": "^11.2.0", 32 | "koa": "^2.15.0", 33 | "koa-body": "^5.0.0", 34 | "koa-bodyparser": "^4.4.1", 35 | "koa-range": "^0.3.0", 36 | "koa-router": "^12.0.1", 37 | "koa2-cors": "^2.0.6", 38 | "lodash": "^4.17.21", 39 | "mime": "^4.0.1", 40 | "minimist": "^1.2.8", 41 | "randomstring": "^1.3.0", 42 | "uuid": "^9.0.1", 43 | "yaml": "^2.3.4" 44 | }, 45 | "devDependencies": { 46 | "@types/lodash": "^4.14.202", 47 | "@types/mime": "^3.0.4", 48 | "tsup": "^8.0.2", 49 | "typescript": "^5.3.3" 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /.github/workflows/sync.yml: -------------------------------------------------------------------------------- 1 | name: Upstream Sync 2 | 3 | permissions: 4 | contents: write 5 | issues: write 6 | actions: write 7 | 8 | on: 9 | schedule: 10 | - cron: '0 * * * *' # every hour 11 | workflow_dispatch: 12 | 13 | jobs: 14 | sync_latest_from_upstream: 15 | name: Sync latest commits from upstream repo 16 | runs-on: ubuntu-latest 17 | if: ${{ github.event.repository.fork }} 18 | 19 | steps: 20 | - uses: actions/checkout@v4 21 | 22 | - name: Clean issue notice 23 | uses: actions-cool/issues-helper@v3 24 | with: 25 | actions: 'close-issues' 26 | labels: '🚨 Sync Fail' 27 | 28 | - name: Sync upstream changes 29 | id: sync 30 | uses: aormsby/Fork-Sync-With-Upstream-action@v3.4 31 | with: 32 | upstream_sync_repo: Niansuh/deepseek-free-api 33 | upstream_sync_branch: master 34 | target_sync_branch: master 35 | target_repo_token: ${{ secrets.GITHUB_TOKEN }} # automatically generated, no need to set 36 | test_mode: false 37 | 38 | - name: Sync check 39 | if: failure() 40 | uses: actions-cool/issues-helper@v3 41 | with: 42 | actions: 'create-issue' 43 | title: '🚨 Sync Fail' 44 | labels: '🚨 Sync Fail' 45 | body: | 46 | Due to a change in the workflow file of the Niansuh/deepseek-free-api upstream repository, GitHub has automatically suspended the scheduled automatic update. You need to manually sync your fork. Please refer to the detailed [Tutorial][tutorial-en-US] for instructions. 47 | -------------------------------------------------------------------------------- /src/api/routes/chat.ts: -------------------------------------------------------------------------------- 1 | import _ from 'lodash'; 2 | 3 | import Request from '@/lib/request/Request.ts'; 4 | import Response from '@/lib/response/Response.ts'; 5 | import chat from '@/api/controllers/chat.ts'; 6 | 7 | export default { 8 | 9 | prefix: '/nai/v1/chat', 10 | 11 | post: { 12 | 13 | '/completions': async (request: Request) => { 14 | request 15 | .validate('body.conversation_id', v => _.isUndefined(v) || _.isString(v)) 16 | .validate('body.messages', _.isArray) 17 | .validate('headers.authorization', _.isString) 18 | 19 | const tokens = chat.tokenSplit(request.headers.authorization); 20 | 21 | const token = _.sample(tokens); 22 | let { model, messages, stream } = request.body; 23 | if(['deepseek_chat', 'deepseek_code', 'deepseek-chat*', 'deepseek-chat', 'deepseek-coder'].includes(model)) 24 | model = { 25 | 'deepseek-chat*': 'deepseek_chat', 26 | 'deepseek-chat': 'deepseek_chat', 27 | 'deepseek-coder': 'deepseek_code' 28 | }[model] || model; 29 | else 30 | model = 'deepseek_chat'; 31 | if (stream) { 32 | const stream = await chat.createCompletionStream(model, messages, token); 33 | return new Response(stream, { 34 | type: "text/event-stream" 35 | }); 36 | } 37 | else 38 | return await chat.createCompletion(model, messages, token); 39 | } 40 | 41 | } 42 | 43 | } 44 | -------------------------------------------------------------------------------- /src/lib/http-status-codes.ts: -------------------------------------------------------------------------------- 1 | export default { 2 | 3 | CONTINUE: 100, 4 | SWITCHING_PROTOCOLS: 101, 5 | PROCESSING: 102, 6 | 7 | OK: 200, 8 | CREATED: 201, 9 | ACCEPTED: 202, 10 | NON_AUTHORITATIVE_INFO: 203, 11 | NO_CONTENT: 204, 12 | RESET_CONTENT: 205, 13 | PARTIAL_CONTENT: 206, 14 | MULTIPLE_STATUS: 207, 15 | 16 | MULTIPLE_CHOICES: 300, 17 | MOVED_PERMANENTLY: 301, 18 | FOUND: 302, 19 | SEE_OTHER: 303, 20 | NOT_MODIFIED: 304, 21 | USE_PROXY: 305, 22 | UNUSED: 306, 23 | TEMPORARY_REDIRECT: 307, 24 | 25 | BAD_REQUEST: 400, 26 | UNAUTHORIZED: 401, 27 | PAYMENT_REQUIRED: 402, 28 | FORBIDDEN: 403, 29 | NOT_FOUND: 404, 30 | METHOD_NOT_ALLOWED: 405, 31 | NO_ACCEPTABLE: 406, 32 | PROXY_AUTHENTICATION_REQUIRED: 407, 33 | REQUEST_TIMEOUT: 408, 34 | CONFLICT: 409, 35 | GONE: 410, 36 | LENGTH_REQUIRED: 411, 37 | PRECONDITION_FAILED: 412, 38 | REQUEST_ENTITY_TOO_LARGE: 413, 39 | REQUEST_URI_TOO_LONG: 414, 40 | UNSUPPORTED_MEDIA_TYPE: 415, 41 | REQUESTED_RANGE_NOT_SATISFIABLE: 416, 42 | EXPECTION_FAILED: 417, 43 | TOO_MANY_CONNECTIONS: 421, 44 | UNPROCESSABLE_ENTITY: 422, 45 | FAILED_DEPENDENCY: 424, 46 | UNORDERED_COLLECTION: 425, 47 | UPGRADE_REQUIRED: 426, 48 | RETRY_WITH: 449, 49 | 50 | INTERNAL_SERVER_ERROR: 500, 51 | NOT_IMPLEMENTED: 501, 52 | BAD_GATEWAY: 502, 53 | SERVICE_UNAVAILABLE: 503, 54 | GATEWAY_TIMEOUT: 504, 55 | HTTP_VERSION_NOT_SUPPORTED: 505, 56 | VARIANT_ALSO_NEGOTIATES: 506, 57 | INSUFFICIENT_STORAGE: 507, 58 | BANDWIDTH_LIMIT_EXCEEDED: 509, 59 | NOT_EXTENDED: 510 60 | 61 | }; 62 | -------------------------------------------------------------------------------- /src/lib/response/Response.ts: -------------------------------------------------------------------------------- 1 | import mime from 'mime'; 2 | import _ from 'lodash'; 3 | 4 | import Body from './Body.ts'; 5 | import util from '../util.ts'; 6 | 7 | export interface ResponseOptions { 8 | statusCode?: number; 9 | type?: string; 10 | headers?: Record; 11 | redirect?: string; 12 | body?: any; 13 | size?: number; 14 | time?: number; 15 | } 16 | 17 | export default class Response { 18 | 19 | 20 | statusCode: number; 21 | 22 | type: string; 23 | 24 | headers: Record; 25 | 26 | redirect: string; 27 | 28 | body: any; 29 | 30 | size: number; 31 | 32 | time: number; 33 | 34 | constructor(body: any, options: ResponseOptions = {}) { 35 | const { statusCode, type, headers, redirect, size, time } = options; 36 | this.statusCode = Number(_.defaultTo(statusCode, Body.isInstance(body) ? body.statusCode : undefined)) 37 | this.type = type; 38 | this.headers = headers; 39 | this.redirect = redirect; 40 | this.size = size; 41 | this.time = Number(_.defaultTo(time, util.timestamp())); 42 | this.body = body; 43 | } 44 | 45 | injectTo(ctx) { 46 | this.redirect && ctx.redirect(this.redirect); 47 | this.statusCode && (ctx.status = this.statusCode); 48 | this.type && (ctx.type = mime.getType(this.type) || this.type); 49 | const headers = this.headers || {}; 50 | if(this.size && !headers["Content-Length"] && !headers["content-length"]) 51 | headers["Content-Length"] = this.size; 52 | ctx.set(headers); 53 | if(Body.isInstance(this.body)) 54 | ctx.body = this.body.toObject(); 55 | else 56 | ctx.body = this.body; 57 | } 58 | 59 | static isInstance(value) { 60 | return value instanceof Response; 61 | } 62 | 63 | } 64 | -------------------------------------------------------------------------------- /src/lib/configs/service-config.ts: -------------------------------------------------------------------------------- 1 | import path from 'path'; 2 | 3 | import fs from 'fs-extra'; 4 | import yaml from 'yaml'; 5 | import _ from 'lodash'; 6 | 7 | import environment from '../environment.ts'; 8 | import util from '../util.ts'; 9 | 10 | const CONFIG_PATH = path.join(path.resolve(), 'configs/', environment.env, "/service.yml"); 11 | 12 | 13 | export class ServiceConfig { 14 | 15 | 16 | name: string; 17 | 18 | host; 19 | 20 | port; 21 | 22 | urlPrefix; 23 | 24 | bindAddress; 25 | 26 | constructor(options?: any) { 27 | const { name, host, port, urlPrefix, bindAddress } = options || {}; 28 | this.name = _.defaultTo(name, 'deepseek-free-api'); 29 | this.host = _.defaultTo(host, '0.0.0.0'); 30 | this.port = _.defaultTo(port, 5566); 31 | this.urlPrefix = _.defaultTo(urlPrefix, ''); 32 | this.bindAddress = bindAddress; 33 | } 34 | 35 | get addressHost() { 36 | if(this.bindAddress) return this.bindAddress; 37 | const ipAddresses = util.getIPAddressesByIPv4(); 38 | for(let ipAddress of ipAddresses) { 39 | if(ipAddress === this.host) 40 | return ipAddress; 41 | } 42 | return ipAddresses[0] || "127.0.0.1"; 43 | } 44 | 45 | get address() { 46 | return `${this.addressHost}:${this.port}`; 47 | } 48 | 49 | get pageDirUrl() { 50 | return `http://127.0.0.1:${this.port}/page`; 51 | } 52 | 53 | get publicDirUrl() { 54 | return `http://127.0.0.1:${this.port}/public`; 55 | } 56 | 57 | static load() { 58 | const external = _.pickBy(environment, (v, k) => ["name", "host", "port"].includes(k) && !_.isUndefined(v)); 59 | if(!fs.pathExistsSync(CONFIG_PATH)) return new ServiceConfig(external); 60 | const data = yaml.parse(fs.readFileSync(CONFIG_PATH).toString()); 61 | return new ServiceConfig({ ...data, ...external }); 62 | } 63 | 64 | } 65 | 66 | export default ServiceConfig.load(); 67 | -------------------------------------------------------------------------------- /src/lib/request/Request.ts: -------------------------------------------------------------------------------- 1 | import _ from 'lodash'; 2 | 3 | import APIException from '@/lib/exceptions/APIException.ts'; 4 | import EX from '@/api/consts/exceptions.ts'; 5 | import logger from '@/lib/logger.ts'; 6 | import util from '@/lib/util.ts'; 7 | 8 | export interface RequestOptions { 9 | time?: number; 10 | } 11 | 12 | export default class Request { 13 | 14 | 15 | method: string; 16 | 17 | url: string; 18 | 19 | path: string; 20 | 21 | type: string; 22 | 23 | headers: any; 24 | 25 | search: string; 26 | 27 | query: any; 28 | 29 | params: any; 30 | 31 | body: any; 32 | 33 | files: any[]; 34 | 35 | remoteIP: string | null; 36 | 37 | time: number; 38 | 39 | constructor(ctx, options: RequestOptions = {}) { 40 | const { time } = options; 41 | this.method = ctx.request.method; 42 | this.url = ctx.request.url; 43 | this.path = ctx.request.path; 44 | this.type = ctx.request.type; 45 | this.headers = ctx.request.headers || {}; 46 | this.search = ctx.request.search; 47 | this.query = ctx.query || {}; 48 | this.params = ctx.params || {}; 49 | this.body = ctx.request.body || {}; 50 | this.files = ctx.request.files || {}; 51 | this.remoteIP = this.headers["X-Real-IP"] || this.headers["x-real-ip"] || this.headers["X-Forwarded-For"] || this.headers["x-forwarded-for"] || ctx.ip || null; 52 | this.time = Number(_.defaultTo(time, util.timestamp())); 53 | } 54 | 55 | validate(key: string, fn?: Function) { 56 | try { 57 | const value = _.get(this, key); 58 | if (fn) { 59 | if (fn(value) === false) 60 | throw `[Mismatch] -> ${fn}`; 61 | } 62 | else if (_.isUndefined(value)) 63 | throw '[Undefined]'; 64 | } 65 | catch (err) { 66 | logger.warn(`Params ${key} invalid:`, err); 67 | throw new APIException(EX.API_REQUEST_PARAMS_INVALID, `Params ${key} invalid`); 68 | } 69 | return this; 70 | } 71 | 72 | } 73 | -------------------------------------------------------------------------------- /src/lib/configs/system-config.ts: -------------------------------------------------------------------------------- 1 | import path from 'path'; 2 | 3 | import fs from 'fs-extra'; 4 | import yaml from 'yaml'; 5 | import _ from 'lodash'; 6 | 7 | import environment from '../environment.ts'; 8 | 9 | const CONFIG_PATH = path.join(path.resolve(), 'configs/', environment.env, "/system.yml"); 10 | 11 | 12 | export class SystemConfig { 13 | 14 | 15 | requestLog: boolean; 16 | 17 | tmpDir: string; 18 | 19 | logDir: string; 20 | 21 | logWriteInterval: number; 22 | 23 | logFileExpires: number; 24 | 25 | publicDir: string; 26 | 27 | tmpFileExpires: number; 28 | 29 | requestBody: any; 30 | 31 | debug: boolean; 32 | 33 | constructor(options?: any) { 34 | const { requestLog, tmpDir, logDir, logWriteInterval, logFileExpires, publicDir, tmpFileExpires, requestBody, debug } = options || {}; 35 | this.requestLog = _.defaultTo(requestLog, false); 36 | this.tmpDir = _.defaultTo(tmpDir, './tmp'); 37 | this.logDir = _.defaultTo(logDir, './logs'); 38 | this.logWriteInterval = _.defaultTo(logWriteInterval, 200); 39 | this.logFileExpires = _.defaultTo(logFileExpires, 2626560000); 40 | this.publicDir = _.defaultTo(publicDir, './public'); 41 | this.tmpFileExpires = _.defaultTo(tmpFileExpires, 86400000); 42 | this.requestBody = Object.assign(requestBody || {}, { 43 | enableTypes: ['json', 'form', 'text', 'xml'], 44 | encoding: 'utf-8', 45 | formLimit: '100mb', 46 | jsonLimit: '100mb', 47 | textLimit: '100mb', 48 | xmlLimit: '100mb', 49 | formidable: { 50 | maxFileSize: '100mb' 51 | }, 52 | multipart: true, 53 | parsedMethods: ['POST', 'PUT', 'PATCH'] 54 | }); 55 | this.debug = _.defaultTo(debug, true); 56 | } 57 | 58 | get rootDirPath() { 59 | return path.resolve(); 60 | } 61 | 62 | get tmpDirPath() { 63 | return path.resolve(this.tmpDir); 64 | } 65 | 66 | get logDirPath() { 67 | return path.resolve(this.logDir); 68 | } 69 | 70 | get publicDirPath() { 71 | return path.resolve(this.publicDir); 72 | } 73 | 74 | static load() { 75 | if (!fs.pathExistsSync(CONFIG_PATH)) return new SystemConfig(); 76 | const data = yaml.parse(fs.readFileSync(CONFIG_PATH).toString()); 77 | return new SystemConfig(data); 78 | } 79 | 80 | } 81 | 82 | export default SystemConfig.load(); 83 | -------------------------------------------------------------------------------- /src/daemon.ts: -------------------------------------------------------------------------------- 1 | import process from 'process'; 2 | import path from 'path'; 3 | import { spawn } from 'child_process'; 4 | 5 | import fs from 'fs-extra'; 6 | import { format as dateFormat } from 'date-fns'; 7 | import 'colors'; 8 | 9 | const CRASH_RESTART_LIMIT = 600; 10 | const CRASH_RESTART_DELAY = 5000; 11 | const LOG_PATH = path.resolve("./logs/daemon.log"); 12 | let crashCount = 0; 13 | let currentProcess; 14 | 15 | 16 | function daemonLog(value, color?: string) { 17 | try { 18 | const head = `[daemon][${dateFormat(new Date(), "yyyy-MM-dd HH:mm:ss.SSS")}] `; 19 | value = head + value; 20 | console.log(color ? value[color] : value); 21 | fs.ensureDirSync(path.dirname(LOG_PATH)); 22 | fs.appendFileSync(LOG_PATH, value + "\n"); 23 | } 24 | catch(err) { 25 | console.error("daemon log write error:", err); 26 | } 27 | } 28 | 29 | daemonLog(`daemon pid: ${process.pid}`); 30 | 31 | function createProcess() { 32 | const childProcess = spawn("node", ["index.js", ...process.argv.slice(2)]); 33 | childProcess.stdout.pipe(process.stdout, { end: false }); 34 | childProcess.stderr.pipe(process.stderr, { end: false }); 35 | currentProcess = childProcess; 36 | daemonLog(`process(${childProcess.pid}) has started`); 37 | childProcess.on("error", err => daemonLog(`process(${childProcess.pid}) error: ${err.stack}`, "red")); 38 | childProcess.on("close", code => { 39 | if(code === 0) 40 | daemonLog(`process(${childProcess.pid}) has exited`); 41 | else if(code === 2) 42 | daemonLog(`process(${childProcess.pid}) has been killed!`, "bgYellow"); 43 | else if(code === 3) { 44 | daemonLog(`process(${childProcess.pid}) has restart`, "yellow"); 45 | createProcess(); 46 | } 47 | else { 48 | if(crashCount++ < CRASH_RESTART_LIMIT) { 49 | daemonLog(`process(${childProcess.pid}) has crashed! delay ${CRASH_RESTART_DELAY}ms try restarting...(${crashCount})`, "bgRed"); 50 | setTimeout(() => createProcess(), CRASH_RESTART_DELAY); 51 | } 52 | else 53 | daemonLog(`process(${childProcess.pid}) has crashed! unable to restart`, "bgRed"); 54 | } 55 | }); 56 | } 57 | 58 | process.on("exit", code => { 59 | if(code === 0) 60 | daemonLog("daemon process exited"); 61 | else if(code === 2) 62 | daemonLog("daemon process has been killed!"); 63 | }); 64 | 65 | process.on("SIGTERM", () => { 66 | daemonLog("received kill signal", "yellow"); 67 | currentProcess && currentProcess.kill("SIGINT"); 68 | process.exit(2); 69 | }); 70 | 71 | process.on("SIGINT", () => { 72 | currentProcess && currentProcess.kill("SIGINT"); 73 | process.exit(0); 74 | }); 75 | 76 | createProcess(); 77 | -------------------------------------------------------------------------------- /src/lib/logger.ts: -------------------------------------------------------------------------------- 1 | import path from 'path'; 2 | import _util from 'util'; 3 | 4 | import 'colors'; 5 | import _ from 'lodash'; 6 | import fs from 'fs-extra'; 7 | import { format as dateFormat } from 'date-fns'; 8 | 9 | import config from './config.ts'; 10 | import util from './util.ts'; 11 | 12 | const isVercelEnv = process.env.VERCEL; 13 | 14 | class LogWriter { 15 | 16 | #buffers = []; 17 | 18 | constructor() { 19 | !isVercelEnv && fs.ensureDirSync(config.system.logDirPath); 20 | !isVercelEnv && this.work(); 21 | } 22 | 23 | push(content) { 24 | const buffer = Buffer.from(content); 25 | this.#buffers.push(buffer); 26 | } 27 | 28 | writeSync(buffer) { 29 | !isVercelEnv && fs.appendFileSync(path.join(config.system.logDirPath, `/${util.getDateString()}.log`), buffer); 30 | } 31 | 32 | async write(buffer) { 33 | !isVercelEnv && await fs.appendFile(path.join(config.system.logDirPath, `/${util.getDateString()}.log`), buffer); 34 | } 35 | 36 | flush() { 37 | if(!this.#buffers.length) return; 38 | !isVercelEnv && fs.appendFileSync(path.join(config.system.logDirPath, `/${util.getDateString()}.log`), Buffer.concat(this.#buffers)); 39 | } 40 | 41 | work() { 42 | if (!this.#buffers.length) return setTimeout(this.work.bind(this), config.system.logWriteInterval); 43 | const buffer = Buffer.concat(this.#buffers); 44 | this.#buffers = []; 45 | this.write(buffer) 46 | .finally(() => setTimeout(this.work.bind(this), config.system.logWriteInterval)) 47 | .catch(err => console.error("Log write error:", err)); 48 | } 49 | 50 | } 51 | 52 | class LogText { 53 | 54 | 55 | level; 56 | 57 | text; 58 | 59 | source; 60 | 61 | time = new Date(); 62 | 63 | constructor(level, ...params) { 64 | this.level = level; 65 | this.text = _util.format.apply(null, params); 66 | this.source = this.#getStackTopCodeInfo(); 67 | } 68 | 69 | #getStackTopCodeInfo() { 70 | const unknownInfo = { name: "unknown", codeLine: 0, codeColumn: 0 }; 71 | const stackArray = new Error().stack.split("\n"); 72 | const text = stackArray[4]; 73 | if (!text) 74 | return unknownInfo; 75 | const match = text.match(/at (.+) \((.+)\)/) || text.match(/at (.+)/); 76 | if (!match || !_.isString(match[2] || match[1])) 77 | return unknownInfo; 78 | const temp = match[2] || match[1]; 79 | const _match = temp.match(/([a-zA-Z0-9_\-\.]+)\:(\d+)\:(\d+)$/); 80 | if (!_match) 81 | return unknownInfo; 82 | const [, scriptPath, codeLine, codeColumn] = _match as any; 83 | return { 84 | name: scriptPath ? scriptPath.replace(/.js$/, "") : "unknown", 85 | path: scriptPath || null, 86 | codeLine: parseInt(codeLine || 0), 87 | codeColumn: parseInt(codeColumn || 0) 88 | }; 89 | } 90 | 91 | toString() { 92 | return `[${dateFormat(this.time, "yyyy-MM-dd HH:mm:ss.SSS")}][${this.level}][${this.source.name}<${this.source.codeLine},${this.source.codeColumn}>] ${this.text}`; 93 | } 94 | 95 | } 96 | 97 | class Logger { 98 | 99 | 100 | config = {}; 101 | 102 | static Level = { 103 | Success: "success", 104 | Info: "info", 105 | Log: "log", 106 | Debug: "debug", 107 | Warning: "warning", 108 | Error: "error", 109 | Fatal: "fatal" 110 | }; 111 | 112 | static LevelColor = { 113 | [Logger.Level.Success]: "green", 114 | [Logger.Level.Info]: "brightCyan", 115 | [Logger.Level.Debug]: "white", 116 | [Logger.Level.Warning]: "brightYellow", 117 | [Logger.Level.Error]: "brightRed", 118 | [Logger.Level.Fatal]: "red" 119 | }; 120 | #writer; 121 | 122 | constructor() { 123 | this.#writer = new LogWriter(); 124 | } 125 | 126 | header() { 127 | this.#writer.writeSync(Buffer.from(`\n\n===================== LOG START ${dateFormat(new Date(), "yyyy-MM-dd HH:mm:ss.SSS")} =====================\n\n`)); 128 | } 129 | 130 | footer() { 131 | this.#writer.flush(); 132 | this.#writer.writeSync(Buffer.from(`\n\n===================== LOG END ${dateFormat(new Date(), "yyyy-MM-dd HH:mm:ss.SSS")} =====================\n\n`)); 133 | } 134 | 135 | success(...params) { 136 | const content = new LogText(Logger.Level.Success, ...params).toString(); 137 | console.info(content[Logger.LevelColor[Logger.Level.Success]]); 138 | this.#writer.push(content + "\n"); 139 | } 140 | 141 | info(...params) { 142 | const content = new LogText(Logger.Level.Info, ...params).toString(); 143 | console.info(content[Logger.LevelColor[Logger.Level.Info]]); 144 | this.#writer.push(content + "\n"); 145 | } 146 | 147 | log(...params) { 148 | const content = new LogText(Logger.Level.Log, ...params).toString(); 149 | console.log(content[Logger.LevelColor[Logger.Level.Log]]); 150 | this.#writer.push(content + "\n"); 151 | } 152 | 153 | debug(...params) { 154 | if(!config.system.debug) return; 155 | const content = new LogText(Logger.Level.Debug, ...params).toString(); 156 | console.debug(content[Logger.LevelColor[Logger.Level.Debug]]); 157 | this.#writer.push(content + "\n"); 158 | } 159 | 160 | warn(...params) { 161 | const content = new LogText(Logger.Level.Warning, ...params).toString(); 162 | console.warn(content[Logger.LevelColor[Logger.Level.Warning]]); 163 | this.#writer.push(content + "\n"); 164 | } 165 | 166 | error(...params) { 167 | const content = new LogText(Logger.Level.Error, ...params).toString(); 168 | console.error(content[Logger.LevelColor[Logger.Level.Error]]); 169 | this.#writer.push(content); 170 | } 171 | 172 | fatal(...params) { 173 | const content = new LogText(Logger.Level.Fatal, ...params).toString(); 174 | console.error(content[Logger.LevelColor[Logger.Level.Fatal]]); 175 | this.#writer.push(content); 176 | } 177 | 178 | destory() { 179 | this.#writer.destory(); 180 | } 181 | 182 | } 183 | 184 | export default new Logger(); 185 | -------------------------------------------------------------------------------- /src/lib/server.ts: -------------------------------------------------------------------------------- 1 | import Koa from 'koa'; 2 | import KoaRouter from 'koa-router'; 3 | import koaRange from 'koa-range'; 4 | import koaCors from "koa2-cors"; 5 | import koaBody from 'koa-body'; 6 | import _ from 'lodash'; 7 | 8 | import Exception from './exceptions/Exception.ts'; 9 | import Request from './request/Request.ts'; 10 | import Response from './response/Response.js'; 11 | import FailureBody from './response/FailureBody.ts'; 12 | import EX from './consts/exceptions.ts'; 13 | import logger from './logger.ts'; 14 | import config from './config.ts'; 15 | 16 | class Server { 17 | 18 | app; 19 | router; 20 | 21 | constructor() { 22 | this.app = new Koa(); 23 | this.app.use(koaCors()); 24 | 25 | this.app.use(koaRange); 26 | this.router = new KoaRouter({ prefix: config.service.urlPrefix }); 27 | 28 | this.app.use(async (ctx: any, next: Function) => { 29 | if(ctx.request.type === "application/xml" || ctx.request.type === "application/ssml+xml") 30 | ctx.req.headers["content-type"] = "text/xml"; 31 | try { await next() } 32 | catch (err) { 33 | logger.error(err); 34 | const failureBody = new FailureBody(err); 35 | new Response(failureBody).injectTo(ctx); 36 | } 37 | }); 38 | 39 | this.app.use(koaBody(_.clone(config.system.requestBody))); 40 | this.app.on("error", (err: any) => { 41 | 42 | if (["ECONNRESET", "ECONNABORTED", "EPIPE", "ECANCELED"].includes(err.code)) return; 43 | logger.error(err); 44 | }); 45 | logger.success("Server initialized"); 46 | } 47 | 48 | 49 | attachRoutes(routes: any[]) { 50 | routes.forEach((route: any) => { 51 | const prefix = route.prefix || ""; 52 | for (let method in route) { 53 | if(method === "prefix") continue; 54 | if (!_.isObject(route[method])) { 55 | logger.warn(`Router ${prefix} ${method} invalid`); 56 | continue; 57 | } 58 | for (let uri in route[method]) { 59 | this.router[method](`${prefix}${uri}`, async ctx => { 60 | const { request, response } = await this.#requestProcessing(ctx, route[method][uri]); 61 | if(response != null && config.system.requestLog) 62 | logger.info(`<- ${request.method} ${request.url} ${response.time - request.time}ms`); 63 | }); 64 | } 65 | } 66 | logger.info(`Route ${config.service.urlPrefix || ""}${prefix} attached`); 67 | }); 68 | this.app.use(this.router.routes()); 69 | this.app.use((ctx: any) => { 70 | const request = new Request(ctx); 71 | logger.debug(`-> ${ctx.request.method} ${ctx.request.url} request is not supported - ${request.remoteIP || "unknown"}`); 72 | // const failureBody = new FailureBody(new Exception(EX.SYSTEM_NOT_ROUTE_MATCHING, "Request is not supported")); 73 | // const response = new Response(failureBody); 74 | const message = `[Incorrect request]: The correct request is POST -> /nai/v1/chat/completions, and the current request is ${ctx.request.method} -> ${ctx.request.url} please correct`; 75 | logger.warn(message); 76 | const failureBody = new FailureBody(new Error(message)); 77 | const response = new Response(failureBody); 78 | response.injectTo(ctx); 79 | if(config.system.requestLog) 80 | logger.info(`<- ${request.method} ${request.url} ${response.time - request.time}ms`); 81 | }); 82 | } 83 | 84 | 85 | #requestProcessing(ctx: any, routeFn: Function): Promise { 86 | return new Promise(resolve => { 87 | const request = new Request(ctx); 88 | try { 89 | if(config.system.requestLog) 90 | logger.info(`-> ${request.method} ${request.url}`); 91 | routeFn(request) 92 | .then(response => { 93 | try { 94 | if(!Response.isInstance(response)) { 95 | const _response = new Response(response); 96 | _response.injectTo(ctx); 97 | return resolve({ request, response: _response }); 98 | } 99 | response.injectTo(ctx); 100 | resolve({ request, response }); 101 | } 102 | catch(err) { 103 | logger.error(err); 104 | const failureBody = new FailureBody(err); 105 | const response = new Response(failureBody); 106 | response.injectTo(ctx); 107 | resolve({ request, response }); 108 | } 109 | }) 110 | .catch(err => { 111 | try { 112 | logger.error(err); 113 | const failureBody = new FailureBody(err); 114 | const response = new Response(failureBody); 115 | response.injectTo(ctx); 116 | resolve({ request, response }); 117 | } 118 | catch(err) { 119 | logger.error(err); 120 | const failureBody = new FailureBody(err); 121 | const response = new Response(failureBody); 122 | response.injectTo(ctx); 123 | resolve({ request, response }); 124 | } 125 | }); 126 | } 127 | catch(err) { 128 | logger.error(err); 129 | const failureBody = new FailureBody(err); 130 | const response = new Response(failureBody); 131 | response.injectTo(ctx); 132 | resolve({ request, response }); 133 | } 134 | }); 135 | } 136 | 137 | 138 | async listen() { 139 | const host = config.service.host; 140 | const port = config.service.port; 141 | await Promise.all([ 142 | new Promise((resolve, reject) => { 143 | if(host === "0.0.0.0" || host === "localhost" || host === "127.0.0.1") 144 | return resolve(null); 145 | this.app.listen(port, "localhost", err => { 146 | if(err) return reject(err); 147 | resolve(null); 148 | }); 149 | }), 150 | new Promise((resolve, reject) => { 151 | this.app.listen(port, host, err => { 152 | if(err) return reject(err); 153 | resolve(null); 154 | }); 155 | }) 156 | ]); 157 | logger.success(`Server listening on port ${port} (${host})`); 158 | } 159 | 160 | } 161 | 162 | export default new Server(); 163 | -------------------------------------------------------------------------------- /src/lib/util.ts: -------------------------------------------------------------------------------- 1 | import os from "os"; 2 | import path from "path"; 3 | import crypto from "crypto"; 4 | import { Readable, Writable } from "stream"; 5 | 6 | import "colors"; 7 | import mime from "mime"; 8 | import axios from "axios"; 9 | import fs from "fs-extra"; 10 | import { v1 as uuid } from "uuid"; 11 | import { format as dateFormat } from "date-fns"; 12 | import CRC32 from "crc-32"; 13 | import randomstring from "randomstring"; 14 | import _ from "lodash"; 15 | import { CronJob } from "cron"; 16 | 17 | import HTTP_STATUS_CODE from "./http-status-codes.ts"; 18 | 19 | const autoIdMap = new Map(); 20 | 21 | const util = { 22 | is2DArrays(value: any) { 23 | return ( 24 | _.isArray(value) && 25 | (!value[0] || (_.isArray(value[0]) && _.isArray(value[value.length - 1]))) 26 | ); 27 | }, 28 | 29 | uuid: (separator = true) => (separator ? uuid() : uuid().replace(/\-/g, "")), 30 | 31 | autoId: (prefix = "") => { 32 | let index = autoIdMap.get(prefix); 33 | if (index > 999999) index = 0; 34 | autoIdMap.set(prefix, (index || 0) + 1); 35 | return `${prefix}${index || 1}`; 36 | }, 37 | 38 | ignoreJSONParse(value: string) { 39 | const result = _.attempt(() => JSON.parse(value)); 40 | if (_.isError(result)) return null; 41 | return result; 42 | }, 43 | 44 | generateRandomString(options: any): string { 45 | return randomstring.generate(options); 46 | }, 47 | 48 | getResponseContentType(value: any): string | null { 49 | return value.headers 50 | ? value.headers["content-type"] || value.headers["Content-Type"] 51 | : null; 52 | }, 53 | 54 | mimeToExtension(value: string) { 55 | let extension = mime.getExtension(value); 56 | if (extension == "mpga") return "mp3"; 57 | return extension; 58 | }, 59 | 60 | extractURLExtension(value: string) { 61 | const extname = path.extname(new URL(value).pathname); 62 | return extname.substring(1).toLowerCase(); 63 | }, 64 | 65 | createCronJob(cronPatterns: any, callback?: Function) { 66 | if (!_.isFunction(callback)) 67 | throw new Error("callback must be an Function"); 68 | return new CronJob( 69 | cronPatterns, 70 | () => callback(), 71 | null, 72 | false, 73 | "Asia/Shanghai" 74 | ); 75 | }, 76 | 77 | getDateString(format = "yyyy-MM-dd", date = new Date()) { 78 | return dateFormat(date, format); 79 | }, 80 | 81 | getIPAddressesByIPv4(): string[] { 82 | const interfaces = os.networkInterfaces(); 83 | const addresses = []; 84 | for (let name in interfaces) { 85 | const networks = interfaces[name]; 86 | const results = networks.filter( 87 | (network) => 88 | network.family === "IPv4" && 89 | network.address !== "127.0.0.1" && 90 | !network.internal 91 | ); 92 | if (results[0] && results[0].address) addresses.push(results[0].address); 93 | } 94 | return addresses; 95 | }, 96 | 97 | getMACAddressesByIPv4(): string[] { 98 | const interfaces = os.networkInterfaces(); 99 | const addresses = []; 100 | for (let name in interfaces) { 101 | const networks = interfaces[name]; 102 | const results = networks.filter( 103 | (network) => 104 | network.family === "IPv4" && 105 | network.address !== "127.0.0.1" && 106 | !network.internal 107 | ); 108 | if (results[0] && results[0].mac) addresses.push(results[0].mac); 109 | } 110 | return addresses; 111 | }, 112 | 113 | generateSSEData(event?: string, data?: string, retry?: number) { 114 | return `event: ${event || "message"}\ndata: ${(data || "") 115 | .replace(/\n/g, "\\n") 116 | .replace(/\s/g, "\\s")}\nretry: ${retry || 3000}\n\n`; 117 | }, 118 | 119 | buildDataBASE64(type, ext, buffer) { 120 | return `data:${type}/${ext.replace("jpg", "jpeg")};base64,${buffer.toString( 121 | "base64" 122 | )}`; 123 | }, 124 | 125 | isLinux() { 126 | return os.platform() !== "win32"; 127 | }, 128 | 129 | isIPAddress(value) { 130 | return ( 131 | _.isString(value) && 132 | (/^((2[0-4]\d|25[0-5]|[01]?\d\d?)\.){3}(2[0-4]\d|25[0-5]|[01]?\d\d?)$/.test( 133 | value 134 | ) || 135 | /\s*((([0-9A-Fa-f]{1,4}:){7}([0-9A-Fa-f]{1,4}|:))|(([0-9A-Fa-f]{1,4}:){6}(:[0-9A-Fa-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){5}(((:[0-9A-Fa-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){4}(((:[0-9A-Fa-f]{1,4}){1,3})|((:[0-9A-Fa-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){3}(((:[0-9A-Fa-f]{1,4}){1,4})|((:[0-9A-Fa-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){2}(((:[0-9A-Fa-f]{1,4}){1,5})|((:[0-9A-Fa-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){1}(((:[0-9A-Fa-f]{1,4}){1,6})|((:[0-9A-Fa-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9A-Fa-f]{1,4}){1,7})|((:[0-9A-Fa-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))(%.+)?\s*/.test( 136 | value 137 | )) 138 | ); 139 | }, 140 | 141 | isPort(value) { 142 | return _.isNumber(value) && value > 0 && value < 65536; 143 | }, 144 | 145 | isReadStream(value): boolean { 146 | return ( 147 | value && 148 | (value instanceof Readable || "readable" in value || value.readable) 149 | ); 150 | }, 151 | 152 | isWriteStream(value): boolean { 153 | return ( 154 | value && 155 | (value instanceof Writable || "writable" in value || value.writable) 156 | ); 157 | }, 158 | 159 | isHttpStatusCode(value) { 160 | return _.isNumber(value) && Object.values(HTTP_STATUS_CODE).includes(value); 161 | }, 162 | 163 | isURL(value) { 164 | return !_.isUndefined(value) && /^(http|https)/.test(value); 165 | }, 166 | 167 | isSrc(value) { 168 | return !_.isUndefined(value) && /^\/.+\.[0-9a-zA-Z]+(\?.+)?$/.test(value); 169 | }, 170 | 171 | isBASE64(value) { 172 | return !_.isUndefined(value) && /^[a-zA-Z0-9\/\+]+(=?)+$/.test(value); 173 | }, 174 | 175 | isBASE64Data(value) { 176 | return /^data:/.test(value); 177 | }, 178 | 179 | extractBASE64DataFormat(value): string | null { 180 | const match = value.trim().match(/^data:(.+);base64,/); 181 | if (!match) return null; 182 | return match[1]; 183 | }, 184 | 185 | removeBASE64DataHeader(value): string { 186 | return value.replace(/^data:(.+);base64,/, ""); 187 | }, 188 | 189 | isDataString(value): boolean { 190 | return /^(base64|json):/.test(value); 191 | }, 192 | 193 | isStringNumber(value) { 194 | return _.isFinite(Number(value)); 195 | }, 196 | 197 | isUnixTimestamp(value) { 198 | return /^[0-9]{10}$/.test(`${value}`); 199 | }, 200 | 201 | isTimestamp(value) { 202 | return /^[0-9]{13}$/.test(`${value}`); 203 | }, 204 | 205 | isEmail(value) { 206 | return /^([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+@([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+\.[a-zA-Z]{2,3}$/.test( 207 | value 208 | ); 209 | }, 210 | 211 | isAsyncFunction(value) { 212 | return Object.prototype.toString.call(value) === "[object AsyncFunction]"; 213 | }, 214 | 215 | async isAPNG(filePath) { 216 | let head; 217 | const readStream = fs.createReadStream(filePath, { start: 37, end: 40 }); 218 | const readPromise = new Promise((resolve, reject) => { 219 | readStream.once("end", resolve); 220 | readStream.once("error", reject); 221 | }); 222 | readStream.once("data", (data) => (head = data)); 223 | await readPromise; 224 | return head.compare(Buffer.from([0x61, 0x63, 0x54, 0x4c])) === 0; 225 | }, 226 | 227 | unixTimestamp() { 228 | return parseInt(`${Date.now() / 1000}`); 229 | }, 230 | 231 | timestamp() { 232 | return Date.now(); 233 | }, 234 | 235 | urlJoin(...values) { 236 | let url = ""; 237 | for (let i = 0; i < values.length; i++) 238 | url += `${i > 0 ? "/" : ""}${values[i] 239 | .replace(/^\/*/, "") 240 | .replace(/\/*$/, "")}`; 241 | return url; 242 | }, 243 | 244 | millisecondsToHmss(milliseconds) { 245 | if (_.isString(milliseconds)) return milliseconds; 246 | milliseconds = parseInt(milliseconds); 247 | const sec = Math.floor(milliseconds / 1000); 248 | const hours = Math.floor(sec / 3600); 249 | const minutes = Math.floor((sec - hours * 3600) / 60); 250 | const seconds = sec - hours * 3600 - minutes * 60; 251 | const ms = (milliseconds % 60000) - seconds * 1000; 252 | return `${hours > 9 ? hours : "0" + hours}:${ 253 | minutes > 9 ? minutes : "0" + minutes 254 | }:${seconds > 9 ? seconds : "0" + seconds}.${ms}`; 255 | }, 256 | 257 | millisecondsToTimeString(milliseconds) { 258 | if (milliseconds < 1000) return `${milliseconds}ms`; 259 | if (milliseconds < 60000) 260 | return `${parseFloat((milliseconds / 1000).toFixed(2))}s`; 261 | return `${Math.floor(milliseconds / 1000 / 60)}m${Math.floor( 262 | (milliseconds / 1000) % 60 263 | )}s`; 264 | }, 265 | 266 | rgbToHex(r, g, b): string { 267 | return ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1); 268 | }, 269 | 270 | hexToRgb(hex) { 271 | const value = parseInt(hex.replace(/^#/, ""), 16); 272 | return [(value >> 16) & 255, (value >> 8) & 255, value & 255]; 273 | }, 274 | 275 | md5(value) { 276 | return crypto.createHash("md5").update(value).digest("hex"); 277 | }, 278 | 279 | crc32(value) { 280 | return _.isBuffer(value) ? CRC32.buf(value) : CRC32.str(value); 281 | }, 282 | 283 | arrayParse(value): any[] { 284 | return _.isArray(value) ? value : [value]; 285 | }, 286 | 287 | booleanParse(value) { 288 | return value === "true" || value === true ? true : false; 289 | }, 290 | 291 | encodeBASE64(value) { 292 | return Buffer.from(value).toString("base64"); 293 | }, 294 | 295 | decodeBASE64(value) { 296 | return Buffer.from(value, "base64").toString(); 297 | }, 298 | 299 | async fetchFileBASE64(url: string) { 300 | const result = await axios.get(url, { 301 | responseType: "arraybuffer", 302 | }); 303 | return result.data.toString("base64"); 304 | }, 305 | }; 306 | 307 | export default util; 308 | -------------------------------------------------------------------------------- /src/api/controllers/chat.ts: -------------------------------------------------------------------------------- 1 | import { PassThrough } from "stream"; 2 | import _ from "lodash"; 3 | import AsyncLock from "async-lock"; 4 | import axios, { AxiosResponse } from "axios"; 5 | 6 | import APIException from "@/lib/exceptions/APIException.ts"; 7 | import EX from "@/api/consts/exceptions.ts"; 8 | import { createParser } from "eventsource-parser"; 9 | import logger from "@/lib/logger.ts"; 10 | import util from "@/lib/util.ts"; 11 | 12 | 13 | const MODEL_NAME = "deepseek-chat"; 14 | 15 | const ACCESS_TOKEN_EXPIRES = 3600; 16 | 17 | const MAX_RETRY_COUNT = 3; 18 | 19 | const RETRY_DELAY = 5000; 20 | 21 | const FAKE_HEADERS = { 22 | Accept: "*/*", 23 | "Accept-Encoding": "gzip, deflate, br, zstd", 24 | "Accept-Language": "zh-CN,zh;q=0.9", 25 | Origin: "https://chat.deepseek.com", 26 | Pragma: "no-cache", 27 | Referer: "https://chat.deepseek.com/", 28 | "Sec-Ch-Ua": 29 | '"Chromium";v="124", "Google Chrome";v="124", "Not-A.Brand";v="99"', 30 | "Sec-Ch-Ua-Mobile": "?0", 31 | "Sec-Ch-Ua-Platform": '"Windows"', 32 | "Sec-Fetch-Dest": "empty", 33 | "Sec-Fetch-Mode": "cors", 34 | "Sec-Fetch-Site": "same-origin", 35 | "User-Agent": 36 | "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36", 37 | "X-App-Version": "20240126.0", 38 | }; 39 | 40 | const accessTokenMap = new Map(); 41 | 42 | const accessTokenRequestQueueMap: Record = {}; 43 | 44 | 45 | const chatLock = new AsyncLock(); 46 | 47 | 48 | async function requestToken(refreshToken: string) { 49 | if (accessTokenRequestQueueMap[refreshToken]) 50 | return new Promise((resolve) => 51 | accessTokenRequestQueueMap[refreshToken].push(resolve) 52 | ); 53 | accessTokenRequestQueueMap[refreshToken] = []; 54 | logger.info(`Refresh token: ${refreshToken}`); 55 | const result = await (async () => { 56 | const result = await axios.get( 57 | "https://chat.deepseek.com/api/v0/users/current", 58 | { 59 | headers: { 60 | Authorization: `Bearer ${refreshToken}`, 61 | ...FAKE_HEADERS, 62 | }, 63 | timeout: 15000, 64 | validateStatus: () => true, 65 | } 66 | ); 67 | const { token } = checkResult(result, refreshToken); 68 | return { 69 | accessToken: token, 70 | refreshToken: token, 71 | refreshTime: util.unixTimestamp() + ACCESS_TOKEN_EXPIRES, 72 | }; 73 | })() 74 | .then((result) => { 75 | if (accessTokenRequestQueueMap[refreshToken]) { 76 | accessTokenRequestQueueMap[refreshToken].forEach((resolve) => 77 | resolve(result) 78 | ); 79 | delete accessTokenRequestQueueMap[refreshToken]; 80 | } 81 | logger.success(`Refresh successful`); 82 | return result; 83 | }) 84 | .catch((err) => { 85 | if (accessTokenRequestQueueMap[refreshToken]) { 86 | accessTokenRequestQueueMap[refreshToken].forEach((resolve) => 87 | resolve(err) 88 | ); 89 | delete accessTokenRequestQueueMap[refreshToken]; 90 | } 91 | return err; 92 | }); 93 | if (_.isError(result)) throw result; 94 | return result; 95 | } 96 | 97 | 98 | async function acquireToken(refreshToken: string): Promise { 99 | let result = accessTokenMap.get(refreshToken); 100 | if (!result) { 101 | result = await requestToken(refreshToken); 102 | accessTokenMap.set(refreshToken, result); 103 | } 104 | if (util.unixTimestamp() > result.refreshTime) { 105 | result = await requestToken(refreshToken); 106 | accessTokenMap.set(refreshToken, result); 107 | } 108 | return result.accessToken; 109 | } 110 | 111 | 112 | async function clearContext(model: string, refreshToken: string) { 113 | const token = await acquireToken(refreshToken); 114 | const result = await axios.post( 115 | "https://chat.deepseek.com/api/v0/chat/clear_context", 116 | { 117 | model_class: model, 118 | append_welcome_message: false 119 | }, 120 | { 121 | headers: { 122 | Authorization: `Bearer ${token}`, 123 | ...FAKE_HEADERS, 124 | }, 125 | timeout: 15000, 126 | validateStatus: () => true, 127 | } 128 | ); 129 | checkResult(result, refreshToken); 130 | } 131 | 132 | 133 | async function createCompletion( 134 | model = MODEL_NAME, 135 | messages: any[], 136 | refreshToken: string, 137 | retryCount = 0 138 | ) { 139 | return (async () => { 140 | logger.info(messages); 141 | 142 | 143 | const result = await chatLock.acquire(refreshToken, async () => { 144 | 145 | await clearContext(model, refreshToken); 146 | 147 | const token = await acquireToken(refreshToken); 148 | return await axios.post( 149 | "https://chat.deepseek.com/api/v0/chat/completions", 150 | { 151 | message: messagesPrepare(messages), 152 | stream: true, 153 | model_preference: null, 154 | model_class: model, 155 | temperature: 0 156 | }, 157 | { 158 | headers: { 159 | Authorization: `Bearer ${token}`, 160 | ...FAKE_HEADERS 161 | }, 162 | 163 | timeout: 120000, 164 | validateStatus: () => true, 165 | responseType: "stream", 166 | } 167 | ); 168 | }); 169 | 170 | if (result.headers["content-type"].indexOf("text/event-stream") == -1) { 171 | result.data.on("data", buffer => logger.error(buffer.toString())); 172 | throw new APIException( 173 | EX.API_REQUEST_FAILED, 174 | `Stream response Content-Type invalid: ${result.headers["content-type"]}` 175 | ); 176 | } 177 | 178 | const streamStartTime = util.timestamp(); 179 | 180 | const answer = await receiveStream(model, result.data); 181 | logger.success( 182 | `Stream has completed transfer ${util.timestamp() - streamStartTime}ms` 183 | ); 184 | 185 | return answer; 186 | })().catch((err) => { 187 | if (retryCount < MAX_RETRY_COUNT) { 188 | logger.error(`Stream response error: ${err.stack}`); 189 | logger.warn(`Try again after ${RETRY_DELAY / 1000}s...`); 190 | return (async () => { 191 | await new Promise((resolve) => setTimeout(resolve, RETRY_DELAY)); 192 | return createCompletion( 193 | model, 194 | messages, 195 | refreshToken, 196 | retryCount + 1 197 | ); 198 | })(); 199 | } 200 | throw err; 201 | }); 202 | } 203 | 204 | 205 | async function createCompletionStream( 206 | model = MODEL_NAME, 207 | messages: any[], 208 | refreshToken: string, 209 | retryCount = 0 210 | ) { 211 | return (async () => { 212 | logger.info(messages); 213 | 214 | const result = await chatLock.acquire(refreshToken, async () => { 215 | 216 | await clearContext(model, refreshToken); 217 | 218 | const token = await acquireToken(refreshToken); 219 | return await axios.post( 220 | "https://chat.deepseek.com/api/v0/chat/completions", 221 | { 222 | message: messagesPrepare(messages), 223 | stream: true, 224 | model_preference: null, 225 | model_class: model, 226 | temperature: 0 227 | }, 228 | { 229 | headers: { 230 | Authorization: `Bearer ${token}`, 231 | ...FAKE_HEADERS 232 | }, 233 | 234 | timeout: 120000, 235 | validateStatus: () => true, 236 | responseType: "stream", 237 | } 238 | ); 239 | }); 240 | 241 | if (result.headers["content-type"].indexOf("text/event-stream") == -1) { 242 | logger.error( 243 | `Invalid response Content-Type:`, 244 | result.headers["content-type"] 245 | ); 246 | result.data.on("data", buffer => logger.error(buffer.toString())); 247 | const transStream = new PassThrough(); 248 | transStream.end( 249 | `data: ${JSON.stringify({ 250 | id: "", 251 | model: MODEL_NAME, 252 | object: "chat.completion.chunk", 253 | choices: [ 254 | { 255 | index: 0, 256 | delta: { 257 | role: "assistant", 258 | content: "Service is temporarily unavailable, third-party response error", 259 | }, 260 | finish_reason: "stop", 261 | }, 262 | ], 263 | usage: { prompt_tokens: 1, completion_tokens: 1, total_tokens: 2 }, 264 | created: util.unixTimestamp(), 265 | })}\n\n` 266 | ); 267 | return transStream; 268 | } 269 | const streamStartTime = util.timestamp(); 270 | 271 | return createTransStream(model, result.data, () => { 272 | logger.success( 273 | `Stream has completed transfer ${util.timestamp() - streamStartTime}ms` 274 | ); 275 | }); 276 | })().catch((err) => { 277 | if (retryCount < MAX_RETRY_COUNT) { 278 | logger.error(`Stream response error: ${err.stack}`); 279 | logger.warn(`Try again after ${RETRY_DELAY / 1000}s...`); 280 | return (async () => { 281 | await new Promise((resolve) => setTimeout(resolve, RETRY_DELAY)); 282 | return createCompletionStream( 283 | model, 284 | messages, 285 | refreshToken, 286 | retryCount + 1 287 | ); 288 | })(); 289 | } 290 | throw err; 291 | }); 292 | } 293 | 294 | 295 | function messagesPrepare(messages: any[]) { 296 | let content; 297 | if (messages.length < 2) { 298 | content = messages.reduce((content, message) => { 299 | if (_.isArray(message.content)) { 300 | return ( 301 | message.content.reduce((_content, v) => { 302 | if (!_.isObject(v) || v["type"] != "text") return _content; 303 | return _content + (v["text"] || "") + "\n"; 304 | }, content) 305 | ); 306 | } 307 | return content + `${message.content}\n`; 308 | }, ""); 309 | logger.info("\nTransparent content:\n" + content); 310 | } 311 | else { 312 | content = ( 313 | messages.reduce((content, message) => { 314 | if (_.isArray(message.content)) { 315 | return ( 316 | message.content.reduce((_content, v) => { 317 | if (!_.isObject(v) || v["type"] != "text") return _content; 318 | return _content + (`${message.role}:` + v["text"] || "") + "\n"; 319 | }, content) 320 | ); 321 | } 322 | return (content += `${message.role}:${message.content}\n`); 323 | }, "") + "assistant:" 324 | ) 325 | 326 | .replace(/\!\[.+\]\(.+\)/g, ""); 327 | logger.info("\nConversation merge:\n" + content); 328 | } 329 | return content; 330 | } 331 | 332 | 333 | function checkResult(result: AxiosResponse, refreshToken: string) { 334 | if (!result.data) return null; 335 | const { code, data, msg } = result.data; 336 | if (!_.isFinite(code)) return result.data; 337 | if (code === 0) return data; 338 | if (code == 40003) accessTokenMap.delete(refreshToken); 339 | throw new APIException(EX.API_REQUEST_FAILED, `[Request deepseek failed]: ${msg}`); 340 | } 341 | 342 | 343 | async function receiveStream(model: string, stream: any): Promise { 344 | return new Promise((resolve, reject) => { 345 | 346 | const data = { 347 | id: "", 348 | model, 349 | object: "chat.completion", 350 | choices: [ 351 | { 352 | index: 0, 353 | message: { role: "assistant", content: "" }, 354 | finish_reason: "stop", 355 | }, 356 | ], 357 | usage: { prompt_tokens: 1, completion_tokens: 1, total_tokens: 2 }, 358 | created: util.unixTimestamp(), 359 | }; 360 | const parser = createParser((event) => { 361 | try { 362 | if (event.type !== "event") return; 363 | 364 | const result = _.attempt(() => JSON.parse(event.data)); 365 | if (_.isError(result)) 366 | throw new Error(`Stream response invalid: ${event.data}`); 367 | if (!result.choices || !result.choices[0] || !result.choices[0].delta || !result.choices[0].delta.content || result.choices[0].delta.content == ' ') 368 | return; 369 | data.choices[0].message.content += result.choices[0].delta.content; 370 | if (result.choices && result.choices[0] && result.choices[0].finish_reason === "stop") 371 | resolve(data); 372 | } catch (err) { 373 | logger.error(err); 374 | reject(err); 375 | } 376 | }); 377 | 378 | stream.on("data", (buffer) => parser.feed(buffer.toString())); 379 | stream.once("error", (err) => reject(err)); 380 | stream.once("close", () => resolve(data)); 381 | }); 382 | } 383 | 384 | 385 | function createTransStream(model: string, stream: any, endCallback?: Function) { 386 | 387 | const created = util.unixTimestamp(); 388 | 389 | const transStream = new PassThrough(); 390 | !transStream.closed && 391 | transStream.write( 392 | `data: ${JSON.stringify({ 393 | id: "", 394 | model, 395 | object: "chat.completion.chunk", 396 | choices: [ 397 | { 398 | index: 0, 399 | delta: { role: "assistant", content: "" }, 400 | finish_reason: null, 401 | }, 402 | ], 403 | created, 404 | })}\n\n` 405 | ); 406 | const parser = createParser((event) => { 407 | try { 408 | if (event.type !== "event") return; 409 | 410 | const result = _.attempt(() => JSON.parse(event.data)); 411 | if (_.isError(result)) 412 | throw new Error(`Stream response invalid: ${event.data}`); 413 | if (!result.choices || !result.choices[0] || !result.choices[0].delta || !result.choices[0].delta.content || result.choices[0].delta.content == ' ') 414 | return; 415 | result.model = model; 416 | transStream.write(`data: ${JSON.stringify({ 417 | id: result.id, 418 | model: result.model, 419 | object: "chat.completion.chunk", 420 | choices: [ 421 | { 422 | index: 0, 423 | delta: { role: "assistant", content: result.choices[0].delta.content }, 424 | finish_reason: null, 425 | }, 426 | ], 427 | created, 428 | })}\n\n`); 429 | if (result.choices && result.choices[0] && result.choices[0].finish_reason === "stop") { 430 | transStream.write(`data: ${JSON.stringify({ 431 | id: result.id, 432 | model: result.model, 433 | object: "chat.completion.chunk", 434 | choices: [ 435 | { 436 | index: 0, 437 | delta: { role: "assistant", content: "" }, 438 | finish_reason: "stop" 439 | }, 440 | ], 441 | created, 442 | })}\n\n`); 443 | !transStream.closed && transStream.end("data: [DONE]\n\n"); 444 | } 445 | } catch (err) { 446 | logger.error(err); 447 | !transStream.closed && transStream.end("data: [DONE]\n\n"); 448 | } 449 | }); 450 | 451 | stream.on("data", (buffer) => parser.feed(buffer.toString())); 452 | stream.once( 453 | "error", 454 | () => !transStream.closed && transStream.end("data: [DONE]\n\n") 455 | ); 456 | stream.once( 457 | "close", 458 | () => !transStream.closed && transStream.end("data: [DONE]\n\n") 459 | ); 460 | return transStream; 461 | } 462 | 463 | 464 | function tokenSplit(authorization: string) { 465 | return authorization.replace("Bearer ", "").split(","); 466 | } 467 | 468 | 469 | async function getTokenLiveStatus(refreshToken: string) { 470 | const token = await acquireToken(refreshToken); 471 | const result = await axios.get( 472 | "https://chat.deepseek.com/api/v0/users/current", 473 | { 474 | headers: { 475 | Authorization: `Bearer ${token}`, 476 | ...FAKE_HEADERS, 477 | }, 478 | timeout: 15000, 479 | validateStatus: () => true, 480 | } 481 | ); 482 | try { 483 | const { token } = checkResult(result, refreshToken); 484 | return !!token; 485 | } 486 | catch (err) { 487 | return false; 488 | } 489 | } 490 | 491 | export default { 492 | createCompletion, 493 | createCompletionStream, 494 | getTokenLiveStatus, 495 | tokenSplit, 496 | }; 497 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | --------------------------------------------------------------------------------