1
1
# GPT agent example
2
2
3
- This example uses the [ OpenAI ] ( https://openai.com ) API for GPT-based responses and [ XMTP] ( https://xmtp.org ) for secure messaging. You can test your agent on [ xmtp.chat] ( https://xmtp.chat ) or any other XMTP-compatible client.
3
+ This example uses the [ Grok ] ( https://x.ai/api ) API for responses and [ XMTP] ( https://xmtp.org ) for secure messaging. You can test your agent on [ xmtp.chat] ( https://xmtp.chat ) or any other XMTP-compatible client.
4
4
5
5
## Environment variables
6
6
@@ -25,33 +25,41 @@ yarn gen:keys
25
25
26
26
``` tsx
27
27
import { Client , type XmtpEnv } from " @xmtp/node-sdk" ;
28
- import OpenAI from " openai" ;
29
28
import { createSigner , getEncryptionKeyFromHex } from " @/helpers" ;
30
29
31
- const { WALLET_KEY, ENCRYPTION_KEY, OPENAI_API_KEY, GROK_API_KEY } =
32
- process .env ;
30
+ /* Get the wallet key associated to the public key of
31
+ * the agent and the encryption key for the local db
32
+ * that stores your agent's messages */
33
+ const { WALLET_KEY, ENCRYPTION_KEY, GROK_API_KEY } = process .env ;
33
34
35
+ /* Check if the environment variables are set */
34
36
if (! WALLET_KEY ) {
35
37
throw new Error (" WALLET_KEY must be set" );
36
38
}
37
39
40
+ /* Check if the encryption key is set */
38
41
if (! ENCRYPTION_KEY ) {
39
42
throw new Error (" ENCRYPTION_KEY must be set" );
40
43
}
41
44
42
- if (! OPENAI_API_KEY ) {
43
- throw new Error (" OPENAI_API_KEY must be set" );
45
+ /* Check if the Grok API key is set */
46
+ if (! GROK_API_KEY ) {
47
+ throw new Error (" GROK_API_KEY must be set" );
44
48
}
45
49
50
+ /* Create the signer using viem and parse the encryption key for the local db */
46
51
const signer = createSigner (WALLET_KEY );
47
52
const encryptionKey = getEncryptionKeyFromHex (ENCRYPTION_KEY );
48
- const openai = new OpenAI ({ apiKey: OPENAI_API_KEY });
49
53
50
54
/* Set the environment to dev or production */
51
55
const env: XmtpEnv = " dev" ;
52
56
57
+ /**
58
+ * Main function to run the agent
59
+ */
53
60
async function main() {
54
61
console .log (` Creating client on the '${env }' network... ` );
62
+ /* Initialize the xmtp client */
55
63
const client = await Client .create (signer , encryptionKey , {
56
64
env ,
57
65
});
@@ -61,10 +69,124 @@ async function main() {
61
69
await client .conversations .sync ();
62
70
63
71
console .log (
64
- ` Agent initialized on ${client .accountAddress }\n Send a message on http://xmtp.chat/dm/${client .accountAddress } ` ,
72
+ ` Agent initialized on ${client .accountAddress }\n Send a message on http://xmtp.chat/dm/${client .accountAddress }?env=${ env } ` ,
65
73
);
74
+ console .log (" Waiting for messages..." );
75
+ /* Stream all messages from the network */
76
+ const stream = client .conversations .streamAllMessages ();
77
+
78
+ for await (const message of await stream ) {
79
+ /* Ignore messages from the same agent or non-text messages */
80
+ if (
81
+ message ?.senderInboxId .toLowerCase () === client .inboxId .toLowerCase () ||
82
+ message ?.contentType ?.typeId !== " text"
83
+ ) {
84
+ continue ;
85
+ }
86
+
87
+ console .log (
88
+ ` Received message: ${message .content as string } by ${message .senderInboxId } ` ,
89
+ );
90
+
91
+ /* Get the conversation from the local db */
92
+ const conversation = client .conversations .getConversationById (
93
+ message .conversationId ,
94
+ );
95
+
96
+ /* If the conversation is not found, skip the message */
97
+ if (! conversation ) {
98
+ console .log (" Unable to find conversation, skipping" );
99
+ continue ;
100
+ }
101
+
102
+ try {
103
+ /* Get the AI response from Grok */
104
+ const response = await fetch (" https://api.x.ai/v1/chat/completions" , {
105
+ method: " POST" ,
106
+ headers: {
107
+ " Content-Type" : " application/json" ,
108
+ Authorization: ` Bearer ${GROK_API_KEY } ` , // Use the same API key variable
109
+ },
110
+ body: JSON .stringify ({
111
+ messages: [
112
+ { role: " system" , content: " You are a test assistant." },
113
+ { role: " user" , content: message .content as string },
114
+ ],
115
+ model: " grok-2-latest" ,
116
+ stream: false ,
117
+ temperature: 0 ,
118
+ }),
119
+ }).then (
120
+ (res ) =>
121
+ res .json () as Promise <{
122
+ choices: { message: { content: string } }[];
123
+ }>,
124
+ );
125
+ const aiResponse = response .choices [0 ]?.message ?.content || " " ;
126
+ console .log (` Sending AI response: ${aiResponse } ` );
127
+ /* Send the AI response to the conversation */
128
+ await conversation .send (aiResponse );
129
+ } catch (error ) {
130
+ console .error (" Error getting AI response:" , error );
131
+ await conversation .send (
132
+ " Sorry, I encountered an error processing your message." ,
133
+ );
134
+ }
135
+
136
+ console .log (" Waiting for messages..." );
137
+ }
138
+ }
139
+
140
+ main ().catch (console .error );
141
+ import { Client , type XmtpEnv } from " @xmtp/node-sdk" ;
142
+ import { createSigner , getEncryptionKeyFromHex } from " @/helpers" ;
143
+
144
+ /* Get the wallet key associated to the public key of
145
+ * the agent and the encryption key for the local db
146
+ * that stores your agent's messages */
147
+ const { WALLET_KEY, ENCRYPTION_KEY, GROK_API_KEY } = process .env ;
148
+
149
+ /* Check if the environment variables are set */
150
+ if (! WALLET_KEY ) {
151
+ throw new Error (" WALLET_KEY must be set" );
152
+ }
153
+
154
+ /* Check if the encryption key is set */
155
+ if (! ENCRYPTION_KEY ) {
156
+ throw new Error (" ENCRYPTION_KEY must be set" );
157
+ }
158
+
159
+ /* Check if the Grok API key is set */
160
+ if (! GROK_API_KEY ) {
161
+ throw new Error (" GROK_API_KEY must be set" );
162
+ }
163
+
164
+ /* Create the signer using viem and parse the encryption key for the local db */
165
+ const signer = createSigner (WALLET_KEY );
166
+ const encryptionKey = getEncryptionKeyFromHex (ENCRYPTION_KEY );
167
+
168
+ /* Set the environment to dev or production */
169
+ const env: XmtpEnv = " dev" ;
66
170
171
+ /**
172
+ * Main function to run the agent
173
+ */
174
+ async function main() {
175
+ console .log (` Creating client on the '${env }' network... ` );
176
+ /* Initialize the xmtp client */
177
+ const client = await Client .create (signer , encryptionKey , {
178
+ env ,
179
+ });
180
+
181
+ console .log (" Syncing conversations..." );
182
+ /* Sync the conversations from the network to update the local db */
183
+ await client .conversations .sync ();
184
+
185
+ console .log (
186
+ ` Agent initialized on ${client .accountAddress }\n Send a message on http://xmtp.chat/dm/${client .accountAddress }?env=${env } ` ,
187
+ );
67
188
console .log (" Waiting for messages..." );
189
+ /* Stream all messages from the network */
68
190
const stream = client .conversations .streamAllMessages ();
69
191
70
192
for await (const message of await stream ) {
@@ -80,22 +202,24 @@ async function main() {
80
202
` Received message: ${message .content as string } by ${message .senderInboxId } ` ,
81
203
);
82
204
205
+ /* Get the conversation from the local db */
83
206
const conversation = client .conversations .getConversationById (
84
207
message .conversationId ,
85
208
);
86
209
210
+ /* If the conversation is not found, skip the message */
87
211
if (! conversation ) {
88
212
console .log (" Unable to find conversation, skipping" );
89
213
continue ;
90
214
}
91
215
92
216
try {
93
- // Use Grok API to get AI response
217
+ /* Get the AI response from Grok */
94
218
const response = await fetch (" https://api.x.ai/v1/chat/completions" , {
95
219
method: " POST" ,
96
220
headers: {
97
221
" Content-Type" : " application/json" ,
98
- Authorization: ` Bearer ${GROK_API_KEY } ` ,
222
+ Authorization: ` Bearer ${GROK_API_KEY } ` , // Use the same API key variable
99
223
},
100
224
body: JSON .stringify ({
101
225
messages: [
@@ -114,6 +238,7 @@ async function main() {
114
238
);
115
239
const aiResponse = response .choices [0 ]?.message ?.content || " " ;
116
240
console .log (` Sending AI response: ${aiResponse } ` );
241
+ /* Send the AI response to the conversation */
117
242
await conversation .send (aiResponse );
118
243
} catch (error ) {
119
244
console .error (" Error getting AI response:" , error );
0 commit comments