├── .gitignore ├── dist ├── src │ ├── __tests__ │ │ ├── prompt.test.d.ts │ │ ├── GPTPromptKit.test.d.ts │ │ ├── PromptCraft.test.d.ts │ │ ├── textNormalization.test.d.ts │ │ ├── textNormalization.test.js │ │ ├── prompt.test.js │ │ ├── GPTPromptKit.test.js │ │ └── PromptCraft.test.js │ ├── utils.d.ts │ ├── textNormalization.d.ts │ ├── index.d.ts │ ├── prompt.d.ts │ ├── textNormalization.js │ ├── constant.d.ts │ ├── constant.js │ ├── GPTPromptKit.d.ts │ ├── prompt.js │ ├── index.js │ ├── PromptCraft.d.ts │ ├── GPTPromptKit.js │ ├── utils.js │ └── PromptCraft.js └── demo │ ├── translate.d.ts │ ├── formatJSON.d.ts │ ├── translate.js │ ├── formatJSON.js │ ├── interpreter.d.ts │ ├── interpreter.js │ ├── formatFree.d.ts │ └── formatFree.js ├── demo-img ├── translate.png ├── formatFree.png ├── formatFree2.png ├── formatJSON.png ├── formatJSON2.png ├── translate2.png └── customizedOptions.png ├── .prettierrc.js ├── jest.config.js ├── src ├── textNormalization.ts ├── index.ts ├── constant.ts ├── prompt.ts ├── __tests__ │ ├── textNormalization.test.ts │ ├── prompt.test.ts │ └── GPTPromptKit.test.ts └── GPTPromptKit.ts ├── .eslintrc.js ├── demo ├── translate.ts ├── formatJSON.ts └── formatFree.ts ├── tsconfig.json ├── tea.yaml ├── LICENSE ├── package.json └── README.md /.gitignore: -------------------------------------------------------------------------------- 1 | /node_modules -------------------------------------------------------------------------------- /dist/src/__tests__/prompt.test.d.ts: -------------------------------------------------------------------------------- 1 | export {}; 2 | -------------------------------------------------------------------------------- /dist/src/__tests__/GPTPromptKit.test.d.ts: -------------------------------------------------------------------------------- 1 | export {}; 2 | -------------------------------------------------------------------------------- /dist/src/__tests__/PromptCraft.test.d.ts: -------------------------------------------------------------------------------- 1 | export {}; 2 | -------------------------------------------------------------------------------- /dist/src/__tests__/textNormalization.test.d.ts: -------------------------------------------------------------------------------- 1 | export {}; 2 | -------------------------------------------------------------------------------- /dist/src/utils.d.ts: -------------------------------------------------------------------------------- 1 | export declare function runScript(script: string): Promise; 2 | -------------------------------------------------------------------------------- /dist/demo/translate.d.ts: -------------------------------------------------------------------------------- 1 | export {}; 2 | /** 3 | * output = 这是一个很棒的图书馆,gpt太棒了! 4 | */ 5 | -------------------------------------------------------------------------------- /demo-img/translate.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/clean99/gpt-prompt-kit/HEAD/demo-img/translate.png -------------------------------------------------------------------------------- /demo-img/formatFree.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/clean99/gpt-prompt-kit/HEAD/demo-img/formatFree.png -------------------------------------------------------------------------------- /demo-img/formatFree2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/clean99/gpt-prompt-kit/HEAD/demo-img/formatFree2.png -------------------------------------------------------------------------------- /demo-img/formatJSON.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/clean99/gpt-prompt-kit/HEAD/demo-img/formatJSON.png -------------------------------------------------------------------------------- /demo-img/formatJSON2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/clean99/gpt-prompt-kit/HEAD/demo-img/formatJSON2.png -------------------------------------------------------------------------------- /demo-img/translate2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/clean99/gpt-prompt-kit/HEAD/demo-img/translate2.png -------------------------------------------------------------------------------- /demo-img/customizedOptions.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/clean99/gpt-prompt-kit/HEAD/demo-img/customizedOptions.png -------------------------------------------------------------------------------- /.prettierrc.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | semi: true, 3 | trailingComma: 'es5', 4 | singleQuote: true, 5 | printWidth: 80, 6 | tabWidth: 2, 7 | }; 8 | -------------------------------------------------------------------------------- /jest.config.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | preset: 'ts-jest', 3 | testEnvironment: 'node', 4 | testMatch: ['**/*.test.ts'], 5 | modulePathIgnorePatterns: ['/dist/'] 6 | }; 7 | -------------------------------------------------------------------------------- /dist/src/textNormalization.d.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * A function that takes a string input and returns the normalized string. 3 | * @param text 4 | * @returns {string} 5 | */ 6 | export declare const getCodeBlock: (text: string) => string | null; 7 | -------------------------------------------------------------------------------- /dist/demo/formatJSON.d.ts: -------------------------------------------------------------------------------- 1 | export {}; 2 | /** 3 | * output = { 4 | * "title": "Math", 5 | * "subjects": [ 6 | * "Algebra", 7 | * "Geometry", 8 | * "Calculus", 9 | * "Statistics", 10 | * "Trigonometry" 11 | * ] 12 | * } 13 | */ 14 | -------------------------------------------------------------------------------- /src/textNormalization.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * A function that takes a string input and returns the normalized string. 3 | * @param text 4 | * @returns {string} 5 | */ 6 | export const getCodeBlock = (text: string): string | null => 7 | /```[\s\S]*?\n([\s\S]*?)\n```/.exec(text)?.[1].trim() ?? null; 8 | -------------------------------------------------------------------------------- /dist/src/index.d.ts: -------------------------------------------------------------------------------- 1 | import GPTPromptKit from './GPTPromptKit'; 2 | export declare const gptPromptKitFactory: (apiKey: string, options?: any) => GPTPromptKit; 3 | export * as defaultPrompt from './prompt'; 4 | export * from './textNormalization'; 5 | export * from './constant'; 6 | export { default as GPTPromptKit } from './GPTPromptKit'; 7 | -------------------------------------------------------------------------------- /.eslintrc.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | parser: '@typescript-eslint/parser', 3 | extends: [ 4 | 'plugin:@typescript-eslint/recommended', 5 | 'plugin:prettier/recommended', 6 | 'prettier', 7 | ], 8 | plugins: ['@typescript-eslint', 'prettier'], 9 | rules: { 10 | 'prettier/prettier': 'error', 11 | }, 12 | }; 13 | -------------------------------------------------------------------------------- /dist/src/prompt.d.ts: -------------------------------------------------------------------------------- 1 | import { OpenAIApi, CreateChatCompletionRequest } from 'openai'; 2 | export declare const prompt: (messages: CreateChatCompletionRequest['messages'], openai: OpenAIApi, options?: any) => Promise; 3 | export declare const promptWithTextGenerator: (apiKey: string, options?: any) => (content: string) => Promise; 4 | -------------------------------------------------------------------------------- /demo/translate.ts: -------------------------------------------------------------------------------- 1 | import { Lang } from '../src/constant'; 2 | import { gptPromptKitFactory } from '../src/index'; 3 | 4 | const gptPromptKit = gptPromptKitFactory('Your API key'); 5 | 6 | const translator = gptPromptKit.translate(Lang.English, Lang.Chinese); 7 | 8 | translator('This is an awesome library, gpt is awesome!').then(console.log); 9 | 10 | /** 11 | * output = 这是一个很棒的图书馆,gpt太棒了! 12 | */ 13 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "target": "es6", 4 | "module": "commonjs", 5 | "declaration": true, 6 | "outDir": "./dist", 7 | "strict": true, 8 | "esModuleInterop": true, 9 | "forceConsistentCasingInFileNames": true 10 | }, 11 | "include": ["src/**/*", "demo/**/*"], 12 | "exclude": ["node_modules", "**/*.spec.ts"] 13 | } 14 | -------------------------------------------------------------------------------- /src/index.ts: -------------------------------------------------------------------------------- 1 | import GPTPromptKit from './GPTPromptKit'; 2 | import * as defaultPrompt from './prompt'; 3 | 4 | export const gptPromptKitFactory = (apiKey: string, options?: any) => 5 | new GPTPromptKit(defaultPrompt.promptWithTextGenerator(apiKey, options)); 6 | 7 | export * as defaultPrompt from './prompt'; 8 | export * from './textNormalization'; 9 | export * from './constant'; 10 | export { default as GPTPromptKit } from './GPTPromptKit'; 11 | -------------------------------------------------------------------------------- /dist/demo/translate.js: -------------------------------------------------------------------------------- 1 | "use strict"; 2 | Object.defineProperty(exports, "__esModule", { value: true }); 3 | const constant_1 = require("../src/constant"); 4 | const index_1 = require("../src/index"); 5 | const gptPromptKit = (0, index_1.gptPromptKitFactory)('Your API key'); 6 | const translator = gptPromptKit.translate(constant_1.Lang.English, constant_1.Lang.Chinese); 7 | translator('This is an awesome library, gpt is awesome!').then(console.log); 8 | /** 9 | * output = 这是一个很棒的图书馆,gpt太棒了! 10 | */ 11 | -------------------------------------------------------------------------------- /dist/src/textNormalization.js: -------------------------------------------------------------------------------- 1 | "use strict"; 2 | Object.defineProperty(exports, "__esModule", { value: true }); 3 | exports.getCodeBlock = void 0; 4 | /** 5 | * A function that takes a string input and returns the normalized string. 6 | * @param text 7 | * @returns {string} 8 | */ 9 | const getCodeBlock = (text) => { var _a, _b; return (_b = (_a = /```[\s\S]*?\n([\s\S]*?)\n```/.exec(text)) === null || _a === void 0 ? void 0 : _a[1].trim()) !== null && _b !== void 0 ? _b : null; }; 10 | exports.getCodeBlock = getCodeBlock; 11 | -------------------------------------------------------------------------------- /demo/formatJSON.ts: -------------------------------------------------------------------------------- 1 | import { gptPromptKitFactory } from '../src/index'; 2 | 3 | const gptPromptKit = gptPromptKitFactory('Your API key'); 4 | 5 | const formatJson = gptPromptKit.formatJson({ 6 | title: 'The title of the subject.', 7 | subjects: 'The subjects list under the title.', 8 | }); 9 | 10 | const description = 11 | 'Generate a list of subjects that I need to learned under the title, which the length is 5.'; 12 | 13 | const input = { 14 | title: 'Math', 15 | }; 16 | 17 | formatJson(description, input).then(console.log); 18 | 19 | /** 20 | * output = { 21 | * "title": "Math", 22 | * "subjects": [ 23 | * "Algebra", 24 | * "Geometry", 25 | * "Calculus", 26 | * "Statistics", 27 | * "Trigonometry" 28 | * ] 29 | * } 30 | */ 31 | -------------------------------------------------------------------------------- /tea.yaml: -------------------------------------------------------------------------------- 1 | # https://tea.xyz/what-is-this-file 2 | # 3 | # DO NOT REMOVE OR EDIT THIS WARNING: 4 | # 5 | # This file is auto-generated by the TEA app. It is intended to validate ownership of your repository. 6 | # DO NOT commit this file or accept any PR if you don't know what this is. 7 | # We are aware that spammers will try to use this file to try to profit off others' work. 8 | # We take this very seriously and will take action against any malicious actors. 9 | # 10 | # If you are not the owner of this repository, and someone maliciously opens a commit with this file 11 | # please report it to us at support@tea.xyz. 12 | # 13 | # A constitution without this header is invalid. 14 | --- 15 | version: 2.0.0 16 | codeOwners: 17 | - '0xD1fe93EF52B1D0a252302dc3a1873f595D3e6A9b' 18 | quorum: 1 19 | -------------------------------------------------------------------------------- /dist/demo/formatJSON.js: -------------------------------------------------------------------------------- 1 | "use strict"; 2 | Object.defineProperty(exports, "__esModule", { value: true }); 3 | const index_1 = require("../src/index"); 4 | const gptPromptKit = (0, index_1.gptPromptKitFactory)('Your API key'); 5 | const formatJson = gptPromptKit.formatJson({ 6 | title: 'The title of the subject.', 7 | subjects: 'The subjects list under the title.', 8 | }); 9 | const description = 'Generate a list of subjects that I need to learned under the title, which the length is 5.'; 10 | const input = { 11 | title: 'Math', 12 | }; 13 | formatJson(description, input).then(console.log); 14 | /** 15 | * output = { 16 | * "title": "Math", 17 | * "subjects": [ 18 | * "Algebra", 19 | * "Geometry", 20 | * "Calculus", 21 | * "Statistics", 22 | * "Trigonometry" 23 | * ] 24 | * } 25 | */ 26 | -------------------------------------------------------------------------------- /src/constant.ts: -------------------------------------------------------------------------------- 1 | export enum Lang { 2 | English = 'English', 3 | Chinese = 'Chinese', 4 | Japanese = 'Japanese', 5 | Korean = 'Korean', 6 | French = 'French', 7 | German = 'German', 8 | Spanish = 'Spanish', 9 | Italian = 'Italian', 10 | Indian = 'Indian', 11 | Filipino = 'Filipino', 12 | Russian = 'Russian', 13 | Portuguese = 'Portuguese', 14 | Dutch = 'Dutch', 15 | Swedish = 'Swedish', 16 | Danish = 'Danish', 17 | Norwegian = 'Norwegian', 18 | Finnish = 'Finnish', 19 | Polish = 'Polish', 20 | Czech = 'Czech', 21 | Hungarian = 'Hungarian', 22 | Romanian = 'Romanian', 23 | Turkish = 'Turkish', 24 | Greek = 'Greek', 25 | Bulgarian = 'Bulgarian', 26 | Arabic = 'Arabic', 27 | Hebrew = 'Hebrew', 28 | Hindi = 'Hindi', 29 | } 30 | 31 | export enum Interpreter { 32 | JS_V8 = 'NodeJS', 33 | } 34 | -------------------------------------------------------------------------------- /dist/demo/interpreter.d.ts: -------------------------------------------------------------------------------- 1 | export {}; 2 | /** 3 | * codeBlock console.log(7 + Math.pow(14, 3)); 4 | * output 2751 5 | */ 6 | /** 7 | * codeBlock const lengthOfLIS = function(nums) { 8 | * const dp = new Array(nums.length).fill(1); 9 | * let max = 0; 10 | * for (let i = 0; i < nums.length; i++) { 11 | * for (let j = 0; j < i; j++) { 12 | * if (nums[i] > nums[j]) { 13 | * dp[i] = Math.max(dp[i], dp[j] + 1); 14 | * } 15 | * } 16 | * max = Math.max(max, dp[i]); 17 | * } 18 | * return max; 19 | *}; 20 | * console.log(lengthOfLIS([10,9,2,5,3,7,101,18])); 21 | * 22 | * output 4 23 | */ 24 | /** 25 | * codeBlock const leak = () => { 26 | * const arr = []; 27 | * for (let i = 0; i < 1000000; i++) { 28 | * arr.push(new Array(1000000).fill(0)); 29 | * } 30 | * }; 31 | * 32 | * leak(); 33 | * 34 | * output undefined 35 | */ 36 | -------------------------------------------------------------------------------- /dist/src/constant.d.ts: -------------------------------------------------------------------------------- 1 | export declare enum Lang { 2 | English = "English", 3 | Chinese = "Chinese", 4 | Japanese = "Japanese", 5 | Korean = "Korean", 6 | French = "French", 7 | German = "German", 8 | Spanish = "Spanish", 9 | Italian = "Italian", 10 | Indian = "Indian", 11 | Filipino = "Filipino", 12 | Russian = "Russian", 13 | Portuguese = "Portuguese", 14 | Dutch = "Dutch", 15 | Swedish = "Swedish", 16 | Danish = "Danish", 17 | Norwegian = "Norwegian", 18 | Finnish = "Finnish", 19 | Polish = "Polish", 20 | Czech = "Czech", 21 | Hungarian = "Hungarian", 22 | Romanian = "Romanian", 23 | Turkish = "Turkish", 24 | Greek = "Greek", 25 | Bulgarian = "Bulgarian", 26 | Arabic = "Arabic", 27 | Hebrew = "Hebrew", 28 | Hindi = "Hindi" 29 | } 30 | export declare enum Interpreter { 31 | JS_V8 = "NodeJS" 32 | } 33 | -------------------------------------------------------------------------------- /src/prompt.ts: -------------------------------------------------------------------------------- 1 | import { 2 | Configuration, 3 | OpenAIApi, 4 | CreateChatCompletionRequest, 5 | ChatCompletionRequestMessageRoleEnum, 6 | } from 'openai'; 7 | 8 | const DEFUALT_OPTIONS = { 9 | model: 'gpt-3.5-turbo', 10 | max_tokens: 3500, 11 | temperature: 0.4, 12 | }; 13 | 14 | export const prompt = async ( 15 | messages: CreateChatCompletionRequest['messages'], 16 | openai: OpenAIApi, 17 | options: any = DEFUALT_OPTIONS 18 | ): Promise => { 19 | const response = await openai.createChatCompletion({ 20 | ...options, 21 | messages, 22 | }); 23 | return response?.data?.choices?.[0]?.message?.content ?? ''; 24 | }; 25 | 26 | export const promptWithTextGenerator = 27 | (apiKey: string, options?: any) => 28 | async (content: string): Promise => { 29 | const configuration = new Configuration({ 30 | apiKey, 31 | }); 32 | const openai = new OpenAIApi(configuration); 33 | return prompt( 34 | [{ content, role: ChatCompletionRequestMessageRoleEnum.User }], 35 | openai, 36 | options 37 | ); 38 | }; 39 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2023 clean99 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "gpt-prompt-kit", 3 | "version": "1.1.2", 4 | "description": "Help you better prompt by using prompt engineering technique like external interpreter, chain of thought.", 5 | "repository": "https://github.com/clean99/gpt-prompt-kit", 6 | "main": "dist/src/index.js", 7 | "scripts": { 8 | "build": "tsc", 9 | "test": "jest", 10 | "test:watch": "jest --watch", 11 | "lint": "eslint 'src/**/*.{ts,tsx}' --fix", 12 | "format": "prettier --write 'src/**/*.{ts,tsx}'" 13 | }, 14 | "keywords": [ 15 | "prompt", 16 | "prompt-engineering", 17 | "chatgpt", 18 | "chain-of-thought", 19 | "perfect-prompt", 20 | "prompt-with-program" 21 | ], 22 | "author": "clean99", 23 | "license": "MIT", 24 | "devDependencies": { 25 | "@types/jest": "^29.4.0", 26 | "@types/node": "^18.15.0", 27 | "@typescript-eslint/eslint-plugin": "^5.55.0", 28 | "@typescript-eslint/parser": "^5.55.0", 29 | "eslint": "^8.36.0", 30 | "eslint-config-prettier": "^8.7.0", 31 | "eslint-plugin-prettier": "^4.2.1", 32 | "jest": "^29.5.0", 33 | "prettier": "^2.8.4", 34 | "ts-jest": "^29.0.5", 35 | "ts-node": "^10.9.1", 36 | "typescript": "^4.9.5" 37 | }, 38 | "dependencies": { 39 | "openai": "^3.2.1" 40 | }, 41 | "publishConfig": { 42 | "registry": "https://registry.npmjs.org" 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /dist/src/constant.js: -------------------------------------------------------------------------------- 1 | "use strict"; 2 | Object.defineProperty(exports, "__esModule", { value: true }); 3 | exports.Interpreter = exports.Lang = void 0; 4 | var Lang; 5 | (function (Lang) { 6 | Lang["English"] = "English"; 7 | Lang["Chinese"] = "Chinese"; 8 | Lang["Japanese"] = "Japanese"; 9 | Lang["Korean"] = "Korean"; 10 | Lang["French"] = "French"; 11 | Lang["German"] = "German"; 12 | Lang["Spanish"] = "Spanish"; 13 | Lang["Italian"] = "Italian"; 14 | Lang["Indian"] = "Indian"; 15 | Lang["Filipino"] = "Filipino"; 16 | Lang["Russian"] = "Russian"; 17 | Lang["Portuguese"] = "Portuguese"; 18 | Lang["Dutch"] = "Dutch"; 19 | Lang["Swedish"] = "Swedish"; 20 | Lang["Danish"] = "Danish"; 21 | Lang["Norwegian"] = "Norwegian"; 22 | Lang["Finnish"] = "Finnish"; 23 | Lang["Polish"] = "Polish"; 24 | Lang["Czech"] = "Czech"; 25 | Lang["Hungarian"] = "Hungarian"; 26 | Lang["Romanian"] = "Romanian"; 27 | Lang["Turkish"] = "Turkish"; 28 | Lang["Greek"] = "Greek"; 29 | Lang["Bulgarian"] = "Bulgarian"; 30 | Lang["Arabic"] = "Arabic"; 31 | Lang["Hebrew"] = "Hebrew"; 32 | Lang["Hindi"] = "Hindi"; 33 | })(Lang = exports.Lang || (exports.Lang = {})); 34 | var Interpreter; 35 | (function (Interpreter) { 36 | Interpreter["JS_V8"] = "NodeJS"; 37 | })(Interpreter = exports.Interpreter || (exports.Interpreter = {})); 38 | -------------------------------------------------------------------------------- /dist/demo/interpreter.js: -------------------------------------------------------------------------------- 1 | "use strict"; 2 | Object.defineProperty(exports, "__esModule", { value: true }); 3 | const constant_1 = require("../src/constant"); 4 | const index_1 = require("../src/index"); 5 | const gptPromptKit = (0, index_1.gptPromptKitFactory)('Your API Key'); 6 | const gptWithInterpreterAndRunCode = gptPromptKit.useInterpreter(constant_1.Interpreter.JS_V8, true); 7 | const gptWithInterpreterButNotRunCode = gptPromptKit.useInterpreter(constant_1.Interpreter.JS_V8, false); 8 | const mathQuestion = `What is the result of 7 + 14 ^ 3?`; 9 | const algorithm = `What is the LIS length of [10,9,2,5,3,7,101,18]?`; 10 | const hackProgram = `Write a program that causes memory leak`; 11 | gptWithInterpreterAndRunCode(mathQuestion).then(console.log); 12 | gptWithInterpreterAndRunCode(algorithm).then(console.log); 13 | gptWithInterpreterButNotRunCode(hackProgram).then(console.log); 14 | /** 15 | * codeBlock console.log(7 + Math.pow(14, 3)); 16 | * output 2751 17 | */ 18 | /** 19 | * codeBlock const lengthOfLIS = function(nums) { 20 | * const dp = new Array(nums.length).fill(1); 21 | * let max = 0; 22 | * for (let i = 0; i < nums.length; i++) { 23 | * for (let j = 0; j < i; j++) { 24 | * if (nums[i] > nums[j]) { 25 | * dp[i] = Math.max(dp[i], dp[j] + 1); 26 | * } 27 | * } 28 | * max = Math.max(max, dp[i]); 29 | * } 30 | * return max; 31 | *}; 32 | * console.log(lengthOfLIS([10,9,2,5,3,7,101,18])); 33 | * 34 | * output 4 35 | */ 36 | /** 37 | * codeBlock const leak = () => { 38 | * const arr = []; 39 | * for (let i = 0; i < 1000000; i++) { 40 | * arr.push(new Array(1000000).fill(0)); 41 | * } 42 | * }; 43 | * 44 | * leak(); 45 | * 46 | * output undefined 47 | */ 48 | -------------------------------------------------------------------------------- /dist/src/GPTPromptKit.d.ts: -------------------------------------------------------------------------------- 1 | import { Lang } from './constant'; 2 | interface PromptEngineering { 3 | /** 4 | * Returns a function that translates the given text from the specified source language to the target language. 5 | * @param {string} from The source language. 6 | * @param {string} to The target language. 7 | * @returns {(text: string) => string} A function that takes a string input and returns the translated string. 8 | */ 9 | translate: (from: Lang, to: Lang) => (text: string) => Promise; 10 | /** 11 | * Returns a function that formats the given input data into the specified JSON schema. 12 | * @param {object} schema The JSON schema to format the data into. 13 | * @returns {(description: string, input: object) => string} A function that takes an input object and returns the formatted JSON string. 14 | */ 15 | formatJson: (schema: Record) => (description: string, input: object) => Promise; 16 | /** 17 | * Returns a function that formats the given input data according to the specified format string. 18 | * @param {string format The format string to use for formatting the input data. 19 | * @returns {(description: string) => string} A function that takes an description and returns the formatted string. 20 | */ 21 | formatFree: (format: string) => (description: string) => Promise; 22 | } 23 | declare class GPTPromptKit implements PromptEngineering { 24 | private prompt; 25 | private getCodeBlock; 26 | constructor(prompt: (text: string) => Promise, getCodeBlock?: (text: string) => string | null); 27 | translate(from: Lang, to: Lang): (text: string) => Promise; 28 | formatJson(schema: Record): (description: string, input: object) => Promise; 29 | formatFree(schema: string): (description: string) => Promise; 30 | } 31 | export default GPTPromptKit; 32 | -------------------------------------------------------------------------------- /dist/src/prompt.js: -------------------------------------------------------------------------------- 1 | "use strict"; 2 | var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { 3 | function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } 4 | return new (P || (P = Promise))(function (resolve, reject) { 5 | function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } 6 | function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } 7 | function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } 8 | step((generator = generator.apply(thisArg, _arguments || [])).next()); 9 | }); 10 | }; 11 | Object.defineProperty(exports, "__esModule", { value: true }); 12 | exports.promptWithTextGenerator = exports.prompt = void 0; 13 | const openai_1 = require("openai"); 14 | const DEFUALT_OPTIONS = { 15 | model: 'gpt-3.5-turbo', 16 | max_tokens: 3500, 17 | temperature: 0.4, 18 | }; 19 | const prompt = (messages, openai, options = DEFUALT_OPTIONS) => __awaiter(void 0, void 0, void 0, function* () { 20 | var _a, _b, _c, _d, _e; 21 | const response = yield openai.createChatCompletion(Object.assign(Object.assign({}, options), { messages })); 22 | return (_e = (_d = (_c = (_b = (_a = response === null || response === void 0 ? void 0 : response.data) === null || _a === void 0 ? void 0 : _a.choices) === null || _b === void 0 ? void 0 : _b[0]) === null || _c === void 0 ? void 0 : _c.message) === null || _d === void 0 ? void 0 : _d.content) !== null && _e !== void 0 ? _e : ''; 23 | }); 24 | exports.prompt = prompt; 25 | const promptWithTextGenerator = (apiKey, options) => (content) => __awaiter(void 0, void 0, void 0, function* () { 26 | const configuration = new openai_1.Configuration({ 27 | apiKey, 28 | }); 29 | const openai = new openai_1.OpenAIApi(configuration); 30 | return (0, exports.prompt)([{ content, role: openai_1.ChatCompletionRequestMessageRoleEnum.User }], openai, options); 31 | }); 32 | exports.promptWithTextGenerator = promptWithTextGenerator; 33 | -------------------------------------------------------------------------------- /dist/src/index.js: -------------------------------------------------------------------------------- 1 | "use strict"; 2 | var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { 3 | if (k2 === undefined) k2 = k; 4 | var desc = Object.getOwnPropertyDescriptor(m, k); 5 | if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { 6 | desc = { enumerable: true, get: function() { return m[k]; } }; 7 | } 8 | Object.defineProperty(o, k2, desc); 9 | }) : (function(o, m, k, k2) { 10 | if (k2 === undefined) k2 = k; 11 | o[k2] = m[k]; 12 | })); 13 | var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { 14 | Object.defineProperty(o, "default", { enumerable: true, value: v }); 15 | }) : function(o, v) { 16 | o["default"] = v; 17 | }); 18 | var __importStar = (this && this.__importStar) || function (mod) { 19 | if (mod && mod.__esModule) return mod; 20 | var result = {}; 21 | if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); 22 | __setModuleDefault(result, mod); 23 | return result; 24 | }; 25 | var __exportStar = (this && this.__exportStar) || function(m, exports) { 26 | for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p); 27 | }; 28 | var __importDefault = (this && this.__importDefault) || function (mod) { 29 | return (mod && mod.__esModule) ? mod : { "default": mod }; 30 | }; 31 | Object.defineProperty(exports, "__esModule", { value: true }); 32 | exports.GPTPromptKit = exports.defaultPrompt = exports.gptPromptKitFactory = void 0; 33 | const GPTPromptKit_1 = __importDefault(require("./GPTPromptKit")); 34 | const defaultPrompt = __importStar(require("./prompt")); 35 | const gptPromptKitFactory = (apiKey, options) => new GPTPromptKit_1.default(defaultPrompt.promptWithTextGenerator(apiKey, options)); 36 | exports.gptPromptKitFactory = gptPromptKitFactory; 37 | exports.defaultPrompt = __importStar(require("./prompt")); 38 | __exportStar(require("./textNormalization"), exports); 39 | __exportStar(require("./constant"), exports); 40 | var GPTPromptKit_2 = require("./GPTPromptKit"); 41 | Object.defineProperty(exports, "GPTPromptKit", { enumerable: true, get: function () { return __importDefault(GPTPromptKit_2).default; } }); 42 | -------------------------------------------------------------------------------- /dist/src/PromptCraft.d.ts: -------------------------------------------------------------------------------- 1 | import { Lang, Interpreter } from './constant'; 2 | interface PromptEngineering { 3 | /** 4 | * Returns a function that translates the given text from the specified source language to the target language. 5 | * @param {string} from The source language. 6 | * @param {string} to The target language. 7 | * @returns {(text: string) => string} A function that takes a string input and returns the translated string. 8 | */ 9 | translate: (from: Lang, to: Lang) => (text: string) => Promise; 10 | /** 11 | * Returns a function that formats the given input data into the specified JSON schema. 12 | * @param {object} schema The JSON schema to format the data into. 13 | * @returns {(description: string, input: object) => string} A function that takes an input object and returns the formatted JSON string. 14 | */ 15 | formatJson: (schema: Record) => (description: string, input: object) => Promise; 16 | /** 17 | * Returns a function that formats the given input data according to the specified format string. 18 | * @param {string format The format string to use for formatting the input data. 19 | * @returns {(description: string) => string} A function that takes an description and returns the formatted string. 20 | */ 21 | formatFree: (format: string) => (description: string) => Promise; 22 | /** 23 | * Returns a function that uses an external interpreter to answer the given question. 24 | * @param {Interpreter} interpreter The name or path of the external interpreter to use. 25 | * @returns {(question: string) => string} A function that takes a question string and returns the interpreter's answer. 26 | */ 27 | useInterpreter: (interpreter: Interpreter, runCode?: boolean) => (question: string) => Promise; 28 | } 29 | declare class GPTPromptKit implements PromptEngineering { 30 | private prompt; 31 | private getCodeBlock; 32 | constructor(prompt: (text: string) => Promise, getCodeBlock?: (text: string) => string | null); 33 | translate(from: Lang, to: Lang): (text: string) => Promise; 34 | formatJson(schema: Record): (description: string, input: object) => Promise; 35 | formatFree(schema: string): (description: string) => Promise; 36 | useInterpreter(interpreter: Interpreter, runCode?: boolean): (question: string) => Promise; 37 | } 38 | export default GPTPromptKit; 39 | -------------------------------------------------------------------------------- /src/__tests__/textNormalization.test.ts: -------------------------------------------------------------------------------- 1 | import { getCodeBlock } from '../textNormalization'; 2 | 3 | describe('getCodeBlock', () => { 4 | test('returns null for input without code block', () => { 5 | const text = 'This is some text without a code block.'; 6 | expect(getCodeBlock(text)).toBeNull(); 7 | }); 8 | 9 | test('returns normalized code block for input with code block', () => { 10 | const text = 11 | 'This is some text with a code block:\n```js\nconsole.log("Hello, world!");\n```'; 12 | const expected = 'console.log("Hello, world!");'; 13 | expect(getCodeBlock(text)).toBe(expected); 14 | }); 15 | 16 | test('normalizes leading/trailing whitespace', () => { 17 | const text = 18 | 'Here is a code block with leading/trailing whitespace:\n```\n foo \n```'; 19 | const expected = 'foo'; 20 | expect(getCodeBlock(text)).toBe(expected); 21 | }); 22 | 23 | test('normalizes multiple lines of code', () => { 24 | const text = 25 | 'Here is a code block with multiple lines:\n```html\n

Hello, world!

\n

Welcome to my website.

\n```'; 26 | const expected = '

Hello, world!

\n

Welcome to my website.

'; 27 | expect(getCodeBlock(text)).toBe(expected); 28 | }); 29 | 30 | test('normalizes empty code block', () => { 31 | const text = 'Here is an empty code block:\n```\n```'; 32 | expect(getCodeBlock(text)).toBeNull(); 33 | }); 34 | 35 | test('normalizes code block with leading/trailing newlines', () => { 36 | const text = 37 | '\nHere is a code block with leading/trailing newlines:\n```\n\nfoo\n\n```'; 38 | const expected = 'foo'; 39 | expect(getCodeBlock(text)).toBe(expected); 40 | }); 41 | 42 | test('normalizes code block with leading/trailing backticks', () => { 43 | const text = 44 | 'Here is a code block with leading/trailing backticks:\n```js```\nconsole.log("Hello, world!");\n``````'; 45 | const expected = 'console.log("Hello, world!");'; 46 | expect(getCodeBlock(text)).toBe(expected); 47 | }); 48 | 49 | test('normalizes multiple lines of code', () => { 50 | const text = 51 | 'Here is a code block with multiple lines:\n```js\nfunction add(a, b) {\n return a + b;\n}\n```'; 52 | const expected = 'function add(a, b) {\n return a + b;\n}'; 53 | expect(getCodeBlock(text)).toBe(expected); 54 | }); 55 | test('normalizes multiple lines of code', () => { 56 | const text = 57 | 'Here is a code block with multiple lines:\n```json\n{\n "name": "John",\n "age": 30,\n "city": "New York"\n}\n```'; 58 | const expected = 59 | '{\n "name": "John",\n "age": 30,\n "city": "New York"\n}'; 60 | expect(getCodeBlock(text)).toBe(expected); 61 | }); 62 | }); 63 | -------------------------------------------------------------------------------- /dist/src/GPTPromptKit.js: -------------------------------------------------------------------------------- 1 | "use strict"; 2 | var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { 3 | function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } 4 | return new (P || (P = Promise))(function (resolve, reject) { 5 | function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } 6 | function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } 7 | function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } 8 | step((generator = generator.apply(thisArg, _arguments || [])).next()); 9 | }); 10 | }; 11 | Object.defineProperty(exports, "__esModule", { value: true }); 12 | const textNormalization_1 = require("./textNormalization"); 13 | class GPTPromptKit { 14 | constructor(prompt, getCodeBlock = textNormalization_1.getCodeBlock) { 15 | this.prompt = prompt; 16 | this.getCodeBlock = getCodeBlock; 17 | } 18 | // translate method 19 | translate(from, to) { 20 | return (text) => { 21 | return this.prompt(`A ${from} phrase is provided: ${text} 22 | The masterful ${from} translator flawlessly translates the phrase into ${to}:`); 23 | }; 24 | } 25 | // formatJson method 26 | formatJson(schema) { 27 | return (description, input) => __awaiter(this, void 0, void 0, function* () { 28 | const promptResult = yield this.prompt(` 29 | ${description}\n 30 | Add \`\`\` at the start and end of json:\n 31 | ${Object.keys(schema) 32 | .map((key) => `${key}: ${schema[key]}`) 33 | .join('\n // ')} 34 | 35 | input = ${JSON.stringify(input, null, 4)} 36 | Use JSON format: 37 | \`\`\` 38 | 39 | \`\`\` 40 | `); 41 | const codeBlock = this.getCodeBlock(promptResult); 42 | if (codeBlock) { 43 | return JSON.parse(codeBlock); 44 | } 45 | return promptResult; 46 | }); 47 | } 48 | // formatFree method 49 | formatFree(schema) { 50 | return (description) => __awaiter(this, void 0, void 0, function* () { 51 | var _a; 52 | const promptResult = yield this.prompt(` 53 | ${description}\n 54 | Use this format, add \`\`\` at the start and end of content:\n 55 | ${schema} 56 | `); 57 | return (_a = this.getCodeBlock(promptResult)) !== null && _a !== void 0 ? _a : promptResult; 58 | }); 59 | } 60 | } 61 | exports.default = GPTPromptKit; 62 | -------------------------------------------------------------------------------- /src/__tests__/prompt.test.ts: -------------------------------------------------------------------------------- 1 | import { prompt } from '../prompt'; 2 | import { 3 | CreateChatCompletionResponse, 4 | ChatCompletionRequestMessageRoleEnum, 5 | } from 'openai'; 6 | 7 | describe('prompt', () => { 8 | const mockCreateChatCompletion = jest.fn(); 9 | const mockOpenai = { 10 | createChatCompletion: mockCreateChatCompletion, 11 | }; 12 | afterEach(() => { 13 | jest.resetAllMocks(); 14 | }); 15 | test('returns empty string when no message is provided', async () => { 16 | // eslint-disable-next-line 17 | // @ts-ignore 18 | const result = await prompt([], mockOpenai); 19 | expect(result).toBe(''); 20 | expect(mockCreateChatCompletion).toHaveBeenCalled(); 21 | }); 22 | 23 | test('returns response from createChatCompletion', async () => { 24 | const mockResponse: CreateChatCompletionResponse = { 25 | id: '123', 26 | object: 'object', 27 | created: 123, 28 | model: 'model', 29 | choices: [ 30 | { 31 | message: { 32 | role: ChatCompletionRequestMessageRoleEnum.Assistant, 33 | content: 'Hello, world!', 34 | }, 35 | }, 36 | ], 37 | }; 38 | mockCreateChatCompletion.mockResolvedValue({ 39 | data: mockResponse, 40 | }); 41 | 42 | const messages = [ 43 | { role: ChatCompletionRequestMessageRoleEnum.User, content: 'Hi!' }, 44 | ]; 45 | const options = { engine: 'davinci', maxTokens: 10 }; 46 | // eslint-disable-next-line 47 | // @ts-ignore 48 | const result = await prompt(messages, mockOpenai, options); 49 | 50 | expect(mockCreateChatCompletion).toHaveBeenCalledWith({ 51 | ...options, 52 | messages, 53 | }); 54 | expect(result).toBe(mockResponse?.choices?.[0]?.message?.content); 55 | }); 56 | 57 | test('returns empty string when no message content is provided', async () => { 58 | const mockResponse: CreateChatCompletionResponse = { 59 | id: '123', 60 | object: 'object', 61 | created: 123, 62 | model: 'model', 63 | choices: [ 64 | { 65 | // eslint-disable-next-line 66 | // @ts-ignore 67 | message: {}, 68 | }, 69 | ], 70 | }; 71 | mockCreateChatCompletion.mockResolvedValue({ 72 | data: mockResponse, 73 | }); 74 | 75 | const messages = [{ text: 'Hi!' }]; 76 | // eslint-disable-next-line 77 | // @ts-ignore 78 | const result = await prompt(messages, mockOpenai); 79 | 80 | expect(mockCreateChatCompletion).toHaveBeenCalled(); 81 | expect(result).toBe(''); 82 | }); 83 | 84 | test('returns empty string when response is undefined', async () => { 85 | mockCreateChatCompletion.mockResolvedValue(undefined); 86 | const messages = [{ text: 'Hi!' }]; 87 | // eslint-disable-next-line 88 | // @ts-ignore 89 | const result = await prompt(messages, mockOpenai); 90 | 91 | expect(mockCreateChatCompletion).toHaveBeenCalled(); 92 | expect(result).toBe(''); 93 | }); 94 | }); 95 | -------------------------------------------------------------------------------- /dist/src/__tests__/textNormalization.test.js: -------------------------------------------------------------------------------- 1 | "use strict"; 2 | Object.defineProperty(exports, "__esModule", { value: true }); 3 | const textNormalization_1 = require("../textNormalization"); 4 | describe('getCodeBlock', () => { 5 | test('returns null for input without code block', () => { 6 | const text = 'This is some text without a code block.'; 7 | expect((0, textNormalization_1.getCodeBlock)(text)).toBeNull(); 8 | }); 9 | test('returns normalized code block for input with code block', () => { 10 | const text = 'This is some text with a code block:\n```js\nconsole.log("Hello, world!");\n```'; 11 | const expected = 'console.log("Hello, world!");'; 12 | expect((0, textNormalization_1.getCodeBlock)(text)).toBe(expected); 13 | }); 14 | test('normalizes leading/trailing whitespace', () => { 15 | const text = 'Here is a code block with leading/trailing whitespace:\n```\n foo \n```'; 16 | const expected = 'foo'; 17 | expect((0, textNormalization_1.getCodeBlock)(text)).toBe(expected); 18 | }); 19 | test('normalizes multiple lines of code', () => { 20 | const text = 'Here is a code block with multiple lines:\n```html\n

Hello, world!

\n

Welcome to my website.

\n```'; 21 | const expected = '

Hello, world!

\n

Welcome to my website.

'; 22 | expect((0, textNormalization_1.getCodeBlock)(text)).toBe(expected); 23 | }); 24 | test('normalizes empty code block', () => { 25 | const text = 'Here is an empty code block:\n```\n```'; 26 | expect((0, textNormalization_1.getCodeBlock)(text)).toBeNull(); 27 | }); 28 | test('normalizes code block with leading/trailing newlines', () => { 29 | const text = '\nHere is a code block with leading/trailing newlines:\n```\n\nfoo\n\n```'; 30 | const expected = 'foo'; 31 | expect((0, textNormalization_1.getCodeBlock)(text)).toBe(expected); 32 | }); 33 | test('normalizes code block with leading/trailing backticks', () => { 34 | const text = 'Here is a code block with leading/trailing backticks:\n```js```\nconsole.log("Hello, world!");\n``````'; 35 | const expected = 'console.log("Hello, world!");'; 36 | expect((0, textNormalization_1.getCodeBlock)(text)).toBe(expected); 37 | }); 38 | test('normalizes multiple lines of code', () => { 39 | const text = 'Here is a code block with multiple lines:\n```js\nfunction add(a, b) {\n return a + b;\n}\n```'; 40 | const expected = 'function add(a, b) {\n return a + b;\n}'; 41 | expect((0, textNormalization_1.getCodeBlock)(text)).toBe(expected); 42 | }); 43 | test('normalizes multiple lines of code', () => { 44 | const text = 'Here is a code block with multiple lines:\n```json\n{\n "name": "John",\n "age": 30,\n "city": "New York"\n}\n```'; 45 | const expected = '{\n "name": "John",\n "age": 30,\n "city": "New York"\n}'; 46 | expect((0, textNormalization_1.getCodeBlock)(text)).toBe(expected); 47 | }); 48 | }); 49 | -------------------------------------------------------------------------------- /dist/src/utils.js: -------------------------------------------------------------------------------- 1 | "use strict"; 2 | var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { 3 | if (k2 === undefined) k2 = k; 4 | var desc = Object.getOwnPropertyDescriptor(m, k); 5 | if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { 6 | desc = { enumerable: true, get: function() { return m[k]; } }; 7 | } 8 | Object.defineProperty(o, k2, desc); 9 | }) : (function(o, m, k, k2) { 10 | if (k2 === undefined) k2 = k; 11 | o[k2] = m[k]; 12 | })); 13 | var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { 14 | Object.defineProperty(o, "default", { enumerable: true, value: v }); 15 | }) : function(o, v) { 16 | o["default"] = v; 17 | }); 18 | var __importStar = (this && this.__importStar) || function (mod) { 19 | if (mod && mod.__esModule) return mod; 20 | var result = {}; 21 | if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); 22 | __setModuleDefault(result, mod); 23 | return result; 24 | }; 25 | var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { 26 | function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } 27 | return new (P || (P = Promise))(function (resolve, reject) { 28 | function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } 29 | function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } 30 | function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } 31 | step((generator = generator.apply(thisArg, _arguments || [])).next()); 32 | }); 33 | }; 34 | Object.defineProperty(exports, "__esModule", { value: true }); 35 | exports.runScript = void 0; 36 | function runScript(script) { 37 | return __awaiter(this, void 0, void 0, function* () { 38 | const result = { 39 | exports: null, 40 | }; 41 | let NodeVM; 42 | if (typeof window === 'undefined') { 43 | NodeVM = (yield Promise.resolve().then(() => __importStar(require('vm2')))).NodeVM; 44 | // Create a new context for the script 45 | const vm = new NodeVM({ 46 | console: 'inherit', 47 | wrapper: 'none', 48 | sandbox: { 49 | result, 50 | }, 51 | require: { 52 | external: true, 53 | builtin: ['*'], 54 | root: './', 55 | }, 56 | }); 57 | // Run the script in the context and capture the result 58 | const vmExports = yield vm.run(script); 59 | // Return the result 60 | return vmExports; 61 | } 62 | else { 63 | return null; 64 | } 65 | }); 66 | } 67 | exports.runScript = runScript; 68 | -------------------------------------------------------------------------------- /src/GPTPromptKit.ts: -------------------------------------------------------------------------------- 1 | import { Lang, Interpreter } from './constant'; 2 | import { getCodeBlock as defaultGetCodeBlock } from './textNormalization'; 3 | 4 | interface PromptEngineering { 5 | /** 6 | * Returns a function that translates the given text from the specified source language to the target language. 7 | * @param {string} from The source language. 8 | * @param {string} to The target language. 9 | * @returns {(text: string) => string} A function that takes a string input and returns the translated string. 10 | */ 11 | translate: (from: Lang, to: Lang) => (text: string) => Promise; 12 | 13 | /** 14 | * Returns a function that formats the given input data into the specified JSON schema. 15 | * @param {object} schema The JSON schema to format the data into. 16 | * @returns {(description: string, input: object) => string} A function that takes an input object and returns the formatted JSON string. 17 | */ 18 | formatJson: ( 19 | schema: Record 20 | ) => (description: string, input: object) => Promise; 21 | 22 | /** 23 | * Returns a function that formats the given input data according to the specified format string. 24 | * @param {string format The format string to use for formatting the input data. 25 | * @returns {(description: string) => string} A function that takes an description and returns the formatted string. 26 | */ 27 | formatFree: (format: string) => (description: string) => Promise; 28 | } 29 | 30 | class GPTPromptKit implements PromptEngineering { 31 | // prompt method, pass when construct 32 | private prompt: (text: string) => Promise; 33 | private getCodeBlock: (text: string) => string | null; 34 | 35 | constructor( 36 | prompt: (text: string) => Promise, 37 | getCodeBlock: (text: string) => string | null = defaultGetCodeBlock 38 | ) { 39 | this.prompt = prompt; 40 | this.getCodeBlock = getCodeBlock; 41 | } 42 | 43 | // translate method 44 | translate(from: Lang, to: Lang) { 45 | return (text: string) => { 46 | return this.prompt(`A ${from} phrase is provided: ${text} 47 | The masterful ${from} translator flawlessly translates the phrase into ${to}:`); 48 | }; 49 | } 50 | 51 | // formatJson method 52 | formatJson(schema: Record) { 53 | return async (description: string, input: object) => { 54 | const promptResult = await this.prompt(` 55 | ${description}\n 56 | Add \`\`\` at the start and end of json:\n 57 | ${Object.keys(schema) 58 | .map((key) => `${key}: ${schema[key]}`) 59 | .join('\n // ')} 60 | 61 | input = ${JSON.stringify(input, null, 4)} 62 | Use JSON format: 63 | \`\`\` 64 | 65 | \`\`\` 66 | `); 67 | 68 | const codeBlock = this.getCodeBlock(promptResult); 69 | 70 | if (codeBlock) { 71 | return JSON.parse(codeBlock); 72 | } 73 | 74 | return promptResult; 75 | }; 76 | } 77 | 78 | // formatFree method 79 | formatFree(schema: string) { 80 | return async (description: string) => { 81 | const promptResult = await this.prompt(` 82 | ${description}\n 83 | Use this format, add \`\`\` at the start and end of content:\n 84 | ${schema} 85 | `); 86 | 87 | return this.getCodeBlock(promptResult) ?? promptResult; 88 | }; 89 | } 90 | } 91 | 92 | export default GPTPromptKit; 93 | -------------------------------------------------------------------------------- /dist/src/PromptCraft.js: -------------------------------------------------------------------------------- 1 | "use strict"; 2 | var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { 3 | function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } 4 | return new (P || (P = Promise))(function (resolve, reject) { 5 | function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } 6 | function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } 7 | function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } 8 | step((generator = generator.apply(thisArg, _arguments || [])).next()); 9 | }); 10 | }; 11 | Object.defineProperty(exports, "__esModule", { value: true }); 12 | const textNormalization_1 = require("./textNormalization"); 13 | const utils_1 = require("./utils"); 14 | class GPTPromptKit { 15 | constructor(prompt, getCodeBlock = textNormalization_1.getCodeBlock) { 16 | this.prompt = prompt; 17 | this.getCodeBlock = getCodeBlock; 18 | } 19 | // translate method 20 | translate(from, to) { 21 | return (text) => { 22 | return this.prompt(`A ${from} phrase is provided: ${text} 23 | The masterful ${from} translator flawlessly translates the phrase into ${to}:`); 24 | }; 25 | } 26 | // formatJson method 27 | formatJson(schema) { 28 | return (description, input) => __awaiter(this, void 0, void 0, function* () { 29 | const promptResult = yield this.prompt(` 30 | ${description}\n 31 | Use JSON format, add \`\`\` at the start and end of json:\n 32 | ${Object.keys(schema) 33 | .map((key) => `${key}: ${schema[key]}`) 34 | .join('\n // ')} 35 | 36 | input = ${JSON.stringify(input, null, 4)} 37 | `); 38 | const codeBlock = this.getCodeBlock(promptResult); 39 | if (codeBlock) { 40 | return JSON.parse(codeBlock); 41 | } 42 | return promptResult; 43 | }); 44 | } 45 | // formatFree method 46 | formatFree(schema) { 47 | return (description) => __awaiter(this, void 0, void 0, function* () { 48 | var _a; 49 | const promptResult = yield this.prompt(` 50 | ${description}\n 51 | Use this format, add \`\`\` at the start and end of content:\n 52 | ${schema} 53 | `); 54 | return (_a = this.getCodeBlock(promptResult)) !== null && _a !== void 0 ? _a : promptResult; 55 | }); 56 | } 57 | // useInterpreter method 58 | useInterpreter(interpreter, runCode) { 59 | return (question) => __awaiter(this, void 0, void 0, function* () { 60 | const promptResult = yield this.prompt(` 61 | Write an ${interpreter} program to answer the following question.\n 62 | Write a function to solution the problem, call the function and return at the end of the code.\n 63 | Don't use any third party module expect nodejs build-in module.\n 64 | Use this format:\n 65 | \`\`\` 66 | <${interpreter} function and output needed to find answer>\n 67 | 68 | return \n 69 | \`\`\`\n 70 | 71 | Begin.\n 72 | ${question} 73 | `); 74 | const codeBlock = this.getCodeBlock(promptResult); 75 | if (runCode && codeBlock) { 76 | return yield (0, utils_1.runScript)(codeBlock); 77 | } 78 | if (codeBlock) { 79 | return codeBlock; 80 | } 81 | return promptResult; 82 | }); 83 | } 84 | } 85 | exports.default = GPTPromptKit; 86 | -------------------------------------------------------------------------------- /src/__tests__/GPTPromptKit.test.ts: -------------------------------------------------------------------------------- 1 | import { Interpreter, Lang } from '../constant'; 2 | import GPTPromptKit from '../GPTPromptKit'; 3 | import * as defaultPrompt from '../prompt'; 4 | 5 | // mock ./prompt 6 | jest.mock('../prompt', () => { 7 | return { 8 | promptWithTextGenerator: jest.fn(), 9 | }; 10 | }); 11 | 12 | describe('GPTPromptKit', () => { 13 | const getCodeBlock = jest.fn(); 14 | const mockPrompt = jest.fn(); 15 | const gptPromptKit: GPTPromptKit = new GPTPromptKit(mockPrompt, getCodeBlock); 16 | beforeEach(() => { 17 | getCodeBlock.mockClear(); 18 | mockPrompt.mockClear(); 19 | }); 20 | 21 | it('should init an instance with correct api key when new a gptPromptKit', () => { 22 | expect(gptPromptKit).toBeDefined(); 23 | }); 24 | 25 | it('should call prompt with correct text when call translate', async () => { 26 | const from = Lang.French; 27 | const to = Lang.English; 28 | const translator = gptPromptKit.translate(from, to); 29 | const text = 'hello'; 30 | 31 | await translator(text); 32 | 33 | expect(mockPrompt).toBeCalledWith(`A ${from} phrase is provided: ${text} 34 | The masterful ${from} translator flawlessly translates the phrase into ${to}:`); 35 | }); 36 | 37 | it('should call prompt with correct text when call formatJson', async () => { 38 | const jsonSchema = { 39 | page_name: 'The name of the page to get the text for.', 40 | page_url: 'The URL of the page.', 41 | page_text: 'The text of the page.', 42 | }; 43 | const description = `Give the URL and text of the Wikipedia article for the given 44 | page name.`; 45 | const input = { 46 | page_name: 'Taken 4: The Musical', 47 | }; 48 | const formatJsonWithSchema = gptPromptKit.formatJson(jsonSchema); 49 | 50 | await formatJsonWithSchema(description, input); 51 | 52 | expect(mockPrompt.mock.calls).toMatchInlineSnapshot(` 53 | [ 54 | [ 55 | " 56 | Give the URL and text of the Wikipedia article for the given 57 | page name. 58 | 59 | Add \`\`\` at the start and end of json: 60 | 61 | page_name: The name of the page to get the text for. 62 | // page_url: The URL of the page. 63 | // page_text: The text of the page. 64 | 65 | input = { 66 | "page_name": "Taken 4: The Musical" 67 | } 68 | Use JSON format: 69 | \`\`\` 70 | 71 | \`\`\` 72 | ", 73 | ], 74 | ] 75 | `); 76 | expect(getCodeBlock).toBeCalled(); 77 | }); 78 | 79 | it('should call prompt with correct text when call formatFree', async () => { 80 | const customSchema = ` 81 | Tilte: 82 | ## Abstract ## 83 | <Text of abstract> 84 | ## Sections ## 85 | <Numbered list of 10 top-level sections> 86 | ## Content ## 87 | <Text of entire arXiv pre-print in LaTeX notation> 88 | `; 89 | const description = `Generate an arXiv pre-print with the given title.`; 90 | const formatFreeWithSchema = gptPromptKit.formatFree(customSchema); 91 | 92 | await formatFreeWithSchema(description); 93 | 94 | expect(mockPrompt.mock.calls).toMatchInlineSnapshot(` 95 | [ 96 | [ 97 | " 98 | Generate an arXiv pre-print with the given title. 99 | 100 | Use this format, add \`\`\` at the start and end of content: 101 | 102 | 103 | Tilte: <Title> 104 | ## Abstract ## 105 | <Text of abstract> 106 | ## Sections ## 107 | <Numbered list of 10 top-level sections> 108 | ## Content ## 109 | <Text of entire arXiv pre-print in LaTeX notation> 110 | 111 | ", 112 | ], 113 | ] 114 | `); 115 | 116 | expect(getCodeBlock).toBeCalled(); 117 | }); 118 | }); 119 | -------------------------------------------------------------------------------- /dist/src/__tests__/prompt.test.js: -------------------------------------------------------------------------------- 1 | "use strict"; 2 | var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { 3 | function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } 4 | return new (P || (P = Promise))(function (resolve, reject) { 5 | function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } 6 | function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } 7 | function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } 8 | step((generator = generator.apply(thisArg, _arguments || [])).next()); 9 | }); 10 | }; 11 | Object.defineProperty(exports, "__esModule", { value: true }); 12 | const prompt_1 = require("../prompt"); 13 | const openai_1 = require("openai"); 14 | describe('prompt', () => { 15 | const mockCreateChatCompletion = jest.fn(); 16 | const mockOpenai = { 17 | createChatCompletion: mockCreateChatCompletion, 18 | }; 19 | afterEach(() => { 20 | jest.resetAllMocks(); 21 | }); 22 | test('returns empty string when no message is provided', () => __awaiter(void 0, void 0, void 0, function* () { 23 | // eslint-disable-next-line 24 | // @ts-ignore 25 | const result = yield (0, prompt_1.prompt)([], mockOpenai); 26 | expect(result).toBe(''); 27 | expect(mockCreateChatCompletion).toHaveBeenCalled(); 28 | })); 29 | test('returns response from createChatCompletion', () => __awaiter(void 0, void 0, void 0, function* () { 30 | var _a, _b, _c; 31 | const mockResponse = { 32 | id: '123', 33 | object: 'object', 34 | created: 123, 35 | model: 'model', 36 | choices: [ 37 | { 38 | message: { 39 | role: openai_1.ChatCompletionRequestMessageRoleEnum.Assistant, 40 | content: 'Hello, world!', 41 | }, 42 | }, 43 | ], 44 | }; 45 | mockCreateChatCompletion.mockResolvedValue({ 46 | data: mockResponse, 47 | }); 48 | const messages = [ 49 | { role: openai_1.ChatCompletionRequestMessageRoleEnum.User, content: 'Hi!' }, 50 | ]; 51 | const options = { engine: 'davinci', maxTokens: 10 }; 52 | // eslint-disable-next-line 53 | // @ts-ignore 54 | const result = yield (0, prompt_1.prompt)(messages, mockOpenai, options); 55 | expect(mockCreateChatCompletion).toHaveBeenCalledWith(Object.assign(Object.assign({}, options), { messages })); 56 | expect(result).toBe((_c = (_b = (_a = mockResponse === null || mockResponse === void 0 ? void 0 : mockResponse.choices) === null || _a === void 0 ? void 0 : _a[0]) === null || _b === void 0 ? void 0 : _b.message) === null || _c === void 0 ? void 0 : _c.content); 57 | })); 58 | test('returns empty string when no message content is provided', () => __awaiter(void 0, void 0, void 0, function* () { 59 | const mockResponse = { 60 | id: '123', 61 | object: 'object', 62 | created: 123, 63 | model: 'model', 64 | choices: [ 65 | { 66 | // eslint-disable-next-line 67 | // @ts-ignore 68 | message: {}, 69 | }, 70 | ], 71 | }; 72 | mockCreateChatCompletion.mockResolvedValue({ 73 | data: mockResponse, 74 | }); 75 | const messages = [{ text: 'Hi!' }]; 76 | // eslint-disable-next-line 77 | // @ts-ignore 78 | const result = yield (0, prompt_1.prompt)(messages, mockOpenai); 79 | expect(mockCreateChatCompletion).toHaveBeenCalled(); 80 | expect(result).toBe(''); 81 | })); 82 | test('returns empty string when response is undefined', () => __awaiter(void 0, void 0, void 0, function* () { 83 | mockCreateChatCompletion.mockResolvedValue(undefined); 84 | const messages = [{ text: 'Hi!' }]; 85 | // eslint-disable-next-line 86 | // @ts-ignore 87 | const result = yield (0, prompt_1.prompt)(messages, mockOpenai); 88 | expect(mockCreateChatCompletion).toHaveBeenCalled(); 89 | expect(result).toBe(''); 90 | })); 91 | }); 92 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # GPTPromptKit 📚 2 | 3 | **Get Format DATA(Like JSON) from GPT!** 4 | GPTPromptKit is a library that helps developers interact with AI language models more effectively by using prompt engineering techniques. The library offers several techniques that can be used depending on the situation, improving the clarity and accuracy of prompts, and enabling more effective communication with users. 5 | 6 | repo: [gpt-prompt-kit](https://github.com/clean99/gpt-prompt-kit) 7 | 8 | ## Features 🎁 9 | 10 | 1. **Translate** 🌐 : Ask questions in a clear and concise manner to improve translation accuracy. 11 | 2. **Format (Text Normalization)** 📝: Use a specific format to prompt the user with two available options: 12 | - **JSON**: Provide a JSON schema and input, and receive output in this format. 13 | - **Free**: Specify any desired format and receive output accordingly. 14 | 3. **ChainOfThought** 🤔: Prompt GPT to think through the problem step by step.(Coming soon) 15 | 16 | ## Installation 📦 17 | 18 | Install GPTPromptKit using npm: 19 | 20 | ``` 21 | npm install gpt-prompt-kit 22 | ``` 23 | 24 | 25 | ## Usage 🚀 26 | 27 | Create a new file named `index.js` and add the following code: 28 | 29 | ```javascript 30 | import { GPTPromptKit, gptPromptKitFactory } from 'gpt-prompt-kit'; 31 | 32 | // custom your prompt function to create a gPTPromptKit instance. 33 | const prompt = (text) => { 34 | // Your function to send the text to GPT and receive a response 35 | }; 36 | 37 | const gptPromptKit = new GPTPromptKit(prompt); 38 | 39 | // or you can just pass API_KEY to use the build-in GPT-3.5 model 40 | 41 | const gptPromptKit = gptPromptKitFactory(API_KEY); 42 | 43 | // Example usage: 44 | // Translate 45 | const translate = gptPromptKit.translate(Lang.English, Lang.Chinese); 46 | translate('Hello, world!').then(console.log); 47 | 48 | // Format JSON 49 | const formatJson = gptPromptKit.formatJson({ key: 'explain it', key2: 'explain it' }); 50 | formatJson('Description here', { key: 'example' }).then(console.log); 51 | 52 | // Format Free 53 | const formatFree = gptPromptKit.formatFree('Any format template you want'); 54 | formatFree('Description here').then(console.log); 55 | 56 | ``` 57 | 58 | ## Demo 🥸 59 | 60 | In demo directory there are some use demo for you to test the abilities of this library. 61 | 62 | To use those demo: 63 | 64 | 1. Install dependencies: 65 | 66 | ``` 67 | npm install 68 | ``` 69 | 70 | 2. Compile & Run the demo: 71 | 72 | ``` 73 | tsc demo/translate.ts 74 | node demo/translate.js 75 | ``` 76 | 77 | ### Translate 78 | 79 | ![translator](https://github.com/clean99/gpt-prompt-kit/blob/main//demo-img/translate.png "translator") 80 | ![translator](https://github.com/clean99/gpt-prompt-kit/blob/main//demo-img/translate2.png "translator") 81 | 82 | ### Format JSON 83 | 84 | You can get a JSON string with any fields you want: 85 | 86 | ![formatJson](https://github.com/clean99/gpt-prompt-kit/blob/main//demo-img/formatJSON.png "formatJson") 87 | ![formatJson](https://github.com/clean99/gpt-prompt-kit/blob/main//demo-img/formatJSON2.png "formatJson") 88 | 89 | ### Format Free 90 | 91 | ![formatFree](https://github.com/clean99/gpt-prompt-kit/blob/main//demo-img/formatFree.png "formatFree") 92 | ![formatFree](https://github.com/clean99/gpt-prompt-kit/blob/main//demo-img/formatFree2.png "formatFree") 93 | 94 | ## Changelog 📝 95 | 96 | ### 1.1.1 97 | - delete interpreter so that browser also can use this library. 98 | - add customize option for gptPromptKitFactory. Now we can use different GPT model. 99 | ![customizedOptions](https://github.com/clean99/gpt-prompt-kit/blob/main//demo-img/customizedOptions.png "customizedOptions") 100 | 101 | ## Development 🛠️ 102 | 103 | To contribute to GPTPromptKit, follow these steps: 104 | 105 | 1. Clone the repository and install dependencies: 106 | 107 | ``` 108 | git clone https://github.com/clean99/gpt-prompt-kit.git 109 | cd gpt-prompt-kit 110 | npm install 111 | ``` 112 | 113 | 2. Build the project: 114 | 115 | ``` 116 | npm run build 117 | ``` 118 | 119 | 3. Test the project: 120 | 121 | ``` 122 | npm test 123 | ``` 124 | 125 | 4. Lint the project: 126 | 127 | ``` 128 | npm run lint 129 | ``` 130 | 131 | 5. Format the project: 132 | 133 | ``` 134 | npm run format 135 | ``` 136 | 137 | ## Contributing 🤝 138 | We welcome contributions to GPTPromptKit! If you'd like to contribute, please fork the repository, create a new branch, make your changes, and submit a pull request. 139 | 140 | ## License 📄 141 | GPTPromptKit is licensed under the [MIT License](/LICENSE). 142 | 143 | ``` 144 | 145 | Feel free to modify the code snippets, installation, usage, and contributing sections as necessary to match your library's actual implementation and requirements. 146 | ``` 147 | -------------------------------------------------------------------------------- /dist/demo/formatFree.d.ts: -------------------------------------------------------------------------------- 1 | export {}; 2 | /** 3 | * ```Title: What is GPT-3. 4 | 5 | ## Abstract ## 6 | In recent years, the field of natural language processing (NLP) has seen a significant breakthrough with the development of large-scale language models such as GPT-3. This paper aims to provide a comprehensive understanding of what GPT-3 is, how it works, and its potential applications. We discuss the technical details of GPT-3, including its architecture, training data, and inference process. Additionally, we highlight some of the limitations and ethical concerns associated with this technology. 7 | 8 | ## Sections ## 9 | 1. Introduction 10 | 2. Background on NLP 11 | 3. Overview of GPT-3 12 | 4. Architecture of GPT-3 13 | 5. Training data for GPT-3 14 | 6. Inference process of GPT-3 15 | 7. Applications of GPT-3 16 | 8. Limitations of GPT-3 17 | 9. Ethical concerns with GPT-3 18 | 10. Conclusion 19 | 20 | ## Content ## 21 | 22 | \section{Introduction} 23 | In recent years, there has been a significant breakthrough in the field of natural language processing (NLP) with the development of large-scale language models such as GPT-3. GPT-3, which stands for Generative Pre-trained Transformer 3, is a state-of-the-art language model developed by OpenAI. It is capable of generating human-like text, completing sentences, and answering questions with a high degree of accuracy. 24 | 25 | \section{Background on NLP} 26 | NLP is a subfield of artificial intelligence (AI) that focuses on the interaction between computers and human language. It involves the development of algorithms and models that can understand, interpret, and generate human language. NLP has numerous applications, including machine translation, sentiment analysis, and chatbots. 27 | 28 | \section{Overview of GPT-3} 29 | GPT-3 is a language model that uses deep learning techniques to generate human-like text. It is a neural network that has been pre-trained on a massive amount of text data, allowing it to generate coherent and contextually appropriate text. GPT-3 is the largest and most powerful language model developed to date, with over 175 billion parameters. 30 | 31 | \section{Architecture of GPT-3} 32 | GPT-3 uses a transformer architecture, which is a type of neural network that is specifically designed for NLP tasks. The transformer architecture consists of an encoder and a decoder. The encoder processes the input text and creates a representation of the text, while the decoder generates the output text based on the representation created by the encoder. 33 | 34 | \section{Training data for GPT-3} 35 | GPT-3 was trained on a massive amount of text data, including books, articles, and websites. The training data was sourced from a variety of domains, including science, literature, and social media. The large amount of training data allows GPT-3 to generate text that is contextually appropriate and coherent. 36 | 37 | \section{Inference process of GPT-3} 38 | The inference process of GPT-3 involves feeding the model with a prompt, which is a piece of text that provides context for the generated text. The model uses the prompt to generate text that is contextually appropriate and coherent. GPT-3 can generate text in a variety of formats, including prose, poetry, and code. 39 | 40 | \section{Applications of GPT-3} 41 | GPT-3 has numerous applications, including content creation, chatbots, and language translation. It can be used to generate high-quality content for websites, social media, and marketing campaigns. GPT-3 can also be used to create chatbots that can interact with users in a natural and human-like way. Additionally, GPT-3 can be used for language translation, allowing users to translate text from one language to another with a high degree of accuracy. 42 | 43 | \section{Limitations of GPT-3} 44 | Despite its impressive capabilities, GPT-3 has some limitations. One of the main limitations is its inability to understand context beyond the prompt. This means that GPT-3 may generate text that is inappropriate or offensive if the prompt is not carefully crafted. Additionally, GPT-3 may generate text that is biased or discriminatory if the training data is biased. 45 | 46 | \section{Ethical concerns with GPT-3} 47 | GPT-3 raises several ethical concerns, including the potential for misuse and the impact on employment. GPT-3 can be used to generate fake news, propaganda, and malicious content, which can have a significant impact on society. Additionally, GPT-3 has the potential to automate many jobs that require human language skills, which could lead to widespread unemployment. 48 | 49 | \section{Conclusion} 50 | In conclusion, GPT-3 is a state-of-the-art language model that has the potential to revolutionize the field of NLP. It is capable of generating human-like text, completing sentences, and answering questions with a high degree of accuracy. However, it also raises several ethical concerns, and its limitations must be carefully considered. As NLP continues to evolve, it is essential to ensure that these technologies are developed and used in a responsible and ethical manner.``` 51 | */ 52 | -------------------------------------------------------------------------------- /dist/src/__tests__/GPTPromptKit.test.js: -------------------------------------------------------------------------------- 1 | "use strict"; 2 | var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { 3 | function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } 4 | return new (P || (P = Promise))(function (resolve, reject) { 5 | function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } 6 | function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } 7 | function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } 8 | step((generator = generator.apply(thisArg, _arguments || [])).next()); 9 | }); 10 | }; 11 | var __importDefault = (this && this.__importDefault) || function (mod) { 12 | return (mod && mod.__esModule) ? mod : { "default": mod }; 13 | }; 14 | Object.defineProperty(exports, "__esModule", { value: true }); 15 | const constant_1 = require("../constant"); 16 | const GPTPromptKit_1 = __importDefault(require("../GPTPromptKit")); 17 | // mock ./prompt 18 | jest.mock('../prompt', () => { 19 | return { 20 | promptWithTextGenerator: jest.fn(), 21 | }; 22 | }); 23 | describe('GPTPromptKit', () => { 24 | const getCodeBlock = jest.fn(); 25 | const mockPrompt = jest.fn(); 26 | const gptPromptKit = new GPTPromptKit_1.default(mockPrompt, getCodeBlock); 27 | beforeEach(() => { 28 | getCodeBlock.mockClear(); 29 | mockPrompt.mockClear(); 30 | }); 31 | it('should init an instance with correct api key when new a gptPromptKit', () => { 32 | expect(gptPromptKit).toBeDefined(); 33 | }); 34 | it('should call prompt with correct text when call translate', () => __awaiter(void 0, void 0, void 0, function* () { 35 | const from = constant_1.Lang.French; 36 | const to = constant_1.Lang.English; 37 | const translator = gptPromptKit.translate(from, to); 38 | const text = 'hello'; 39 | yield translator(text); 40 | expect(mockPrompt).toBeCalledWith(`A ${from} phrase is provided: ${text} 41 | The masterful ${from} translator flawlessly translates the phrase into ${to}:`); 42 | })); 43 | it('should call prompt with correct text when call formatJson', () => __awaiter(void 0, void 0, void 0, function* () { 44 | const jsonSchema = { 45 | page_name: 'The name of the page to get the text for.', 46 | page_url: 'The URL of the page.', 47 | page_text: 'The text of the page.', 48 | }; 49 | const description = `Give the URL and text of the Wikipedia article for the given 50 | page name.`; 51 | const input = { 52 | page_name: 'Taken 4: The Musical', 53 | }; 54 | const formatJsonWithSchema = gptPromptKit.formatJson(jsonSchema); 55 | yield formatJsonWithSchema(description, input); 56 | expect(mockPrompt.mock.calls).toMatchInlineSnapshot(` 57 | [ 58 | [ 59 | " 60 | Give the URL and text of the Wikipedia article for the given 61 | page name. 62 | 63 | Add \`\`\` at the start and end of json: 64 | 65 | page_name: The name of the page to get the text for. 66 | // page_url: The URL of the page. 67 | // page_text: The text of the page. 68 | 69 | input = { 70 | "page_name": "Taken 4: The Musical" 71 | } 72 | Use JSON format: 73 | \`\`\` 74 | <JSON string> 75 | \`\`\` 76 | ", 77 | ], 78 | ] 79 | `); 80 | expect(getCodeBlock).toBeCalled(); 81 | })); 82 | it('should call prompt with correct text when call formatFree', () => __awaiter(void 0, void 0, void 0, function* () { 83 | const customSchema = ` 84 | Tilte: <Title> 85 | ## Abstract ## 86 | <Text of abstract> 87 | ## Sections ## 88 | <Numbered list of 10 top-level sections> 89 | ## Content ## 90 | <Text of entire arXiv pre-print in LaTeX notation> 91 | `; 92 | const description = `Generate an arXiv pre-print with the given title.`; 93 | const formatFreeWithSchema = gptPromptKit.formatFree(customSchema); 94 | yield formatFreeWithSchema(description); 95 | expect(mockPrompt.mock.calls).toMatchInlineSnapshot(` 96 | [ 97 | [ 98 | " 99 | Generate an arXiv pre-print with the given title. 100 | 101 | Use this format, add \`\`\` at the start and end of content: 102 | 103 | 104 | Tilte: <Title> 105 | ## Abstract ## 106 | <Text of abstract> 107 | ## Sections ## 108 | <Numbered list of 10 top-level sections> 109 | ## Content ## 110 | <Text of entire arXiv pre-print in LaTeX notation> 111 | 112 | ", 113 | ], 114 | ] 115 | `); 116 | expect(getCodeBlock).toBeCalled(); 117 | })); 118 | }); 119 | -------------------------------------------------------------------------------- /demo/formatFree.ts: -------------------------------------------------------------------------------- 1 | import { gptPromptKitFactory } from '../src/index'; 2 | 3 | const gptPromptKit = gptPromptKitFactory('Your API key'); 4 | 5 | const formatFree = gptPromptKit.formatFree(` 6 | Tilte: <Title> 7 | ## Abstract ## 8 | <Text of abstract> 9 | ## Sections ## 10 | <Numbered list of 10 top-level sections> 11 | ## Content ## 12 | <Text of entire arXiv pre-print in LaTeX notation> 13 | `); 14 | 15 | const description = 16 | 'Generate an arXiv pre-print which the title is: What is GPT-3.'; 17 | 18 | formatFree(description).then(console.log); 19 | 20 | /** 21 | * ```Title: What is GPT-3. 22 | 23 | ## Abstract ## 24 | In recent years, the field of natural language processing (NLP) has seen a significant breakthrough with the development of large-scale language models such as GPT-3. This paper aims to provide a comprehensive understanding of what GPT-3 is, how it works, and its potential applications. We discuss the technical details of GPT-3, including its architecture, training data, and inference process. Additionally, we highlight some of the limitations and ethical concerns associated with this technology. 25 | 26 | ## Sections ## 27 | 1. Introduction 28 | 2. Background on NLP 29 | 3. Overview of GPT-3 30 | 4. Architecture of GPT-3 31 | 5. Training data for GPT-3 32 | 6. Inference process of GPT-3 33 | 7. Applications of GPT-3 34 | 8. Limitations of GPT-3 35 | 9. Ethical concerns with GPT-3 36 | 10. Conclusion 37 | 38 | ## Content ## 39 | 40 | \section{Introduction} 41 | In recent years, there has been a significant breakthrough in the field of natural language processing (NLP) with the development of large-scale language models such as GPT-3. GPT-3, which stands for Generative Pre-trained Transformer 3, is a state-of-the-art language model developed by OpenAI. It is capable of generating human-like text, completing sentences, and answering questions with a high degree of accuracy. 42 | 43 | \section{Background on NLP} 44 | NLP is a subfield of artificial intelligence (AI) that focuses on the interaction between computers and human language. It involves the development of algorithms and models that can understand, interpret, and generate human language. NLP has numerous applications, including machine translation, sentiment analysis, and chatbots. 45 | 46 | \section{Overview of GPT-3} 47 | GPT-3 is a language model that uses deep learning techniques to generate human-like text. It is a neural network that has been pre-trained on a massive amount of text data, allowing it to generate coherent and contextually appropriate text. GPT-3 is the largest and most powerful language model developed to date, with over 175 billion parameters. 48 | 49 | \section{Architecture of GPT-3} 50 | GPT-3 uses a transformer architecture, which is a type of neural network that is specifically designed for NLP tasks. The transformer architecture consists of an encoder and a decoder. The encoder processes the input text and creates a representation of the text, while the decoder generates the output text based on the representation created by the encoder. 51 | 52 | \section{Training data for GPT-3} 53 | GPT-3 was trained on a massive amount of text data, including books, articles, and websites. The training data was sourced from a variety of domains, including science, literature, and social media. The large amount of training data allows GPT-3 to generate text that is contextually appropriate and coherent. 54 | 55 | \section{Inference process of GPT-3} 56 | The inference process of GPT-3 involves feeding the model with a prompt, which is a piece of text that provides context for the generated text. The model uses the prompt to generate text that is contextually appropriate and coherent. GPT-3 can generate text in a variety of formats, including prose, poetry, and code. 57 | 58 | \section{Applications of GPT-3} 59 | GPT-3 has numerous applications, including content creation, chatbots, and language translation. It can be used to generate high-quality content for websites, social media, and marketing campaigns. GPT-3 can also be used to create chatbots that can interact with users in a natural and human-like way. Additionally, GPT-3 can be used for language translation, allowing users to translate text from one language to another with a high degree of accuracy. 60 | 61 | \section{Limitations of GPT-3} 62 | Despite its impressive capabilities, GPT-3 has some limitations. One of the main limitations is its inability to understand context beyond the prompt. This means that GPT-3 may generate text that is inappropriate or offensive if the prompt is not carefully crafted. Additionally, GPT-3 may generate text that is biased or discriminatory if the training data is biased. 63 | 64 | \section{Ethical concerns with GPT-3} 65 | GPT-3 raises several ethical concerns, including the potential for misuse and the impact on employment. GPT-3 can be used to generate fake news, propaganda, and malicious content, which can have a significant impact on society. Additionally, GPT-3 has the potential to automate many jobs that require human language skills, which could lead to widespread unemployment. 66 | 67 | \section{Conclusion} 68 | In conclusion, GPT-3 is a state-of-the-art language model that has the potential to revolutionize the field of NLP. It is capable of generating human-like text, completing sentences, and answering questions with a high degree of accuracy. However, it also raises several ethical concerns, and its limitations must be carefully considered. As NLP continues to evolve, it is essential to ensure that these technologies are developed and used in a responsible and ethical manner.``` 69 | */ 70 | -------------------------------------------------------------------------------- /dist/demo/formatFree.js: -------------------------------------------------------------------------------- 1 | "use strict"; 2 | Object.defineProperty(exports, "__esModule", { value: true }); 3 | const index_1 = require("../src/index"); 4 | const gptPromptKit = (0, index_1.gptPromptKitFactory)('Your API key'); 5 | const formatFree = gptPromptKit.formatFree(` 6 | Tilte: <Title> 7 | ## Abstract ## 8 | <Text of abstract> 9 | ## Sections ## 10 | <Numbered list of 10 top-level sections> 11 | ## Content ## 12 | <Text of entire arXiv pre-print in LaTeX notation> 13 | `); 14 | const description = 'Generate an arXiv pre-print which the title is: What is GPT-3.'; 15 | formatFree(description).then(console.log); 16 | /** 17 | * ```Title: What is GPT-3. 18 | 19 | ## Abstract ## 20 | In recent years, the field of natural language processing (NLP) has seen a significant breakthrough with the development of large-scale language models such as GPT-3. This paper aims to provide a comprehensive understanding of what GPT-3 is, how it works, and its potential applications. We discuss the technical details of GPT-3, including its architecture, training data, and inference process. Additionally, we highlight some of the limitations and ethical concerns associated with this technology. 21 | 22 | ## Sections ## 23 | 1. Introduction 24 | 2. Background on NLP 25 | 3. Overview of GPT-3 26 | 4. Architecture of GPT-3 27 | 5. Training data for GPT-3 28 | 6. Inference process of GPT-3 29 | 7. Applications of GPT-3 30 | 8. Limitations of GPT-3 31 | 9. Ethical concerns with GPT-3 32 | 10. Conclusion 33 | 34 | ## Content ## 35 | 36 | \section{Introduction} 37 | In recent years, there has been a significant breakthrough in the field of natural language processing (NLP) with the development of large-scale language models such as GPT-3. GPT-3, which stands for Generative Pre-trained Transformer 3, is a state-of-the-art language model developed by OpenAI. It is capable of generating human-like text, completing sentences, and answering questions with a high degree of accuracy. 38 | 39 | \section{Background on NLP} 40 | NLP is a subfield of artificial intelligence (AI) that focuses on the interaction between computers and human language. It involves the development of algorithms and models that can understand, interpret, and generate human language. NLP has numerous applications, including machine translation, sentiment analysis, and chatbots. 41 | 42 | \section{Overview of GPT-3} 43 | GPT-3 is a language model that uses deep learning techniques to generate human-like text. It is a neural network that has been pre-trained on a massive amount of text data, allowing it to generate coherent and contextually appropriate text. GPT-3 is the largest and most powerful language model developed to date, with over 175 billion parameters. 44 | 45 | \section{Architecture of GPT-3} 46 | GPT-3 uses a transformer architecture, which is a type of neural network that is specifically designed for NLP tasks. The transformer architecture consists of an encoder and a decoder. The encoder processes the input text and creates a representation of the text, while the decoder generates the output text based on the representation created by the encoder. 47 | 48 | \section{Training data for GPT-3} 49 | GPT-3 was trained on a massive amount of text data, including books, articles, and websites. The training data was sourced from a variety of domains, including science, literature, and social media. The large amount of training data allows GPT-3 to generate text that is contextually appropriate and coherent. 50 | 51 | \section{Inference process of GPT-3} 52 | The inference process of GPT-3 involves feeding the model with a prompt, which is a piece of text that provides context for the generated text. The model uses the prompt to generate text that is contextually appropriate and coherent. GPT-3 can generate text in a variety of formats, including prose, poetry, and code. 53 | 54 | \section{Applications of GPT-3} 55 | GPT-3 has numerous applications, including content creation, chatbots, and language translation. It can be used to generate high-quality content for websites, social media, and marketing campaigns. GPT-3 can also be used to create chatbots that can interact with users in a natural and human-like way. Additionally, GPT-3 can be used for language translation, allowing users to translate text from one language to another with a high degree of accuracy. 56 | 57 | \section{Limitations of GPT-3} 58 | Despite its impressive capabilities, GPT-3 has some limitations. One of the main limitations is its inability to understand context beyond the prompt. This means that GPT-3 may generate text that is inappropriate or offensive if the prompt is not carefully crafted. Additionally, GPT-3 may generate text that is biased or discriminatory if the training data is biased. 59 | 60 | \section{Ethical concerns with GPT-3} 61 | GPT-3 raises several ethical concerns, including the potential for misuse and the impact on employment. GPT-3 can be used to generate fake news, propaganda, and malicious content, which can have a significant impact on society. Additionally, GPT-3 has the potential to automate many jobs that require human language skills, which could lead to widespread unemployment. 62 | 63 | \section{Conclusion} 64 | In conclusion, GPT-3 is a state-of-the-art language model that has the potential to revolutionize the field of NLP. It is capable of generating human-like text, completing sentences, and answering questions with a high degree of accuracy. However, it also raises several ethical concerns, and its limitations must be carefully considered. As NLP continues to evolve, it is essential to ensure that these technologies are developed and used in a responsible and ethical manner.``` 65 | */ 66 | -------------------------------------------------------------------------------- /dist/src/__tests__/PromptCraft.test.js: -------------------------------------------------------------------------------- 1 | "use strict"; 2 | var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { 3 | function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } 4 | return new (P || (P = Promise))(function (resolve, reject) { 5 | function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } 6 | function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } 7 | function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } 8 | step((generator = generator.apply(thisArg, _arguments || [])).next()); 9 | }); 10 | }; 11 | var __importDefault = (this && this.__importDefault) || function (mod) { 12 | return (mod && mod.__esModule) ? mod : { "default": mod }; 13 | }; 14 | Object.defineProperty(exports, "__esModule", { value: true }); 15 | const constant_1 = require("../constant"); 16 | const GPTPromptKit_1 = __importDefault(require("../GPTPromptKit")); 17 | // mock ./prompt 18 | jest.mock('../prompt', () => { 19 | return { 20 | promptWithTextGenerator: jest.fn(), 21 | }; 22 | }); 23 | describe('GPTPromptKit', () => { 24 | const mockOpenai = jest.fn(); 25 | const getCodeBlock = jest.fn(); 26 | const mockPrompt = jest.fn(); 27 | const gptPromptKit = new GPTPromptKit_1.default(mockPrompt, getCodeBlock); 28 | beforeEach(() => { 29 | getCodeBlock.mockClear(); 30 | mockPrompt.mockClear(); 31 | }); 32 | it('should init an instance with correct api key when new a gptPromptKit', () => { 33 | expect(gptPromptKit).toBeDefined(); 34 | }); 35 | it('should call prompt with correct text when call translate', () => __awaiter(void 0, void 0, void 0, function* () { 36 | const from = constant_1.Lang.French; 37 | const to = constant_1.Lang.English; 38 | const translator = gptPromptKit.translate(from, to); 39 | const text = 'hello'; 40 | yield translator(text); 41 | expect(mockPrompt).toBeCalledWith(`A ${from} phrase is provided: ${text} 42 | The masterful ${from} translator flawlessly translates the phrase into ${to}:`); 43 | })); 44 | it('should call prompt with correct text when call formatJson', () => __awaiter(void 0, void 0, void 0, function* () { 45 | const jsonSchema = { 46 | page_name: 'The name of the page to get the text for.', 47 | page_url: 'The URL of the page.', 48 | page_text: 'The text of the page.', 49 | }; 50 | const description = `Give the URL and text of the Wikipedia article for the given 51 | page name.`; 52 | const input = { 53 | page_name: 'Taken 4: The Musical', 54 | }; 55 | const formatJsonWithSchema = gptPromptKit.formatJson(jsonSchema); 56 | yield formatJsonWithSchema(description, input); 57 | expect(mockPrompt.mock.calls).toMatchInlineSnapshot(` 58 | [ 59 | [ 60 | " 61 | Give the URL and text of the Wikipedia article for the given 62 | page name. 63 | 64 | Use JSON format, add \`\`\` at the start and end of json: 65 | 66 | page_name: The name of the page to get the text for. 67 | // page_url: The URL of the page. 68 | // page_text: The text of the page. 69 | 70 | input = { 71 | "page_name": "Taken 4: The Musical" 72 | } 73 | ", 74 | ], 75 | ] 76 | `); 77 | expect(getCodeBlock).toBeCalled(); 78 | })); 79 | it('should call prompt with correct text when call formatFree', () => __awaiter(void 0, void 0, void 0, function* () { 80 | const customSchema = ` 81 | Tilte: <Title> 82 | ## Abstract ## 83 | <Text of abstract> 84 | ## Sections ## 85 | <Numbered list of 10 top-level sections> 86 | ## Content ## 87 | <Text of entire arXiv pre-print in LaTeX notation> 88 | `; 89 | const description = `Generate an arXiv pre-print with the given title.`; 90 | const formatFreeWithSchema = gptPromptKit.formatFree(customSchema); 91 | yield formatFreeWithSchema(description); 92 | expect(mockPrompt.mock.calls).toMatchInlineSnapshot(` 93 | [ 94 | [ 95 | " 96 | Generate an arXiv pre-print with the given title. 97 | 98 | Use this format, add \`\`\` at the start and end of content: 99 | 100 | 101 | Tilte: <Title> 102 | ## Abstract ## 103 | <Text of abstract> 104 | ## Sections ## 105 | <Numbered list of 10 top-level sections> 106 | ## Content ## 107 | <Text of entire arXiv pre-print in LaTeX notation> 108 | 109 | ", 110 | ], 111 | ] 112 | `); 113 | expect(getCodeBlock).toBeCalled(); 114 | })); 115 | it('should call prompt with correct text when call useInterpreter', () => __awaiter(void 0, void 0, void 0, function* () { 116 | const interpreter = constant_1.Interpreter.JS_V8; 117 | const question = `What is the answer to life, the universe, and everything?`; 118 | const useInterpreterWithInterpreter = gptPromptKit.useInterpreter(interpreter); 119 | yield useInterpreterWithInterpreter(question); 120 | expect(mockPrompt.mock.calls).toMatchInlineSnapshot(` 121 | [ 122 | [ 123 | " 124 | Write an NodeJS program to answer the following question. 125 | 126 | Write a function to solution the problem, call the function and return at the end of the code. 127 | 128 | Don't use any third party module expect nodejs build-in module. 129 | 130 | Use this format: 131 | 132 | \`\`\` 133 | <NodeJS function and output needed to find answer> 134 | 135 | 136 | return <function call> 137 | 138 | \`\`\` 139 | 140 | 141 | Begin. 142 | 143 | What is the answer to life, the universe, and everything? 144 | ", 145 | ], 146 | ] 147 | `); 148 | expect(getCodeBlock).toBeCalled(); 149 | })); 150 | }); 151 | --------------------------------------------------------------------------------