Skip to content

Rich chat Assistant #215

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 6 commits into from
Mar 7, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
184 changes: 182 additions & 2 deletions packages/app-copywriter/chat.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,11 @@ import { PaperPlaneIcon } from "@radix-ui/react-icons";
import ReactMarkdown from "react-markdown";
import type { Message } from "./core/conversation";
import * as api from "./client";
import {
remarkColorPlugin,
remarkGradientPlugin,
remarkQuotationPlugin,
} from "./plugins";

export function ChatScreen() {
const [busy, setBusy] = React.useState(false);
Expand All @@ -31,7 +36,8 @@ export function ChatScreen() {

api
.chat({ content: message, history: history })
.then(({ response }) => {
.then(({ response, meta }) => {
// console.log("re:", response);
setMessages((l) =>
l.concat({
role: "assistant",
Expand Down Expand Up @@ -106,6 +112,24 @@ export function ChatScreen() {
style={{
background: "white",
}}
onPreviousPrompt={() => {
// load the previous prompt
setMessage(
messages
.filter((m) => m.role === "user")
.map((m) => m.content)
.pop() || ""
);
}}
onNextPrompt={() => {
// load the next prompt
setMessage(
messages
.filter((m) => m.role === "user")
.map((m) => m.content)
.shift() || ""
);
}}
/>
</motion.div>
</div>
Expand Down Expand Up @@ -179,7 +203,90 @@ const Messages = React.forwardRef(function Messages(
{emoji}
</div>
<p>
<ReactMarkdown>{content}</ReactMarkdown>
<MarkdownView
remarkPlugins={[
remarkQuotationPlugin,
remarkGradientPlugin,
remarkColorPlugin,
]}
disallowedElements={[]}
components={{
data: ({ node, ...props }) => {
alert(JSON.stringify(node));
return <strong {...props}></strong>;
},
img: ({ node, ...props }) => (
<CustomGraphic {...props} />
),
h1: ({ node, ...props }) => (
// p
<strong>
<p {...props} />
</strong>
),
h2: ({ node, ...props }) => (
// p
<strong>
<p {...props} />
</strong>
),
h3: ({ node, ...props }) => (
// p
<p {...props} />
),
h4: ({ node, ...props }) => (
// p
<p {...props} />
),
h5: ({ node, ...props }) => (
// p
<p {...props} />
),
h6: ({ node, ...props }) => (
// p
<p {...props} />
),
li: ({ node, ...props }) => (
<ActionableListItem {...props} />
),
ul: ({ node, ...props }) => (
<ul
style={{
margin: 0,
}}
{...props}
/>
),
code: ({ node, ...props }) => (
<code
style={{
background: "rgba(0,0,0,0.1)",
padding: 4,
borderRadius: 4,
fontFamily: "monospace",
fontSize: 14,
display: "inline-block",
whiteSpace: "pre-wrap",
wordBreak: "break-word",
wordWrap: "break-word",
overflowWrap: "break-word",
hyphens: "auto",
lineHeight: 1.5,
overflowX: "auto",
boxShadow: "0 0 0 1px rgba(0,0,0,0.1)",
color: "rgba(0,0,0,0.8)",
border: "none",
outline: "none",
resize: "none",
verticalAlign: "top",
}}
{...props}
/>
),
}}
>
{content}
</MarkdownView>
</p>
</Bubble>
</ResponseItem>
Expand All @@ -191,3 +298,76 @@ const Messages = React.forwardRef(function Messages(
</>
);
});

function CustomGraphic({
src,
alt,
...props
}: React.ImgHTMLAttributes<HTMLImageElement>) {
let __type: "img" | "div" = "img";
let __src = src;
let __background = "transparent";
// transform src
try {
const _ = new URL(alt);

switch (_.protocol) {
case "color:":
__type = "div";
__src = "//:0";
__background = alt.replace("color://", "");

break;
}
} catch (e) {}

switch (__type) {
case "div":
return (
<div
id="custom-graphic"
{...props}
style={{
margin: 4,
background: __background,
width: 64,
height: 64,
borderRadius: 8,
}}
/>
);
case "img": {
return (
<img
id="custom-graphic"
{...props}
src={__src}
style={{
margin: 4,
width: 160,
height: 160,
objectFit: "cover",
}}
/>
);
}
}
}

const MarkdownView = styled(ReactMarkdown)`
ul {
padding-inline-start: 0px;
}
`;

const ActionableListItem = styled.li`
list-style: none;
margin: 8px;
border-radius: 4px;
padding: 8px;
box-shadow: 0 0 0 1px rgba(0, 0, 0, 0.1);

&:hover {
box-shadow: 0 4px 4px 1px rgba(0, 0, 0, 0.1);
}
`;
1 change: 1 addition & 0 deletions packages/app-copywriter/client/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ interface ChatPrompt {

interface ChatResponse {
q: string;
meta: any;
response: string;
model: string;
}
Expand Down
2 changes: 1 addition & 1 deletion packages/app-copywriter/components/bubble.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ const BubbleWrapper = styled.div`
}

&:hover {
background: rgba(0, 0, 0, 0.08);
background: rgba(0, 0, 0, 0.04);
}

transition: all 0.05s ease-in-out;
Expand Down
70 changes: 70 additions & 0 deletions packages/app-copywriter/plugins.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
import visit from "unist-util-visit";

export const remarkQuotationPlugin = () => {
return (tree) => {
visit(tree, "paragraph", (node: any) => {
if (node.__set_by_remark_quotation_plugin) return;
visit(node, "text", (node: any) => {
if (node.__set_by_remark_quotation_plugin) return;

const pattern = /"([^"]*)"/g;
const match = node.value.match(pattern);
if (match) {
node.type = "listItem";
node.children = [
{
type: "paragraph",
__set_by_remark_quotation_plugin: true,
children: [
{
type: "text",
value: match[0],
__set_by_remark_quotation_plugin: true,
},
],
},
];

// node.value = match[0];
}
});
});
};
};

export const remarkGradientPlugin = () => {
return (tree) => {
visit(tree, ["code", "text"], (node: any) => {
const pattern =
/(linear|radial)-gradient\([^(]*(\([^)]*\)[^(]*)*[^)]*\)/g;
const match = node.value.match(pattern);
if (match) {
node.type = "image";
node.url = `//:0`;
node.alt = `color://${match[0]}`;
}
});
};
};

export const remarkColorPlugin = () => {
return (tree) => {
visit(tree, ["code", "text"], (node: any) => {
const pattern_hex = /#[0-9a-fA-F]{6}/g;
const pattern_rgb = /rgb\(\d{1,3},\d{1,3},\d{1,3}\)/g;
const pattern_rgba = /rgba\(\d{1,3},\d{1,3},\d{1,3},\d{1,3}\)/g;

const match_hex = node.value.match(pattern_hex);
const match_rgb = node.value.match(pattern_rgb);
const match_rgba = node.value.match(pattern_rgba);

const match = match_hex || match_rgb || match_rgba;

if (match) {
node.type = "image";
node.url = `//:0`;
node.alt = `color://${match[0]}`;
}
});
};
};
3 changes: 2 additions & 1 deletion packages/ui-ai/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
"@tiptap/starter-kit": "^2.0.0-beta.220",
"@tiptap/suggestion": "^2.0.0-beta.220",
"lowlight": "^2.8.1",
"react-markdown": "^8.0.5"
"react-markdown": "^8.0.5",
"unist-util-visit": "^4.1.2"
}
}
29 changes: 22 additions & 7 deletions packages/ui-ai/prompt/prompt.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,8 @@ export function PromptInputBox({
prompting = false,
submit: submitConfig,
style = {},
onPreviousPrompt,
onNextPrompt,
}: {
readonly?: boolean;
onSubmit?: () => void;
Expand All @@ -37,6 +39,8 @@ export function PromptInputBox({
icon?: React.ReactNode;
};
style?: React.CSSProperties;
onPreviousPrompt?: () => void;
onNextPrompt?: () => void;
}) {
const [focused, setFocused] = React.useState(false);
const ref = React.useRef<HTMLTextAreaElement>(null);
Expand All @@ -58,6 +62,24 @@ export function PromptInputBox({
data-prompting={prompting}
data-focused={focused}
style={style}
onKeyDown={(e) => {
// if shift + enter, new line
if (e.key === "Enter" && !e.shiftKey) {
e.preventDefault();
submit();
}

if (value.trim().length === 0) {
if (e.key === "ArrowUp") {
e.preventDefault();
onPreviousPrompt?.();
}
if (e.key === "ArrowDown") {
e.preventDefault();
onNextPrompt?.();
}
}
}}
>
{/* <TiptapInput
placeholder={placeholder}
Expand All @@ -69,13 +91,6 @@ export function PromptInputBox({
<TextareaAutosize
ref={ref}
onChange={(e) => onChange?.(e.target.value)}
onKeyDown={(e) => {
// if shift + enter, new line
if (e.key === "Enter" && !e.shiftKey) {
e.preventDefault();
submit();
}
}}
value={value}
onFocus={() => setFocused(true)}
onBlur={() => setFocused(false)}
Expand Down
5 changes: 3 additions & 2 deletions web/pages/api/generative/chat.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { NextApiRequest, NextApiResponse } from "next";
import { chatcompletion } from "service/completion";
import { assistCompletion } from "service/assistant";

export default async function handler(
req: NextApiRequest,
Expand All @@ -15,7 +15,7 @@ export default async function handler(
return;
}

const { texts, model } = await chatcompletion({
const { texts, model, meta } = await assistCompletion({
prompt: content,
history: history,
n: 1,
Expand All @@ -26,6 +26,7 @@ export default async function handler(
res.json({
q: content,
response: texts[0],
meta: meta,
model: model,
});
}
Expand Down
Loading