-
Notifications
You must be signed in to change notification settings - Fork 30
/
simpleLlmChat.ts
67 lines (56 loc) · 1.85 KB
/
simpleLlmChat.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
import {Contract, ethers, Wallet} from "ethers";
import ABI from "./abis/OpenAiSimpleLLM.json";
import * as readline from 'readline';
require("dotenv").config()
async function main() {
const rpcUrl = process.env.RPC_URL
if (!rpcUrl) throw Error("Missing RPC_URL in .env")
const privateKey = process.env.PRIVATE_KEY
if (!privateKey) throw Error("Missing PRIVATE_KEY in .env")
const contractAddress = process.env.SIMPLE_LLM_CONTRACT_ADDRESS
if (!contractAddress) throw Error("Missing SIMPLE_LLM_CONTRACT_ADDRESS in .env")
const provider = new ethers.JsonRpcProvider(rpcUrl)
const wallet = new Wallet(
privateKey, provider
)
const contract = new Contract(contractAddress, ABI, wallet)
// The message you want to start the chat with
const message = await getUserInput()
// Call the sendMessage function
const transactionResponse = await contract.sendMessage(message)
const receipt = await transactionResponse.wait()
console.log(`Message sent, tx hash: ${receipt.hash}`)
console.log(`Chat started with message: "${message}"`)
// Read the LLM response on-chain
while (true) {
const response = await contract.response();
if (response) {
console.log("Response from contract:", response);
break;
}
await new Promise(resolve => setTimeout(resolve, 2000))
}
}
async function getUserInput(): Promise<string | undefined> {
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
})
const question = (query: string): Promise<string> => {
return new Promise((resolve) => {
rl.question(query, (answer) => {
resolve(answer)
})
})
}
try {
const input = await question("Message ChatGPT: ")
rl.close()
return input
} catch (err) {
console.error('Error getting user input:', err)
rl.close()
}
}
main()
.then(() => console.log("Done"))