Skip to content

Commit

Permalink
Merge pull request #18 from saimeunt/feat/chat-history
Browse files Browse the repository at this point in the history
Transaction & Chat history display
  • Loading branch information
mo-jaber authored Dec 23, 2024
2 parents 0cf1eff + 032d9bc commit 9829683
Show file tree
Hide file tree
Showing 12 changed files with 1,512 additions and 91 deletions.
12 changes: 6 additions & 6 deletions app/actions.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -61,15 +61,15 @@ async function submit(
const content = skip
? userInput
: formData
? JSON.stringify(Object.fromEntries(formData))
: null;
? JSON.stringify(Object.fromEntries(formData))
: null;
const type = skip
? undefined
: formData?.has('input')
? 'input'
: formData?.has('related_query')
? 'input_related'
: 'inquiry';
? 'input'
: formData?.has('related_query')
? 'input_related'
: 'inquiry';

// Get the model from the form data (e.g., openai:gpt-4o-mini)
const model = (formData?.get('model') as string) || 'openai:gpt-4o-mini';
Expand Down
2 changes: 1 addition & 1 deletion app/layout.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ const description =
'The BSV AI Agent abstracts the complexity of blockchain transactions and empowers users to perform a wide array of on-chain activities using simple, intuitive prompts.';

export const metadata: Metadata = {
metadataBase: new URL('bsv-ai.vercel.app'),
metadataBase: new URL('https://bsv-ai.vercel.app/'),
title,
description,
openGraph: {
Expand Down
6 changes: 5 additions & 1 deletion components/empty-screen.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,10 @@ import { ArrowRight } from 'lucide-react';

const exampleMessages = [
{
heading: 'Can you swap 10 usdc for eth on Ethereum?',
message: 'Can you swap 10 usdc for eth on Ethereum?',
},
/* {
heading: 'What is OpenAI o1?',
message: 'What is OpenAI o1?',
},
Expand All @@ -17,7 +21,7 @@ const exampleMessages = [
{
heading: 'Summary: https://arxiv.org/pdf/2407.16833',
message: 'Summary: https://arxiv.org/pdf/2407.16833',
},
}, */
];
export function EmptyScreen({
submitMessage,
Expand Down
10 changes: 5 additions & 5 deletions lib/actions/workflow.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ export async function workflow(

let action = { object: { next: 'proceed' } };
// If the user does not skip the task, run the task manager
if (!skip) action = (await taskManager(messages, model)) ?? action;
// if (!skip) action = (await taskManager(messages, model)) ?? action;

if (action.object.next === 'inquire') {
// Generate inquiry
Expand Down Expand Up @@ -98,11 +98,11 @@ export async function workflow(
];

// Generate related queries
const relatedQueries = await querySuggestor(
/* const relatedQueries = await querySuggestor(
uiStream,
messagesWithAnswer,
model
);
); */
// Add follow-up panel
uiStream.append(
<Section title="Follow-up">
Expand All @@ -117,12 +117,12 @@ export async function workflow(
...aiState.get(),
messages: [
...aiState.get().messages,
{
/* {
id,
role: 'assistant',
content: JSON.stringify(relatedQueries),
type: 'related',
},
}, */
{
id,
role: 'assistant',
Expand Down
22 changes: 21 additions & 1 deletion lib/agents/researcher.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,24 @@ import { CoreMessage, generateText, streamText } from 'ai';
import { getTools } from './tools';
import { getModel } from '../utils/registry';
import { AnswerSection } from '@/components/answer-section';
import { brianTransact } from '@/lib/brian';

const SYSTEM_PROMPT = `As a professional search expert, you possess the ability to search for any information on the web.
For each user query, utilize the search results to their fullest potential to provide additional information and assistance in your response.
If there are any images relevant to your answer, be sure to include them as well.
Aim to directly address the user's question, augmenting your response with insights gleaned from the search results.`;

const getPrompt = (messages: CoreMessage[]) => {
const lastUserMessage = messages.findLast(({ role }) => role === 'user');
if (!lastUserMessage) {
return '';
}
const { input } = JSON.parse(lastUserMessage.content as string) as {
input: string;
};
return input;
};

export async function researcher(
uiStream: ReturnType<typeof createStreamableUI>,
messages: CoreMessage[],
Expand All @@ -17,7 +29,7 @@ export async function researcher(
try {
let fullResponse = '';
const streamableText = createStreamableValue<string>();
let toolResults: any[] = [];
/* let toolResults: any[] = [];
const currentDate = new Date().toLocaleString();
const result = await streamText({
Expand Down Expand Up @@ -50,6 +62,14 @@ export async function researcher(
streamableText.done(fullResponse);
return { text: fullResponse, toolResults }; */
// const result = await askBrian('What is the capital of France?');
const prompt = getPrompt(messages);
const { text, toolResults } = await brianTransact(prompt);
fullResponse += text;
streamableText.done(fullResponse);
uiStream.append(<AnswerSection result={streamableText.value} />);

return { text: fullResponse, toolResults };
} catch (error) {
console.error('Error in researcher:', error);
Expand Down
52 changes: 52 additions & 0 deletions lib/brian.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
import {
BrianSDK,
TransactionResult as BrianTransactionResult,
} from '@brian-ai/sdk';
import { generateId } from 'ai';

type TransactionResult = BrianTransactionResult & {
extractedParams: Record<string, string>;
conversationHistory: {
sender: 'user' | 'brian';
content: string;
}[];
};

const brian = new BrianSDK({ apiKey: process.env.BRIAN_API_KEY });

export const brianTransact = async (prompt: string) => {
const requestRaw = await brian.transact({
prompt,
address: 'vitalik.eth',
});
const request = requestRaw as TransactionResult[];
const firstTransactionResult = request[0];
if (!firstTransactionResult) {
return { text: 'ERROR', toolResults: [] };
}
const brianAnswer = firstTransactionResult.conversationHistory.find(
({ sender }) => sender === 'brian'
);
if (!brianAnswer) {
return { text: 'ERROR', toolResults: [] };
}
return {
text: brianAnswer.content,
toolResults: [
{
id: generateId(),
role: 'tool',
content: JSON.stringify(firstTransactionResult.data),
name: 'transaction',
type: 'tool',
},
{
id: generateId(),
role: 'tool',
content: JSON.stringify(firstTransactionResult.extractedParams),
name: 'transaction_extracted_params',
type: 'tool',
},
],
};
};
5 changes: 3 additions & 2 deletions lib/types/models.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,8 @@ export interface Model {
}

export const models: Model[] = [
{
{ id: 'brian', name: 'Brian', provider: 'Brian', providerId: 'brian' },
/* {
id: 'gpt-4o',
name: 'GPT-4o',
provider: 'OpenAI',
Expand Down Expand Up @@ -59,5 +60,5 @@ export const models: Model[] = [
name: process.env.NEXT_PUBLIC_OPENAI_COMPATIBLE_MODEL || 'Undefined',
provider: 'OpenAI Compatible',
providerId: 'openai-compatible',
},
}, */
];
2 changes: 2 additions & 0 deletions lib/utils/registry.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,8 @@ export function getModel(model: string) {

export function isProviderEnabled(providerId: string): boolean {
switch (providerId) {
case 'brian':
return !!process.env.BRIAN_API_KEY;
case 'openai':
return !!process.env.OPENAI_API_KEY;
case 'anthropic':
Expand Down
16 changes: 11 additions & 5 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -19,11 +19,17 @@
"prisma:migrate:reset": "dotenvx run -f .env.local -- prisma migrate reset",
"prisma:studio": "dotenvx run -f .env.local -- prisma studio"
},
"prettier": {
"singleQuote": true,
"trailingCommas": "es5",
"semi": true
},
"dependencies": {
"@ai-sdk/anthropic": "^1.0.5",
"@ai-sdk/azure": "^1.0.12",
"@ai-sdk/google": "^1.0.11",
"@ai-sdk/openai": "^1.0.10",
"@ai-sdk/anthropic": "^1.0.6",
"@ai-sdk/azure": "^1.0.13",
"@ai-sdk/google": "^1.0.12",
"@ai-sdk/openai": "^1.0.11",
"@brian-ai/sdk": "^0.3.6",
"@bsv/sdk": "^1.2.19",
"@clerk/nextjs": "^6.9.6",
"@prisma/client": "^6.1.0",
Expand All @@ -42,7 +48,7 @@
"@radix-ui/react-tooltip": "^1.1.6",
"@tailwindcss/typography": "^0.5.15",
"@upstash/redis": "^1.34.3",
"ai": "^4.0.21",
"ai": "^4.0.22",
"bip39": "^3.1.0",
"class-variance-authority": "^0.7.1",
"clsx": "^2.1.1",
Expand Down
Loading

0 comments on commit 9829683

Please sign in to comment.