forked from transitive-bullshit/agentic
-
Notifications
You must be signed in to change notification settings - Fork 0
/
demo-persistence.ts
71 lines (59 loc) · 1.52 KB
/
demo-persistence.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
import KeyvRedis from '@keyv/redis'
import dotenv from 'dotenv-safe'
import Keyv from 'keyv'
import { oraPromise } from 'ora'
import { ChatGPTAPI, type ChatMessage } from '../src'
dotenv.config()
/**
* Demo CLI for testing message persistence with redis.
*
* ```
* npx tsx demos/demo-persistence.ts
* ```
*/
async function main() {
const redisUrl = process.env.REDIS_URL || 'redis://localhost:6379'
const store = new KeyvRedis(redisUrl)
const messageStore = new Keyv({ store, namespace: 'chatgpt-demo' })
let res: ChatMessage
{
// create an initial conversation in one client
const api = new ChatGPTAPI({
apiKey: process.env.OPENAI_API_KEY,
messageStore
})
const prompt = 'What are the top 5 anime of all time?'
res = await oraPromise(api.sendMessage(prompt), {
text: prompt
})
console.log('\n' + res.text + '\n')
}
{
// follow up with a second client using the same underlying redis store
const api = new ChatGPTAPI({
apiKey: process.env.OPENAI_API_KEY,
messageStore
})
const prompt = 'Can you give 5 more?'
res = await oraPromise(
api.sendMessage(prompt, {
parentMessageId: res.id
}),
{
text: prompt
}
)
console.log('\n' + res.text + '\n')
}
// wait for redis to finish and then disconnect
await new Promise<void>((resolve) => {
setTimeout(() => {
messageStore.disconnect()
resolve()
}, 1000)
})
}
main().catch((err) => {
console.error(err)
process.exit(1)
})