-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathrpc.ts
More file actions
207 lines (177 loc) · 4.69 KB
/
Copy pathrpc.ts
File metadata and controls
207 lines (177 loc) · 4.69 KB
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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
// Run `pnpm build:rpc` before running this example
import assert from 'node:assert'
import {
type FileHandle,
mkdir,
open,
readFile,
writeFile,
} from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { inspect } from 'node:util'
import { WASI } from 'node:wasi'
const PROMPTL_WASM_PATH = './dist-rpc/promptl.wasm'
// --- Example 1: Basic chain without references ---
const prompt = `
<step>
<system>
You are a helpful assistant.
</system>
<user>
Say hello.
</user>
</step>
<step>
<user>
Now say goodbye.
</user>
</step>
`
let chain, conversation
chain = await createChain(prompt);
({ chain, ...conversation } = await stepChain(chain));
({ chain, ...conversation } = await stepChain(chain, 'Hello!'));
({ chain, ...conversation } = await stepChain(chain, 'Goodbye!'));
assert(chain.completed)
assert(conversation.completed)
console.log('--- Basic chain ---')
console.log(inspect(conversation.messages, { depth: null }))
// --- Example 2: Chain with prompt references ---
const mainPrompt = `
<step>
<prompt path="instructions" />
<user>
Tell me about {{ topic }}.
</user>
</step>
`
const references = {
instructions: `
<system>
You are an expert assistant. Always be concise.
</system>
`,
}
let refChain, refConversation
refChain = await createChain(mainPrompt, {
parameters: { topic: 'TypeScript' },
references: references,
});
({ chain: refChain, ...refConversation } = await stepChain(refChain));
({ chain: refChain, ...refConversation } = await stepChain(refChain, 'It is good!'));
assert(refChain.completed)
assert(refConversation.completed)
console.log('\n--- Chain with references ---')
console.log(inspect(refConversation.messages, { depth: null }))
// Utility functions
async function createChain(
prompt: string,
opts?: {
parameters?: Record<string, unknown>
references?: Record<string, string>
},
): Promise<any> {
return await execute([
{
procedure: 'createChain',
parameters: {
prompt,
...opts,
},
},
]).then((result) => {
if (result[0]!.error) {
console.log('Error dump: ', inspect(result[0]!.error, { depth: null }))
throw new Error(result[0]!.error.message)
}
return result[0]!.value
})
}
async function stepChain(chain: any, response?: any): Promise<any> {
return await execute([
{
procedure: 'stepChain',
parameters: {
chain: chain,
response: response,
},
},
]).then((result) => {
if (result[0]!.error) {
console.log('Error dump: ', inspect(result[0]!.error, { depth: null }))
throw new Error(result[0]!.error.message)
}
return result[0]!.value
})
}
async function execute(data: any): Promise<any> {
const dir = join(tmpdir(), 'promptl')
const stdin_path = join(dir, 'stdin')
const stdout_path = join(dir, 'stdout')
const stderr_path = join(dir, 'stderr')
await mkdir(dir, { recursive: true })
await writeFile(stdin_path, '')
await writeFile(stdout_path, '')
await writeFile(stderr_path, '')
let stdin: FileHandle | undefined
let stdout: FileHandle | undefined
let stderr: FileHandle | undefined
let wasmStdin: FileHandle | undefined
let wasmStdout: FileHandle | undefined
let wasmStderr: FileHandle | undefined
try {
stdin = await open(stdin_path, 'w')
stdout = await open(stdout_path, 'r')
stderr = await open(stderr_path, 'r')
wasmStdin = await open(stdin_path, 'r')
wasmStdout = await open(stdout_path, 'w')
wasmStderr = await open(stderr_path, 'w')
const wasi = new WASI({
version: 'preview1',
args: [],
env: {},
stdin: wasmStdin.fd,
stdout: wasmStdout.fd,
stderr: wasmStderr.fd,
returnOnExit: true,
})
const bytes = await readFile(PROMPTL_WASM_PATH)
WebAssembly.validate(bytes)
const module = await WebAssembly.compile(bytes)
const instance = await WebAssembly.instantiate(
module,
wasi.getImportObject(),
)
await send(stdin, data)
wasi.start(instance)
const [out, err] = await Promise.all([receive(stdout), receive(stderr)])
if (err) throw new Error(err)
return out
} finally {
await Promise.all([
stdin?.close(),
stdout?.close(),
stderr?.close(),
wasmStdin?.close(),
wasmStdout?.close(),
wasmStderr?.close(),
])
}
}
async function send(file: FileHandle, data: any) {
await writeFile(file, JSON.stringify(data) + '\n', {
encoding: 'utf8',
flush: true,
})
}
async function receive(file: FileHandle): Promise<any> {
const data = await readFile(file, {
encoding: 'utf8',
}).then((data) => data.trim())
try {
return JSON.parse(data)
} catch {
return data
}
}