Skip to content

Commit 63e9bc8

Browse files
committed
grok details
1 parent 1a95a86 commit 63e9bc8

File tree

1 file changed

+135
-10
lines changed

1 file changed

+135
-10
lines changed

integrations/grok/README.md

+135-10
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
# GPT agent example
22

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.
44

55
## Environment variables
66

@@ -25,33 +25,41 @@ yarn gen:keys
2525

2626
```tsx
2727
import { Client, type XmtpEnv } from "@xmtp/node-sdk";
28-
import OpenAI from "openai";
2928
import { createSigner, getEncryptionKeyFromHex } from "@/helpers";
3029

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;
3334

35+
/* Check if the environment variables are set */
3436
if (!WALLET_KEY) {
3537
throw new Error("WALLET_KEY must be set");
3638
}
3739

40+
/* Check if the encryption key is set */
3841
if (!ENCRYPTION_KEY) {
3942
throw new Error("ENCRYPTION_KEY must be set");
4043
}
4144

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");
4448
}
4549

50+
/* Create the signer using viem and parse the encryption key for the local db */
4651
const signer = createSigner(WALLET_KEY);
4752
const encryptionKey = getEncryptionKeyFromHex(ENCRYPTION_KEY);
48-
const openai = new OpenAI({ apiKey: OPENAI_API_KEY });
4953

5054
/* Set the environment to dev or production */
5155
const env: XmtpEnv = "dev";
5256

57+
/**
58+
* Main function to run the agent
59+
*/
5360
async function main() {
5461
console.log(`Creating client on the '${env}' network...`);
62+
/* Initialize the xmtp client */
5563
const client = await Client.create(signer, encryptionKey, {
5664
env,
5765
});
@@ -61,10 +69,124 @@ async function main() {
6169
await client.conversations.sync();
6270

6371
console.log(
64-
`Agent initialized on ${client.accountAddress}\nSend a message on http://xmtp.chat/dm/${client.accountAddress}`,
72+
`Agent initialized on ${client.accountAddress}\nSend a message on http://xmtp.chat/dm/${client.accountAddress}?env=${env}`,
6573
);
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";
66170

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}\nSend a message on http://xmtp.chat/dm/${client.accountAddress}?env=${env}`,
187+
);
67188
console.log("Waiting for messages...");
189+
/* Stream all messages from the network */
68190
const stream = client.conversations.streamAllMessages();
69191

70192
for await (const message of await stream) {
@@ -80,22 +202,24 @@ async function main() {
80202
`Received message: ${message.content as string} by ${message.senderInboxId}`,
81203
);
82204

205+
/* Get the conversation from the local db */
83206
const conversation = client.conversations.getConversationById(
84207
message.conversationId,
85208
);
86209

210+
/* If the conversation is not found, skip the message */
87211
if (!conversation) {
88212
console.log("Unable to find conversation, skipping");
89213
continue;
90214
}
91215

92216
try {
93-
// Use Grok API to get AI response
217+
/* Get the AI response from Grok */
94218
const response = await fetch("https://api.x.ai/v1/chat/completions", {
95219
method: "POST",
96220
headers: {
97221
"Content-Type": "application/json",
98-
Authorization: `Bearer ${GROK_API_KEY}`,
222+
Authorization: `Bearer ${GROK_API_KEY}`, // Use the same API key variable
99223
},
100224
body: JSON.stringify({
101225
messages: [
@@ -114,6 +238,7 @@ async function main() {
114238
);
115239
const aiResponse = response.choices[0]?.message?.content || "";
116240
console.log(`Sending AI response: ${aiResponse}`);
241+
/* Send the AI response to the conversation */
117242
await conversation.send(aiResponse);
118243
} catch (error) {
119244
console.error("Error getting AI response:", error);

0 commit comments

Comments
 (0)