File size: 5,239 Bytes
c2df9c2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f4e05b5
 
c2df9c2
 
 
 
 
f4e05b5
 
c2df9c2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
aab77fe
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c2df9c2
aab77fe
c2df9c2
aab77fe
 
 
 
 
c2df9c2
 
 
 
 
 
 
 
 
db0f0fe
c2df9c2
 
 
cb5d7d2
c2df9c2
 
 
 
 
 
 
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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
"use client";

import styles from './page.module.css';
import { useState } from 'react';
import { useChat } from 'ai/react';
import { FunctionCallHandler, Message, nanoid } from 'ai';
import ReactMarkdown from "react-markdown";
import { Bot, User } from "lucide-react";
import { toast } from 'sonner';
import { FunctionIcon } from './icons';

const Page: React.FC = () => {
  const functionCallHandler: FunctionCallHandler = async (
    chatMessages,
    functionCall,
  ) => {
    let result;
    const { name, arguments: args } = functionCall;
    const response = await fetch("/api/functions", {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify({
        prompt: input,
        name: name
      })
    } as any);

    if (!response.ok) {
      const errorText = await response.text();
      toast.error(`Something went wrong: ${errorText}`);
      return;
    }    

    result = await response.text();

    return {
      messages: [
        ...chatMessages,
        {
          id: nanoid(),
          name: functionCall.name,
          role: "function" as const,
          content: result,
        },
      ],
    };
  };
  const { messages, input, setInput, handleSubmit, isLoading } = useChat({
    experimental_onFunctionCall: functionCallHandler,
    onResponse: (response: { status: number; }) => {
      if (response.status === 429) {
        toast.error("You have reached your request limit for the day.");
        return;
      } else {
        console.log("chat initialized");
      }
    },
    onError: (error: any) => {
      console.log(error);
    },
  });
  const [isExpanded, setIsExpanded] = useState(false);
  const toggleExpand = () => {
    setIsExpanded(!isExpanded);
  };

  const roleUIConfig: {
    [key: string]: {
      avatar: JSX.Element;
      bgColor: string;
      avatarColor: string;
      // eslint-disable-next-line no-unused-vars
      dialogComponent: (message: Message) => JSX.Element;
    };
  } = {
    user: {
      avatar: <User width={20} />,
      bgColor: "bg-white",
      avatarColor: "bg-black",
      dialogComponent: (message: Message) => (
        <ReactMarkdown
          className=""
          components={{
            a: (props) => (
              <a {...props} target="_blank" rel="noopener noreferrer" />
            ),
          }}
        >
          {message.content}
        </ReactMarkdown>
      ),
    },
    assistant: {
      avatar: <Bot width={20} />,
      bgColor: "bg-gray-100",
      avatarColor: "bg-green-500",
      dialogComponent: (message: Message) => (
        <ReactMarkdown
          className=""
          components={{
            a: (props) => (
              <a {...props} target="_blank" rel="noopener noreferrer" />
            ),
          }}
        >
          {message.content}
        </ReactMarkdown>
      ),
    },
    function: {
      avatar: <div className="cursor-pointer" onClick={toggleExpand}><FunctionIcon /></div>,
      bgColor: "bg-gray-200",
      avatarColor: "bg-blue-500",
      dialogComponent: (message: Message) => {
        return (
          <div className="flex flex-col">
            {isExpanded && (
              <div className="py-1">{message.content}</div>
            )}
          </div>
        );
      },
    }    
  };


  return (
    <main className={styles.main}>
      <h1 className={styles.title}>
        πŸ”— URL Surfer πŸ„β€β™‚οΈ
      </h1>
      <div className={styles.messages}>
        {messages.length > 0 ? (
          messages.map((message, i) => {
            const messageClass = `message ${message.role === 'user' ? 'message-user' : ''}`;
            return (
              <div key={i} className={messageClass}>
                <div className="avatar">
                  {roleUIConfig[message.role].avatar}
                </div>
                {message.content === "" && message.function_call != undefined ? (
                  typeof message.function_call === "object" ? (
                    <div className="flex flex-col">
                      <div>
                        Using{" "}
                        <span className="font-bold">
                          {message.function_call.name}
                        </span>{" "}
                        ...
                      </div>
                      <div className="">
                        {message.function_call.arguments}
                      </div>
                    </div>
                  ) : (
                    <div className="function-call">{message.function_call}</div>
                  )
                ) : (
                  roleUIConfig[message.role].dialogComponent(message)
                )}
              </div>
            );
        })) : null}
      </div>
      <form onSubmit={handleSubmit} className={styles.form}>
        <input
          type="text"
          value={input}
          onChange={(e) => setInput(e.target.value)}
          placeholder="Chat with Internet"
          className={styles.input}
        />
        <button type="submit" className={styles.button} disabled={isLoading}>
          {isLoading ? 'Loading...' : 'Send'}
        </button>
      </form>
    </main>
  );
};

export default Page;