Skip to content

Commit

Permalink
first hack at different threads per wallet connection
Browse files Browse the repository at this point in the history
  • Loading branch information
cryptoKevinL committed May 27, 2024
1 parent 9b3dde5 commit ed02c7c
Show file tree
Hide file tree
Showing 6 changed files with 846 additions and 13 deletions.
81 changes: 81 additions & 0 deletions app/api/connectWallet/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
// pages/api/connectWallet.ts

import { NextRequest, NextResponse } from 'next/server';
import { getWalletAddress, setWalletAddress } from '../../../lib/walletstate'; // Correct the path as needed

interface SuccessResponse {
success: boolean;
message?: string;
walletAddress?: string;
}

interface ErrorResponse {
message: string;
}

// POST handler to set the wallet address
export async function POST(req: NextRequest) {
if (req.method !== 'POST') {
return new NextResponse(JSON.stringify({ message: 'Method Not Allowed' }), {
status: 405,
headers: {'Content-Type': 'application/json'}
});
}

try {
const body = await req.json();
const { walletAddress } = body;
if (typeof walletAddress === 'string') {
console.log('Wallet address updated', walletAddress)
let res = new NextResponse(JSON.stringify({ success: true, message: 'Wallet address updated', walletAddress }), {
status: 200,
headers: {'Content-Type': 'application/json'}
});
setWalletAddress(res, walletAddress);
return res;
} else {
return new NextResponse(JSON.stringify({ message: 'Invalid wallet address provided' }), {
status: 400,
headers: {'Content-Type': 'application/json'}
});
}
} catch (error) {
return new NextResponse(JSON.stringify({ message: 'Server error processing your request' }), {
status: 500,
headers: {'Content-Type': 'application/json'}
});
}
}

// GET handler to retrieve the wallet address
export async function GET(req: NextRequest) {
if (req.method !== 'GET') {
return new NextResponse(JSON.stringify({ message: 'Method Not Allowed' }), {
status: 405,
headers: {'Content-Type': 'application/json'}
});
}

console.log('GET wallet address called')

try {
const address = getWalletAddress(req);
if (address) {
console.log('Wallet address found', address)
return new NextResponse(JSON.stringify({ success: true, walletAddress: address }), {
status: 200,
headers: {'Content-Type': 'application/json'}
});
} else {
return new NextResponse(JSON.stringify({ message: 'ConnectWallet: No wallet connected' }), {
status: 404,
headers: {'Content-Type': 'application/json'}
});
}
} catch (error) {
return new NextResponse(JSON.stringify({ message: 'Server error processing your request' }), {
status: 500,
headers: {'Content-Type': 'application/json'}
});
}
}
32 changes: 26 additions & 6 deletions app/api/openai/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import axios from "axios";
import { NextRequest, NextResponse } from 'next/server';
import { Assistant } from "openai/resources/beta/assistants.mjs";
import { ChatCompletionTool } from "openai/resources/index.mjs";
import { getWalletAddress } from '../../../lib/walletstate';

const openai = new OpenAI({
apiKey: process.env.OPENAI_API_KEY,
Expand Down Expand Up @@ -266,6 +267,7 @@ const functions: ChatCompletionTool[] = [

let threadId: string; // Store the thread ID
const conversations: any = {}; // In-memory store for conversations
const threadIdByWallet: any = {}; // In-memory store for conversations

let assistant: Assistant;

Expand All @@ -289,14 +291,22 @@ const initializeAssistant = async () => {
};

async function askAIForExplanation(message: string): Promise<string> {
// Simulate sending a query to an AI. Replace with actual OpenAI API call.
// For example, using OpenAI's `openai.ChatCompletion.create()` method:
try {
const completion = await openai.chat.completions.create({
model: "gpt-4",
messages: [{role: "system", content: "Explain the following blockchain result:"}, {role: "user", content: message}]
messages: [
{ role: "system", content: "Explain the following blockchain result:" },
{ role: "user", content: message }
]
});
return completion.choices[0].message.content;

// Check if the content is not null before returning it
if (completion.choices.length > 0 && completion.choices[0].message.content) {
return completion.choices[0].message.content;
} else {
// Handle the case where content is null or choices are empty
return "No explanation available.";
}
} catch (error) {
console.error("Failed to get explanation from AI:", error);
return "Failed to generate explanation.";
Expand Down Expand Up @@ -430,11 +440,21 @@ const getQueryResults = async (executionId: string) => {
export const POST = async (req: NextRequest, res: NextResponse) => {
await initializeAssistant();
const { message } = await req.json();

if (!threadId) {
const walletAddress = getWalletAddress(req); // Retrieve the wallet address from global state
if(!walletAddress) {
//default thread ID for those who don't want to connect wallet
//this should be removed once we get a landing page (may cause confused if history gets stomped on by others)
const thread = await openai.beta.threads.create();
threadId = thread.id;
conversations[threadId] = []; // Initialize as an array if a new thread is created
} else {
threadId = threadIdByWallet[walletAddress]
if (!threadId) {
const thread = await openai.beta.threads.create();
threadId = thread.id;
conversations[threadId] = []; // Initialize as an array if a new thread is created
threadIdByWallet[walletAddress] = thread.id
}
}

try {
Expand Down
Loading

0 comments on commit ed02c7c

Please sign in to comment.