YC (S26) | Open Computer History | Continuously record your company computer work, map your workflows, help you find work worth automating, and power your agents' context
Rust agentsagiaiai-memoryaudio-recordingcomputer-visionhermeshermes-agentllmlocal-ailocal-firstmachine-learningmcpmultimodalopenclawprivacyrewindscreen-recordingspeech-to-textycombinator
fix function call ui, fix alignment
Louis Beaumont7ccfee2e433b
diff --git a/examples/apps/screenpipe-app-tauri/bun.lockb b/examples/apps/screenpipe-app-tauri/bun.lockbindex f63cf6f16..cc349e459 100755Binary files a/examples/apps/screenpipe-app-tauri/bun.lockb and b/examples/apps/screenpipe-app-tauri/bun.lockb differdiff --git a/examples/apps/screenpipe-app-tauri/components/chat-list-openai-v2.tsx b/examples/apps/screenpipe-app-tauri/components/chat-list-openai-v2.tsxindex da708684f..7b45e2224 100644--- a/examples/apps/screenpipe-app-tauri/components/chat-list-openai-v2.tsx+++ b/examples/apps/screenpipe-app-tauri/components/chat-list-openai-v2.tsx@@ -21,20 +21,44 @@ import { createOpenAI, openai } from "@ai-sdk/openai";import { IconOpenAI } from "./ui/icons";import { spinner } from "./spinner";import { useScrollAnchor } from "@/lib/hooks/use-scroll-anchor";+import { FunctionCallMessage } from "./function-call-message";const screenpipeQuery = z.object({- q: z.string(),- offset: z.number(),- limit: z.number(),- start_date: z.string(),- end_date: z.string(),+ q: z+ .string()+ .describe(+ "The search query matching exact keywords. Use a single keyword that best matches the user intent"+ ),+ contentType: z+ .enum(["ocr", "audio"])+ .describe(+ "The type of content to search for: screenshot data or audio transcriptions"+ ),+ limit: z+ .number()+ .default(5)+ .describe(+ "Number of results to return (default: 5). Don't return more than 50 results as it will be fed to an LLM"+ ),+ offset: z.number().default(0).describe("Offset for pagination (default: 0)"),+ startTime: z+ .string()+ // 1 hour ago+ .default(new Date(Date.now() - 3600000).toISOString())+ .describe("Start time for search range in ISO 8601 format"),+ endTime: z+ .string()+ .default(new Date().toISOString())+ .describe("End time for search range in ISO 8601 format"),+});+const screenpipeMultiQuery = z.object({+ queries: z.array(screenpipeQuery),});-const screenpipeMultiQuery = z.array(screenpipeQuery);async function queryScreenpipeNtimes(params: z.infer<typeof screenpipeMultiQuery>) {- await Promise.all(params.map(queryScreenpipe));+ return Promise.all(params.queries.map(queryScreenpipe));}// Add this new function to handle screenpipe requests@@ -44,8 +68,9 @@ async function queryScreenpipe(params: z.infer<typeof screenpipeQuery>) {q: params.q,offset: params.offset.toString(),limit: params.limit.toString(),- start_date: params.start_date,- end_date: params.end_date,+ start_date: params.startTime,+ end_date: params.endTime,+ content_type: params.contentType,});console.log("calling screenpipe", JSON.stringify(params));const response = await fetch(`http://localhost:3030/search?${queryParams}`);@@ -89,9 +114,9 @@ export function ChatList({ apiKey }: { apiKey: string }) {tools: {query_screenpipe: {description:- "Query the local screenpipe instance for relevant information (UPDATE: just do a SINGLE QUERY ATM)",- parameters: screenpipeQuery,- execute: queryScreenpipe,+ "Query the local screenpipe instance for relevant information. You will return multiple queries under the key 'queries'.",+ parameters: screenpipeMultiQuery,+ execute: queryScreenpipeNtimes,},},toolChoice: "required",@@ -103,7 +128,7 @@ export function ChatList({ apiKey }: { apiKey: string }) {his screen and mics 24/7. The user ask you questionsand you use his screenpipe recordings to answer him.Based on the user request, use tools to screenpipe to best help the user.- Each query should have "q", "offset", "limit", and start_date, end_date fields.+ Each query should have "q", "offset", "limit", "start_date", "end_date", and "content_type" fields.Rules:- q should be a single keyword that would properly find in the text found on the user screen some infomation that would help answering the user question.Return a list of objects with the key "queries"@@ -113,6 +138,7 @@ export function ChatList({ apiKey }: { apiKey: string }) {- DO NOT add \`\`\`json at the beginning or end of your response- Do not use '"' around your response- Date & time now is ${new Date().toISOString()}+ - If the user ask about his morning do not use morning as query that's dumb, try to infer some keywords from the user questionExample answers from you:"{@@ -132,40 +158,6 @@ export function ChatList({ apiKey }: { apiKey: string }) {]}"- Bad example- "Here's the JSON you wanted:- [- {- "queries": [{"q": "sales", "offset": 0, "limit": 10}]- },- {- "queries": [{"q": "customer", "offset": 0, "limit": 20}]- },- {- "queries": [{"q": "goal", "offset": 0, "limit": 10}]- }- ]"- or- "\`\`\`json- [- {- "queries": [- {"q": "goals", "offset": 0, "limit": 3}- ]- },- {- "queries": [- {"q": "life plans", "offset": 0, "limit": 5}- ]- },- {- "queries": [- {"q": "ambitions", "offset": 0, "limit": 3}- ]- }- ]- \`\`\`"- JSON?`,},{@@ -187,12 +179,19 @@ export function ChatList({ apiKey }: { apiKey: string }) {{ id: nanoid(), role: "tool", content: text.toolResults },]);+ console.log("streaming now");++ console.log("toolCalls", text.toolCalls);+ console.log("toolResults", text.toolResults);+const { textStream } = await streamText({model: provider("gpt-4o"),messages: [{role: "user",- content: inputMessage,+ content:+ messages.findLast((msg) => msg.role === "user")?.content ||+ inputMessage,},{role: "assistant",@@ -205,6 +204,8 @@ export function ChatList({ apiKey }: { apiKey: string }) {],});+ console.log("textStream", textStream);+// create new assistantconst assistantMessageId = nanoid();setMessages((prevMessages) => [@@ -215,6 +216,7 @@ export function ChatList({ apiKey }: { apiKey: string }) {let fullResponse = "";for await (const chunk of textStream) {fullResponse += chunk;+ console.log("fullResponse", fullResponse);setMessages((prevMessages) =>prevMessages.map((msg) =>msg.id === assistantMessageId@@ -275,27 +277,25 @@ export function ChatList({ apiKey }: { apiKey: string }) {className="flex flex-col items-start flex-1 max-w-2xl gap-8 px-4 mx-auto"ref={messagesRef}>- {/* display user message */}-- {messages- // only show string messages- .filter((msg) => msg.role === "user")- .map((msg, index) => (- <ChatMessage key={index} message={msg} />- ))}-+ {messages.map((msg, index) => {+ if (+ msg.role === "user" ||+ (msg.role === "assistant" && typeof msg.content === "string")+ ) {+ return <ChatMessage key={index} message={msg} />;+ } else if (+ msg.role === "assistant" &&+ msg.content &&+ typeof msg.content === "object"+ ) {+ return <FunctionCallMessage key={index} message={msg} />;+ } else if (msg.role === "tool") {+ return <FunctionCallMessage key={index} message={msg} isResult />;+ }+ return null;+ })}{isLoading && <SpinnerMessage />}-{error && <p className="text-red-500">{error}</p>}- {messages- // only show string messages from assistant- .filter(- (msg) =>- msg.role === "assistant" && typeof msg.content === "string"- )- .map((msg, index) => (- <ChatMessage key={index} message={msg} />- ))}</div>{messages.length === 0 && (@@ -328,8 +328,8 @@ export function ChatList({ apiKey }: { apiKey: string }) {</Button></div><p className="text-xs font-medium text-center text-neutral-700">- screenpipe canNOT make mistakes. Consider checking important- information.+ screenpipe is in beta, base its answer on your computer activity+ and can make errors.</p></div>)}@@ -351,46 +351,6 @@ export function SpinnerMessage() {);}-// export const getUIStateFromAIState = (aiState: Chat) => {-// return aiState.messages-// .filter((message) => message.role !== "system")-// .map((message, index) => ({-// id: `${aiState.chatId}-${index}`,-// display:-// message.role === "tool" ? (-// message.content.map((tool) => {-// return tool.toolName === "listStocks" ? (-// <BotCard>-// {/* TODO: Infer types based on the tool result*/}-// {/* @ts-expect-error */}-// <Stocks props={tool.result} />-// </BotCard>-// ) : tool.toolName === "showStockPrice" ? (-// <BotCard>-// {/* @ts-expect-error */}-// <Stock props={tool.result} />-// </BotCard>-// ) : tool.toolName === "showStockPurchase" ? (-// <BotCard>-// {/* @ts-expect-error */}-// <Purchase props={tool.result} />-// </BotCard>-// ) : tool.toolName === "getEvents" ? (-// <BotCard>-// {/* @ts-expect-error */}-// <Events props={tool.result} />-// </BotCard>-// ) : null;-// })-// ) : message.role === "user" ? (-// <UserMessage>{message.content as string}</UserMessage>-// ) : message.role === "assistant" &&-// typeof message.content === "string" ? (-// <BotMessage content={message.content} />-// ) : null,-// }));-// };-function ArrowUpIcon(props) {return (<svgdiff --git a/examples/apps/screenpipe-app-tauri/components/chat-message-v2.tsx b/examples/apps/screenpipe-app-tauri/components/chat-message-v2.tsxindex dd573404a..4abba62cf 100644--- a/examples/apps/screenpipe-app-tauri/components/chat-message-v2.tsx+++ b/examples/apps/screenpipe-app-tauri/components/chat-message-v2.tsx@@ -18,7 +18,7 @@ export interface ChatMessageProps {export function ChatMessage({ message, ...props }: ChatMessageProps) {return (<div- className={cn("group relative mb-4 flex items-start md:-ml-12")}+ className={cn("group relative mb-4 flex items-start md:-ml-12 w-full")}{...props}><div@@ -31,35 +31,26 @@ export function ChatMessage({ message, ...props }: ChatMessageProps) {>{message.role === "user" ? <IconUser /> : <IconOpenAI />}</div>- <div className="flex-1 px-1 ml-4 space-y-2 overflow-hidden">+ <div className="flex-1 px-1 ml-4 space-y-2 overflow-hidden w-[96em]"><MemoizedReactMarkdown- className="prose break-words dark:prose-invert prose-p:leading-relaxed prose-pre:p-0"+ className="prose break-words dark:prose-invert prose-p:leading-relaxed prose-pre:p-0 w-full"remarkPlugins={[remarkGfm, remarkMath]}components={{p({ children }) {return <p className="mb-2 last:mb-0">{children}</p>;},- code({ node, inline, className, children, ...props }) {- let childrenContent = Array.isArray(children)- ? children[0]- : children;-- if (typeof childrenContent === "string") {- if (childrenContent === "▍") {- return (- <span className="mt-1 cursor-default animate-pulse">▍</span>- );- }-- childrenContent = childrenContent.replace("`▍`", "▍");- }-+ code({ node, className, children, ...props }) {+ const content = String(children).replace(/\n$/, "");const match = /language-(\w+)/.exec(className || "");-- if (inline) {++ console.log("isInline", content, node);+ if (!match) {return (- <code className={className} {...props}>- {childrenContent}+ <code+ className="px-1 py-0.5 rounded-sm bg-gray-100 dark:bg-gray-800 font-mono text-sm"+ {...props}+ >+ {content}</code>);}@@ -68,7 +59,7 @@ export function ChatMessage({ message, ...props }: ChatMessageProps) {<CodeBlockkey={Math.random()}language={(match && match[1]) || ""}- value={String(childrenContent).replace(/\n$/, "")}+ value={content}{...props}/>);diff --git a/examples/apps/screenpipe-app-tauri/components/function-call-message.tsx b/examples/apps/screenpipe-app-tauri/components/function-call-message.tsxnew file mode 100644index 000000000..0f8509c02--- /dev/null+++ b/examples/apps/screenpipe-app-tauri/components/function-call-message.tsx@@ -0,0 +1,148 @@+import React from "react";+import { Message } from "ai";+import { Badge } from "@/components/ui/badge";+import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";+import { IconOpenAI } from "@/components/ui/icons";+import {+ Accordion,+ AccordionContent,+ AccordionItem,+ AccordionTrigger,+} from "@/components/ui/accordion";+import { MemoizedReactMarkdown } from "./markdown";+import remarkGfm from "remark-gfm";+import remarkMath from "remark-math";+import { CodeBlock } from "./ui/codeblock";++interface FunctionCallMessageProps {+ message: Message;+ isResult?: boolean;+}++export function FunctionCallMessage({+ message,+ isResult = false,+}: FunctionCallMessageProps) {+ console.log("FunctionCallMessage", message);+ // @ts-ignore TODO+ const toolCalls = message.content.filter((content) => !content.result);+ // @ts-ignore TODO+ const toolResults = message.content.filter((content) => content.result);++ console.log("toolCalls", toolCalls);+ console.log("toolResults", toolResults);+ return (+ <div className="group relative mb-4 flex items-start md:-ml-12">+ <div className="flex size-8 shrink-0 select-none items-center justify-center rounded-md border shadow bg-primary text-primary-foreground">+ <IconOpenAI />+ </div>+ <div className="flex-1 px-1 ml-4 space-y-2 overflow-hidden">+ <Card className="w-full">+ <CardHeader>+ <CardTitle className="text-sm font-medium">+ {isResult ? "Function Result" : "Function Call"}+ </CardTitle>+ </CardHeader>+ <CardContent>+ {!isResult && (+ <Accordion type="single" collapsible className="w-full">+ {toolCalls.map((toolCall: any, index: number) => (+ <AccordionItem key={index} value={`item-${index}`}>+ <AccordionTrigger>+ <Badge variant="secondary" className="mr-2">+ {toolCall.type}+ </Badge>+ {toolCall.toolName}+ </AccordionTrigger>+ <AccordionContent>+ <MarkdownContent+ content={`\`\`\`json\n${JSON.stringify(+ toolCall,+ null,+ 2+ )}\n\`\`\``}+ />+ </AccordionContent>+ </AccordionItem>+ ))}+ </Accordion>+ )}+ {isResult && (+ <Accordion type="single" collapsible className="w-full">+ {toolResults.map((toolResult: any, index: number) => (+ <AccordionItem key={index} value={`item-${index}`}>+ <AccordionTrigger>+ <Badge variant="secondary" className="mr-2">+ {toolResult.type}+ </Badge>+ {toolResult.toolName}+ </AccordionTrigger>+ <AccordionContent>+ <MarkdownContent+ content={`\`\`\`json\n${JSON.stringify(+ toolResult,+ null,+ 2+ )}\n\`\`\``}+ />+ </AccordionContent>+ </AccordionItem>+ ))}+ </Accordion>+ )}+ </CardContent>+ </Card>+ </div>+ </div>+ );+}++function MarkdownContent({ content }: { content: string }) {+ return (+ <MemoizedReactMarkdown+ className="prose break-words dark:prose-invert prose-p:leading-relaxed prose-pre:p-0 w-full"+ remarkPlugins={[remarkGfm, remarkMath]}+ components={{+ p({ children }) {+ return <p className="mb-2 last:mb-0">{children}</p>;+ },+ code({ node, inline, className, children, ...props }) {+ let childrenContent = Array.isArray(children)+ ? children[0]+ : children;++ if (typeof childrenContent === "string") {+ if (childrenContent === "▍") {+ return (+ <span className="mt-1 cursor-default animate-pulse">▍</span>+ );+ }++ childrenContent = childrenContent.replace("`▍`", "▍");+ }++ const match = /language-(\w+)/.exec(className || "");++ if (inline) {+ return (+ <code className={className} {...props}>+ {childrenContent}+ </code>+ );+ }++ return (+ <CodeBlock+ key={Math.random()}+ language={(match && match[1]) || ""}+ value={String(childrenContent).replace(/\n$/, "")}+ {...props}+ />+ );+ },+ }}+ >+ {content}+ </MemoizedReactMarkdown>+ );+}diff --git a/examples/apps/screenpipe-app-tauri/components/ui/accordion.tsx b/examples/apps/screenpipe-app-tauri/components/ui/accordion.tsxnew file mode 100644index 000000000..24c788c2c--- /dev/null+++ b/examples/apps/screenpipe-app-tauri/components/ui/accordion.tsx@@ -0,0 +1,58 @@+"use client"++import * as React from "react"+import * as AccordionPrimitive from "@radix-ui/react-accordion"+import { ChevronDown } from "lucide-react"++import { cn } from "@/lib/utils"++const Accordion = AccordionPrimitive.Root++const AccordionItem = React.forwardRef<+ React.ElementRef<typeof AccordionPrimitive.Item>,+ React.ComponentPropsWithoutRef<typeof AccordionPrimitive.Item>+>(({ className, ...props }, ref) => (+ <AccordionPrimitive.Item+ ref={ref}+ className={cn("border-b", className)}+ {...props}+ />+))+AccordionItem.displayName = "AccordionItem"++const AccordionTrigger = React.forwardRef<+ React.ElementRef<typeof AccordionPrimitive.Trigger>,+ React.ComponentPropsWithoutRef<typeof AccordionPrimitive.Trigger>+>(({ className, children, ...props }, ref) => (+ <AccordionPrimitive.Header className="flex">+ <AccordionPrimitive.Trigger+ ref={ref}+ className={cn(+ "flex flex-1 items-center justify-between py-4 font-medium transition-all hover:underline [&[data-state=open]>svg]:rotate-180",+ className+ )}+ {...props}+ >+ {children}+ <ChevronDown className="h-4 w-4 shrink-0 transition-transform duration-200" />+ </AccordionPrimitive.Trigger>+ </AccordionPrimitive.Header>+))+AccordionTrigger.displayName = AccordionPrimitive.Trigger.displayName++const AccordionContent = React.forwardRef<+ React.ElementRef<typeof AccordionPrimitive.Content>,+ React.ComponentPropsWithoutRef<typeof AccordionPrimitive.Content>+>(({ className, children, ...props }, ref) => (+ <AccordionPrimitive.Content+ ref={ref}+ className="overflow-hidden text-sm transition-all data-[state=closed]:animate-accordion-up data-[state=open]:animate-accordion-down"+ {...props}+ >+ <div className={cn("pb-4 pt-0", className)}>{children}</div>+ </AccordionPrimitive.Content>+))++AccordionContent.displayName = AccordionPrimitive.Content.displayName++export { Accordion, AccordionItem, AccordionTrigger, AccordionContent }diff --git a/examples/apps/screenpipe-app-tauri/package.json b/examples/apps/screenpipe-app-tauri/package.jsonindex a9d24675d..892875073 100644--- a/examples/apps/screenpipe-app-tauri/package.json+++ b/examples/apps/screenpipe-app-tauri/package.json@@ -13,6 +13,7 @@"dependencies": {"@ai-sdk/openai": "^0.0.39","@mlc-ai/web-llm": "^0.2.51",+ "@radix-ui/react-accordion": "^1.2.0","@radix-ui/react-avatar": "^1.1.0","@radix-ui/react-dropdown-menu": "^2.1.1","@radix-ui/react-icons": "^1.3.0",