ctod 0.1.5 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (42) hide show
  1. package/README.md +65 -105
  2. package/dist/index.js +1 -1
  3. package/examples/chat-demo.ts +70 -0
  4. package/examples/{applications/cosplay.ts → plugin-demo.ts} +20 -13
  5. package/lib/broker/chat.ts +277 -0
  6. package/lib/core/plugin.ts +9 -60
  7. package/lib/index.ts +13 -25
  8. package/lib/plugins/index.ts +6 -1
  9. package/lib/plugins/limiter.ts +4 -4
  10. package/lib/plugins/print-log.ts +32 -73
  11. package/lib/plugins/retry.ts +23 -30
  12. package/lib/plugins/role.ts +26 -33
  13. package/lib/service/{chatgpt35.ts → openai/chat.ts} +17 -32
  14. package/lib/service/{chatgpt3.ts → openai/completion.ts} +12 -27
  15. package/lib/service/{images-generations.ts → openai/images-generation.ts} +7 -22
  16. package/lib/service/openai/index.ts +43 -0
  17. package/package.json +2 -2
  18. package/types/lib/broker/{35.d.ts → chat.d.ts} +42 -17
  19. package/types/lib/core/plugin.d.ts +9 -43
  20. package/types/lib/index.d.ts +12 -25
  21. package/types/lib/plugins/index.d.ts +17 -19
  22. package/types/lib/plugins/limiter.d.ts +4 -4
  23. package/types/lib/plugins/print-log.d.ts +4 -15
  24. package/types/lib/plugins/retry.d.ts +5 -11
  25. package/types/lib/plugins/role.d.ts +4 -10
  26. package/types/lib/service/{chatgpt35.d.ts → openai/chat.d.ts} +14 -24
  27. package/types/lib/service/{chatgpt3.d.ts → openai/completion.d.ts} +9 -19
  28. package/types/lib/service/{images-generations.d.ts → openai/images-generation.d.ts} +4 -14
  29. package/types/lib/service/openai/index.d.ts +22 -0
  30. package/README-TW.md +0 -239
  31. package/TODO +0 -6
  32. package/examples/applications/bbc-news-reader.ts +0 -224
  33. package/examples/applications/story-generations.ts +0 -131
  34. package/examples/applications/talk-generations.ts +0 -257
  35. package/examples/chatgpt3.5-broker.ts +0 -79
  36. package/examples/chatgpt3.5.ts +0 -42
  37. package/examples/utils/index.ts +0 -56
  38. package/lib/broker/3.ts +0 -160
  39. package/lib/broker/35.ts +0 -207
  40. package/lib/broker/index.ts +0 -83
  41. package/types/lib/broker/3.d.ts +0 -71
  42. package/types/lib/broker/index.d.ts +0 -30
@@ -1,4 +1,4 @@
1
- import { Broker35Plugin } from '../core/plugin';
1
+ import { ChatBrokerPlugin } from '../core/plugin';
2
2
  declare type Events = {
3
3
  run: {
4
4
  id: string;
@@ -27,9 +27,9 @@ declare const _default: {
27
27
  */
28
28
  closeSchedule: () => void;
29
29
  /**
30
- * @zh 用於 Broker35 的版本。
31
- * @en The version for Broker35.
30
+ * @zh Plugin 的接口
31
+ * @en Plugin interface
32
32
  */
33
- ver35: Broker35Plugin<() => {}, () => {}>;
33
+ plugin: ChatBrokerPlugin<() => {}, () => {}>;
34
34
  };
35
35
  export default _default;
@@ -1,16 +1,5 @@
1
- import { Broker35Plugin, Broker3Plugin } from '../core/plugin';
2
- declare const _default: {
3
- /**
4
- * @zh 用於 Broker3 的版本。
5
- * @en The version for Broker3.
6
- */
7
- ver3: Broker3Plugin<() => {}, () => {}>;
8
- /**
9
- * @zh 用於 Broker35 的版本。
10
- * @en The version for Broker35.
11
- */
12
- ver35: Broker35Plugin<(yup: typeof import("yup")) => {
13
- detail: import("yup").BooleanSchema<boolean, import("yup").AnyObject, false, "d">;
14
- }, () => {}>;
15
- };
1
+ import { ChatBrokerPlugin } from '../core/plugin';
2
+ declare const _default: ChatBrokerPlugin<(yup: typeof import("yup")) => {
3
+ detail: import("yup").BooleanSchema<boolean, import("yup").AnyObject, false, "d">;
4
+ }, () => {}>;
16
5
  export default _default;
@@ -1,12 +1,6 @@
1
- import { Broker35Plugin } from '../core/plugin';
2
- declare const _default: {
3
- /**
4
- * @zh 用於 Broker35 的版本。
5
- * @en The version for Broker35.
6
- */
7
- ver35: Broker35Plugin<(yup: typeof import("yup")) => {
8
- retry: import("yup").NumberSchema<number, import("yup").AnyObject, 1, "d">;
9
- printWarn: import("yup").BooleanSchema<boolean, import("yup").AnyObject, true, "d">;
10
- }, () => {}>;
11
- };
1
+ import { ChatBrokerPlugin } from '../core/plugin';
2
+ declare const _default: ChatBrokerPlugin<(yup: typeof import("yup")) => {
3
+ retry: import("yup").NumberSchema<number, import("yup").AnyObject, 1, "d">;
4
+ printWarn: import("yup").BooleanSchema<boolean, import("yup").AnyObject, true, "d">;
5
+ }, () => {}>;
12
6
  export default _default;
@@ -1,11 +1,5 @@
1
- import { Broker35Plugin } from '../core/plugin';
2
- declare const _default: {
3
- /**
4
- * @zh 用於 Broker35 的版本。
5
- * @en The version for Broker35.
6
- */
7
- ver35: Broker35Plugin<(yup: typeof import("yup")) => {
8
- role: import("yup").StringSchema<string, import("yup").AnyObject, undefined, "">;
9
- }, () => {}>;
10
- };
1
+ import { ChatBrokerPlugin } from '../core/plugin';
2
+ declare const _default: ChatBrokerPlugin<(yup: typeof import("yup")) => {
3
+ role: import("yup").StringSchema<string, import("yup").AnyObject, undefined, "">;
4
+ }, () => {}>;
11
5
  export default _default;
@@ -1,6 +1,6 @@
1
- import { AxiosInstance } from 'axios';
2
- import { PromiseResponseType } from '../types';
3
- export declare type ChatGPT35Message = {
1
+ import { OpenAI } from './index';
2
+ import { PromiseResponseType } from '../../types';
3
+ declare type ChatGPTMessage = {
4
4
  role: 'system' | 'user' | 'assistant';
5
5
  name?: string;
6
6
  content: string;
@@ -31,30 +31,20 @@ declare type Config = {
31
31
  */
32
32
  n: number;
33
33
  /**
34
- * @zh 選擇運行的模型,16k意味著能處理長度為 16,384 的文本,而預設為 4096。
34
+ * @zh 選擇運行的模型,16k意味著能處理長度為 16,384 的文本,32k意味著能處理長度為 32768 的文本。
35
35
  * @en How many chat completion choices to generate for each input message.
36
36
  */
37
- model: 'gpt-3.5-turbo' | 'gpt-3.5-turbo-16k';
37
+ model: 'gpt-4' | 'gpt-4-32k' | 'gpt-3.5-turbo' | 'gpt-3.5-turbo-16k';
38
38
  /**
39
39
  * @zh 冒險指數,數值由 0 ~ 2 之間。
40
40
  * @en What sampling temperature to use, between 0 and 2. Higher values like 0.8 will make the output more random, while lower values like 0.2 will make it more focused and deterministic.
41
41
  */
42
42
  temperature: number;
43
43
  };
44
- export declare class ChatGPT35 {
45
- private axios;
46
- private apiKey;
47
- private config;
48
- /**
49
- * @zh 如果你有需要特別設定 axios,請使用這方法
50
- * @en If you need to set axios, use this method
51
- */
52
- setAxios(axios: AxiosInstance): void;
53
- /**
54
- * @zh 設定 api key
55
- * @en Set api key
56
- */
57
- setConfiguration(apiKey: string): void;
44
+ export declare class OpenAIChat {
45
+ openai: OpenAI;
46
+ config: Config;
47
+ constructor(openai: OpenAI);
58
48
  /**
59
49
  * @zh 改變對話的一些設定
60
50
  * @en Change some settings of the conversation
@@ -64,26 +54,26 @@ export declare class ChatGPT35 {
64
54
  * @zh 進行對話
65
55
  * @en Talk to the AI
66
56
  */
67
- talk(messages?: ChatGPT35Message[]): Promise<{
57
+ talk(messages?: ChatGPTMessage[]): Promise<{
68
58
  id: string;
69
59
  text: string;
60
+ newMessages: ChatGPTMessage[];
70
61
  isDone: boolean;
71
- newMessages: ChatGPT35Message[];
72
62
  apiReseponse: ApiResponse;
73
63
  }>;
74
64
  /**
75
65
  * @zh 開啟持續性對話
76
66
  */
77
- chat(prompt: string | string[], oldMessages?: ChatGPT35Message[]): Promise<{
67
+ keepTalk(prompt: string | string[], oldMessages?: ChatGPTMessage[]): Promise<{
78
68
  result: {
79
69
  id: string;
80
70
  text: string;
71
+ newMessages: ChatGPTMessage[];
81
72
  isDone: boolean;
82
- newMessages: ChatGPT35Message[];
83
73
  apiReseponse: ApiResponse;
84
74
  };
85
75
  nextTalk: (prompt: string | string[]) => Promise<any>;
86
76
  }>;
87
77
  }
88
- export declare type ChatGPT35TalkResponse = PromiseResponseType<ChatGPT35['talk']>;
78
+ export declare type OpenAIChatTalkResponse = PromiseResponseType<OpenAIChat['talk']>;
89
79
  export {};
@@ -1,5 +1,5 @@
1
- import { AxiosInstance } from 'axios';
2
- import { PromiseResponseType } from '../types';
1
+ import { OpenAI } from './index';
2
+ import { PromiseResponseType } from '../../types';
3
3
  declare type Config = {
4
4
  /**
5
5
  * @zh 一次回應數量
@@ -35,35 +35,25 @@ declare type ApiResponse = {
35
35
  total_tokens: number;
36
36
  };
37
37
  };
38
- export declare class ChatGPT3 {
39
- private axios;
40
- private apiKey;
38
+ export declare class OpenAICompletion {
39
+ private openai;
41
40
  private config;
42
- /**
43
- * @zh 如果你有需要特別設定 axios,請使用這方法。
44
- * @en If you need to set axios, please use this method.
45
- */
46
- setAxios(axios: AxiosInstance): void;
47
- /**
48
- * @zh 設定 api key。
49
- * @en Set api key.
50
- */
51
- setConfiguration(apiKey: string): void;
41
+ constructor(openai: OpenAI);
52
42
  /**
53
43
  * @zh 改變對話的一些設定。
54
44
  * @en Change some settings of the chat.
55
45
  */
56
46
  setConfig(options: Partial<Config>): void;
57
47
  /**
58
- * @zh 進行對話。
59
- * @en Talk to the chatbot.
48
+ * @zh 進行補文。
49
+ * @en Do completion.
60
50
  */
61
- talk(prompt: string | string[]): Promise<{
51
+ run(prompt: string | string[]): Promise<{
62
52
  id: string;
63
53
  text: string;
64
54
  isDone: boolean;
65
55
  apiReseponse: ApiResponse;
66
56
  }>;
67
57
  }
68
- export declare type ChatGPT3TalkResponse = PromiseResponseType<ChatGPT3['talk']>;
58
+ export declare type OpenAiOpenAICompletionResponse = PromiseResponseType<OpenAICompletion['run']>;
69
59
  export {};
@@ -1,4 +1,4 @@
1
- import { AxiosInstance } from 'axios';
1
+ import { OpenAI } from './index';
2
2
  declare type ApiResponse = {
3
3
  created: string;
4
4
  data: {
@@ -17,20 +17,10 @@ declare type Config = {
17
17
  */
18
18
  size: `${number}x${number}`;
19
19
  };
20
- export declare class ImagesGenerations {
21
- private axios;
22
- private apiKey;
20
+ export declare class OpenAIImagesGeneration {
21
+ private openai;
23
22
  private config;
24
- /**
25
- * @zh 如果你有需要特別設定 axios,請使用這方法
26
- * @en If you need to set axios, use this method
27
- */
28
- setAxios(axios: AxiosInstance): void;
29
- /**
30
- * @zh 設定 api key
31
- * @en Set api key
32
- */
33
- setConfiguration(apiKey: string): void;
23
+ constructor(openai: OpenAI);
34
24
  /**
35
25
  * @zh 改變對話的一些設定
36
26
  * @en Change some settings of the conversation
@@ -0,0 +1,22 @@
1
+ import { OpenAIChat } from './chat';
2
+ import { OpenAICompletion } from './completion';
3
+ import { OpenAIImagesGeneration } from './images-generation';
4
+ import { AxiosInstance } from 'axios';
5
+ export declare class OpenAI {
6
+ _axios: AxiosInstance;
7
+ _apiKey: string;
8
+ constructor(apiKey?: string);
9
+ /**
10
+ * @zh 如果你有需要特別設定 axios,請使用這方法。
11
+ * @en If you need to set axios, please use this method.
12
+ */
13
+ setAxios(axios: AxiosInstance): void;
14
+ /**
15
+ * @zh 設定 api key。
16
+ * @en Set api key.
17
+ */
18
+ setConfiguration(apiKey: string): void;
19
+ createChat(): OpenAIChat;
20
+ createCompletion(): OpenAICompletion;
21
+ createImagesGeneration(): OpenAIImagesGeneration;
22
+ }
package/README-TW.md DELETED
@@ -1,239 +0,0 @@
1
- <br>
2
- <p align="center"><img style="max-width: 300px" src="./logo.png"></p>
3
- <h1 align="center">CtoD</h1>
4
- <h3 align="center">Chat To Data</h3>
5
-
6
- <p align="center">
7
- <a href="https://www.npmjs.com/package/ctod">
8
- <img src="https://img.shields.io/npm/v/ctod.svg">
9
- </a>
10
- <a href="https://github.com/KHC-ZhiHao/ctod">
11
- <img src="https://img.shields.io/github/stars/KHC-ZhiHao/ctod.svg?style=social">
12
- </a>
13
- <br>
14
- </p>
15
-
16
- <br>
17
-
18
- [English Version](./README.md)
19
-
20
- ## Online Playground
21
-
22
- [Chat Of Requirement(織語)](https://cor.metalsheep.com/) 是為了 CtoD 建構的展示工具,你可以在這個工具中建構你與調適你的模板。
23
-
24
- ## 摘要
25
-
26
- 本工具是利用聊天機器人能夠讀懂自然語言的特性,將我們的需求與資料透過口語化的方式交付給他處理,並要求回應可序列化格式,例如:JSON。
27
-
28
- 在對話過程中,本工具採用 [yup](https://github.com/jquense/yup) 來驗證請求與回復資料是否符合預期,以確保一致性,只要保持這個互動模式,就可以利用在 API 串接或是自動化系統上。
29
-
30
- 我們還附帶了一些基礎的串接機器人方案,目前支援 `ChatGPT3` 與 `ChatGPT3.5`。
31
-
32
- ## 安裝
33
-
34
- npm:
35
-
36
- ```bash
37
- npm install ctod
38
- ```
39
-
40
- yarn:
41
-
42
- ```bash
43
- yarn add ctod
44
- ```
45
-
46
- ## 快速開始
47
-
48
- 這個例子示範如何將藥物索引與客戶需求傳遞給聊天機器人,並返回最適合的結果,開發人員可以利用索引結果去資料庫搜尋最適合的藥物給消費者:
49
-
50
- > 關於型態定義,這裡有個有趣的議題,必須將 input 與 output 優先宣告才能讓型態正常運作。
51
-
52
- ```ts
53
- import { ChatGPT35Broker, templates } from 'ctod'
54
-
55
- const API_KEY = 'openai api key'
56
- const broker = new ChatGPT35Broker({
57
- /** 驗證輸入資料 */
58
- input: yup => {
59
- return {
60
- indexs: yup.array(yup.string()).required(),
61
- question: yup.string().required()
62
- }
63
- },
64
- /** 驗證輸出資料 */
65
- output: yup => {
66
- return {
67
- indexs: yup.array(yup.object({
68
- name: yup.string().required(),
69
- score: yup.number().required()
70
- })).required()
71
- }
72
- },
73
- /** 初始化系統,通常來植入或掛鉤生命週期 */
74
- install: ({ bot }) => {
75
- bot.setConfiguration(API_KEY)
76
- },
77
- /** 組裝與定義我們要向機器人發出的請求 */
78
- question: async({ indexs, question }) => {
79
- return templates.requireJsonResponse([
80
- '我有以下索引',
81
- `${JSON.stringify(indexs)}`,
82
- `請幫我解析"${question}"可能是哪個索引`,
83
- '且相關性由高到低排序並給予分數,分數由 0 ~ 1'
84
- ], {
85
- indexs: {
86
- desc: '由高到低排序的索引',
87
- example: [
88
- {
89
- name: '索引名稱',
90
- score: '評比分數,數字顯示'
91
- }
92
- ]
93
- }
94
- })
95
- }
96
- })
97
-
98
- broker.request({
99
- indexs: ['胃痛', '腰痛', '頭痛', '喉嚨痛', '四肢疼痛'],
100
- question: '喝咖啡,吃甜食,胃食道逆流'
101
- }).then(e => {
102
- console.log('輸出結果:', e.indexs)
103
- /*
104
- [
105
- {
106
- name: '胃痛',
107
- score: 1
108
- },
109
- {
110
- name: '喉嚨痛',
111
- score: 0.7
112
- },
113
- ...
114
- ]
115
- */
116
- })
117
- ```
118
-
119
- ### Examples
120
-
121
- 1. [如何利用 ChatGPT35 持續聊天機器人對話](./examples/chatgpt3.5.ts)
122
-
123
- 2. [如何利用 ChatGPT35Broker 來整合機器人回應](./examples/chatgpt3.5-broker.ts)
124
-
125
- ## Plugin
126
-
127
- 雖然 Broker 本身已經能夠處理大部分的事務,但透過 Plugin 可以協助改善複雜的流程,幫助專案工程化。
128
-
129
- 每次發送請求時,Broker 會觸發一系列的生命週期,你可以從[原始碼](./lib/broker/35.ts)中了解每個生命週期的參數與行為,並對其行為進行加工。
130
-
131
- 現在,假設我們想要設計一個插件,它會在每次對話結束時將訊息備份到伺服器上:
132
-
133
- ```ts
134
- import axios from 'axios'
135
- import { ChatGPT35Broker, Broker35Plugin } from 'ctod'
136
- const backupPlugin = new Broker35Plugin({
137
- name: 'backup-plugin',
138
- // 定義參數為 sendUrl
139
- params: yup => {
140
- return {
141
- sendUrl: yup.string().required()
142
- }
143
- },
144
- // 現階段你可以在執行過程中接收到資訊,資訊結構由這裡定義。
145
- receiveData: yup => {
146
- return {
147
- character: yup.string().required()
148
- }
149
- },
150
- onInstall({ params, attach, receive }) {
151
- const store = new Map()
152
- // 假設我們有更多的自訂義資訊需要被傳遞進來,可以在 talkFirst 階段透過 plugins[key].send({ ... }) 傳遞
153
- // 可以從 Applications 分類中的 請機器人角色扮演 觀看案例
154
- receive(({ id, context }) => {
155
- store.get(id).context = context
156
- })
157
- // 第一次對話的時候初始化資料
158
- attach('talkFirst', async({ id }) => {
159
- store.set(id, {
160
- messages: [],
161
- context: null
162
- })
163
- })
164
- // 每次對話完畢後把對話存入狀態
165
- attach('talkAfter', async({ id, lastUserMessage }) => {
166
- store.get(id).messages.push(lastUserMessage)
167
- })
168
- // 結束對話後備份資料
169
- attach('done', async({ id }) => {
170
- await axios.post(params.sendUrl, store.get(id))
171
- store.delete(id)
172
- })
173
- }
174
- })
175
-
176
- const broker = new ChatGPT35Broker({
177
- // ...
178
- plugins: [
179
- backupPlugin.use({
180
- sendUrl: 'https://api/backup'
181
- })
182
- ],
183
- // 以下方案也可以運行
184
- // plugins: () => [
185
- // backupPlugin.use({
186
- // sendUrl: 'https://api/backup'
187
- // })
188
- // ],
189
- // ...
190
- })
191
- ```
192
-
193
- ### Examples
194
-
195
- 1. 能夠印出執行流程:[Print Log Plugin](./lib/plugins/print-log.ts)
196
- 2. 能夠限制發送流量:[Limiter Plugin](./lib/plugins/limiter.ts)
197
- 3. 能夠在失敗的時候重試:[Retry Plugin](./lib/plugins/retry.ts)
198
-
199
- ### Applications
200
-
201
- 以下是一組應用範例,你可以參考這些範例來設計你的 AI System。
202
-
203
- > 你可以透過 clone 本專案,在根目錄中加入 .key file,並貼上你的 openai dev key 來快速試用這些使用範例。
204
-
205
- [解讀 BBC News](./examples/applications/bbc-news-reader.ts)
206
- [請機器人角色扮演](./examples/applications/cosplay.ts)
207
- [故事與封面生產器]('./examples/applications/story-generations.ts')
208
- [對話生產器]('./examples/applications/talk-generations.ts')
209
-
210
- ## Version History
211
-
212
- ### 0.1.x
213
-
214
- 我們對 plugin 做了比較大的異動,主要是為了能夠實行資料交換。
215
-
216
- #### ChatGPT35 Service
217
-
218
- ##### remove: getJailbrokenMessages
219
-
220
- 方案已過時。
221
-
222
- #### Broker
223
-
224
- ##### add: setPreMessages
225
-
226
- 能夠讓使用者在對話開始前,先輸入一些訊息,並確保首要問題被組合至。
227
-
228
- ##### fix: hook
229
-
230
- 修改了綁定行為,現在是 Broker 的綁定優先,再來才是 plugins。
231
-
232
- ##### change: assembly => question
233
-
234
- 為了讓使用者更容易理解,我們將 assembly 改名為 question。
235
-
236
- ### 0.1.3
237
-
238
- * 移除: max_token
239
- * 新增: model add 16k
package/TODO DELETED
@@ -1,6 +0,0 @@
1
- [] 單元測試
2
- [] 程式碼說明註解
3
- [] 其他單元的說明文件
4
- [] ChatGPT 4 版本
5
- [] ChatGPU 3 範例
6
- [] 可在前端透過介面的範本