feat: prose completion api

This commit is contained in:
Jiang Feng
2025-04-26 23:12:13 +08:00
parent ba8c5fbcd3
commit 66794a4b73
16 changed files with 395 additions and 32 deletions

View File

@@ -2,11 +2,10 @@
import { Command, CommandInput } from "../../ui/command";
import { useCompletion } from "@ai-sdk/react";
import { ArrowUp } from "lucide-react";
import { useEditor } from "novel";
import { addAIHighlight } from "novel";
import { useState } from "react";
import { useCallback, useState } from "react";
import Markdown from "react-markdown";
import { toast } from "sonner";
import { Button } from "../../ui/button";
@@ -15,6 +14,8 @@ import { ScrollArea } from "../../ui/scroll-area";
import AICompletionCommands from "./ai-completion-command";
import AISelectorCommands from "./ai-selector-commands";
import { LoadingOutlined } from "@ant-design/icons";
import { resolveServiceURL } from "~/core/api/resolve-service-url";
import { fetchStream } from "~/core/sse";
//TODO: I think it makes more sense to create a custom Tiptap extension for this functionality https://tiptap.dev/docs/editor/ai/introduction
interface AISelectorProps {
@@ -22,23 +23,72 @@ interface AISelectorProps {
onOpenChange: (open: boolean) => void;
}
function useProseCompletion() {
const [completion, setCompletion] = useState("");
const [isLoading, setIsLoading] = useState(false);
const [error, setError] = useState<Error | null>(null);
const complete = useCallback(
async (prompt: string, options?: { body?: Record<string, any> }) => {
setIsLoading(true);
setError(null);
try {
const response = await fetchStream(
resolveServiceURL("/api/prose/generate"),
{
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
prompt,
...options?.body,
}),
},
);
let fullText = "";
// Process the streaming response
for await (const chunk of response) {
fullText += chunk.data;
setCompletion(fullText);
}
setIsLoading(false);
return fullText;
} catch (e) {
const error = e instanceof Error ? e : new Error("An error occurred");
setError(error);
toast.error(error.message);
setIsLoading(false);
throw error;
}
},
[],
);
const reset = useCallback(() => {
setCompletion("");
setError(null);
setIsLoading(false);
}, []);
return {
completion,
complete,
isLoading,
error,
reset,
};
}
export function AISelector({ onOpenChange }: AISelectorProps) {
const { editor } = useEditor();
const [inputValue, setInputValue] = useState("");
const { completion, complete, isLoading } = useCompletion({
// id: "novel",
api: "/api/generate",
onResponse: (response) => {
if (response.status === 429) {
toast.error("You have reached your request limit for the day.");
return;
}
},
onError: (e) => {
toast.error(e.message);
},
});
const { completion, complete, isLoading } = useProseCompletion();
if (!editor) return null;
@@ -57,7 +107,7 @@ export function AISelector({ onOpenChange }: AISelectorProps) {
)}
{isLoading && (
<div className="text-muted-foreground flex h-12 w-full items-center px-4 text-sm font-medium text-purple-500">
<div className="flex h-12 w-full items-center px-4 text-sm font-medium text-purple-500">
<Magic className="mr-2 h-4 w-4 shrink-0" />
AI is thinking
<div className="mt-1 ml-2">

View File

@@ -9,7 +9,7 @@ import { sleep } from "../utils";
import { resolveServiceURL } from "./resolve-service-url";
import type { ChatEvent } from "./types";
export function chatStream(
export async function* chatStream(
userMessage: string,
params: {
thread_id: string;
@@ -32,13 +32,19 @@ export function chatStream(
if (location.search.includes("mock") || location.search.includes("replay=")) {
return chatReplayStream(userMessage, params, options);
}
return fetchStream<ChatEvent>(resolveServiceURL("chat/stream"), {
const stream = fetchStream(resolveServiceURL("chat/stream"), {
body: JSON.stringify({
messages: [{ role: "user", content: userMessage }],
...params,
}),
signal: options.abortSignal,
});
for await (const event of stream) {
yield {
type: event.event,
data: JSON.parse(event.data),
} as ChatEvent;
}
}
async function* chatReplayStream(

View File

@@ -2,6 +2,6 @@
// SPDX-License-Identifier: MIT
export interface StreamEvent {
type: string;
data: object;
event: string;
data: string;
}

View File

@@ -3,10 +3,10 @@
import { type StreamEvent } from "./StreamEvent";
export async function* fetchStream<T extends StreamEvent>(
export async function* fetchStream(
url: string,
init: RequestInit,
): AsyncIterable<T> {
): AsyncIterable<StreamEvent> {
const response = await fetch(url, {
method: "POST",
headers: {
@@ -39,7 +39,7 @@ export async function* fetchStream<T extends StreamEvent>(
}
const chunk = buffer.slice(0, index);
buffer = buffer.slice(index + 2);
const event = parseEvent<T>(chunk);
const event = parseEvent(chunk);
if (event) {
yield event;
}
@@ -47,9 +47,9 @@ export async function* fetchStream<T extends StreamEvent>(
}
}
function parseEvent<T extends StreamEvent>(chunk: string) {
let resultType = "message";
let resultData: object | null = null;
function parseEvent(chunk: string) {
let resultEvent = "message";
let resultData: string | null = null;
for (const line of chunk.split("\n")) {
const pos = line.indexOf(": ");
if (pos === -1) {
@@ -58,16 +58,16 @@ function parseEvent<T extends StreamEvent>(chunk: string) {
const key = line.slice(0, pos);
const value = line.slice(pos + 2);
if (key === "event") {
resultType = value;
resultEvent = value;
} else if (key === "data") {
resultData = JSON.parse(value);
resultData = value;
}
}
if (resultType === "message" && resultData === null) {
if (resultEvent === "message" && resultData === null) {
return undefined;
}
return {
type: resultType,
event: resultEvent,
data: resultData,
} as T;
} as StreamEvent;
}