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
iterate on app ui
Louis Beaumont83b9f503763c
diff --git a/Cargo.toml b/Cargo.tomlindex 18d70c1d1..2f7b8de87 100644--- a/Cargo.toml+++ b/Cargo.toml@@ -4,9 +4,10 @@ members = ["screenpipe-vision","screenpipe-audio","screenpipe-server",+]exclude = [- "examples/apps/screenpipe-app-tauri/src-tauri",+ "examples/apps/screenpipe-app-tauri/src-tauri","examples/apps/screenpipe-app-dioxus",]resolver = "2"@@ -28,6 +29,7 @@ candle-transformers = { package = "candle-transformers", version = "0.6.0" }tokenizers = "0.19.1"tracing = "0.1.37"tokio = { version = "1.15", features = ["full", "tracing"] }+hf-hub = "0.3.0"# devcriterion = { version = "0.5.1", features = ["async_tokio"] }diff --git a/examples/apps/screenpipe-app-tauri/app/page.tsx b/examples/apps/screenpipe-app-tauri/app/page.tsxindex df8ccff80..0e70fcf5f 100644--- a/examples/apps/screenpipe-app-tauri/app/page.tsx+++ b/examples/apps/screenpipe-app-tauri/app/page.tsx@@ -1,6 +1,6 @@"use client";-import { ChatList } from "@/components/chat-list-openai";+import { ChatList } from "@/components/chat-list-openai-v2";import Image from "next/image";import { Button } from "@/components/ui/button"; // Import Button from shadcnimport RagExample from "@/components/rag-example";@@ -54,12 +54,49 @@ function Header() {</div>);}++import { useEffect, useState } from "react"; // Import useState++function Settings({ onKeyChange }) {+ const [apiKey, setApiKey] = useState("");++ useEffect(() => {+ const savedKey = localStorage.getItem("openaiApiKey"); // Load saved key from local storage+ if (savedKey) {+ setApiKey(savedKey);+ onKeyChange(savedKey); // Pass the loaded key to parent+ }+ }, [onKeyChange]);++ const handleChange = (e) => {+ const newKey = e.target.value;+ setApiKey(newKey);+ localStorage.setItem("openaiApiKey", newKey); // Save key to local storage+ onKeyChange(newKey);+ };++ return (+ <div className="settings">+ <input+ type="text"+ value={apiKey}+ onChange={handleChange}+ placeholder="Enter OpenAI API Key"+ className="border p-2"+ />+ </div>+ );+}export default function Home() {+ const [openAiKey, setOpenAiKey] = useState("");+return (<main className="flex min-h-screen flex-col items-center justify-between p-8"><Header /> {/* Use Header component */}{/* TODO for some reason code block style broken when built */}{/* <RagExample /> */}+ <Settings onKeyChange={setOpenAiKey} />+ <ChatList apiKey={openAiKey} /></main>);}diff --git a/examples/apps/screenpipe-app-tauri/bun.lockb b/examples/apps/screenpipe-app-tauri/bun.lockbindex 3cdc14226..f63cf6f16 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.tsxnew file mode 100644index 000000000..da708684f--- /dev/null+++ b/examples/apps/screenpipe-app-tauri/components/chat-list-openai-v2.tsx@@ -0,0 +1,614 @@+"use client";+import { useState } from "react";+import OpenAI from "openai";+import { z } from "zod";+import { zodToJsonSchema } from "zod-to-json-schema";+import { Button } from "@/components/ui/button";+import { Textarea } from "@/components/ui/textarea";+import { Avatar, AvatarImage, AvatarFallback } from "@/components/ui/avatar";+import {+ DropdownMenu,+ DropdownMenuTrigger,+ DropdownMenuContent,+ DropdownMenuItem,+ DropdownMenuSeparator,+} from "@/components/ui/dropdown-menu";+import { Badge } from "@/components/ui/badge";+import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";+import { ChatMessage } from "./chat-message-v2";+import { Message, generateText, nanoid, streamText, tool } from "ai";+import { createOpenAI, openai } from "@ai-sdk/openai";+import { IconOpenAI } from "./ui/icons";+import { spinner } from "./spinner";+import { useScrollAnchor } from "@/lib/hooks/use-scroll-anchor";++const screenpipeQuery = z.object({+ q: z.string(),+ offset: z.number(),+ limit: z.number(),+ start_date: z.string(),+ end_date: z.string(),+});+const screenpipeMultiQuery = z.array(screenpipeQuery);++async function queryScreenpipeNtimes(+ params: z.infer<typeof screenpipeMultiQuery>+) {+ await Promise.all(params.map(queryScreenpipe));+}++// Add this new function to handle screenpipe requests+async function queryScreenpipe(params: z.infer<typeof screenpipeQuery>) {+ try {+ const queryParams = new URLSearchParams({+ q: params.q,+ offset: params.offset.toString(),+ limit: params.limit.toString(),+ start_date: params.start_date,+ end_date: params.end_date,+ });+ console.log("calling screenpipe", JSON.stringify(params));+ const response = await fetch(`http://localhost:3030/search?${queryParams}`);+ if (!response.ok) {+ const text = await response.text();+ throw new Error(`HTTP error! status: ${response.status} ${text}`);+ }+ const result = await response.json();+ console.log("result", result);+ return result;+ } catch (error) {+ console.error("Error querying screenpipe:", error);+ return null;+ }+}++export function ChatList({ apiKey }: { apiKey: string }) {+ const [messages, setMessages] = useState<Message[]>([]);+ const [inputMessage, setInputMessage] = useState("");+ const [isLoading, setIsLoading] = useState(false);+ const [error, setError] = useState<string | null>(null);++ const { messagesRef, scrollRef, visibilityRef, isAtBottom, scrollToBottom } =+ useScrollAnchor();+ const handleSendMessage = async () => {+ if (!inputMessage.trim()) return;++ setIsLoading(true);+ setError(null);++ const userMessage = { id: nanoid(), role: "user", content: inputMessage };+ setMessages((prevMessages) => [...prevMessages, userMessage]);+ setInputMessage("");++ try {+ const provider = createOpenAI({+ apiKey: apiKey,+ });+ const text = await generateText({+ model: provider("gpt-4o"),+ tools: {+ query_screenpipe: {+ description:+ "Query the local screenpipe instance for relevant information (UPDATE: just do a SINGLE QUERY ATM)",+ parameters: screenpipeQuery,+ execute: queryScreenpipe,+ },+ },+ toolChoice: "required",+ messages: [+ {+ role: "system",+ content: `You are a helpful assistant.+ The user is using a product called "screenpipe" which records+ his screen and mics 24/7. The user ask you questions+ and 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.+ 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"+ - q contains a single query, again, for example instead of "life plan" just use "life"+ - Respond with only the updated JSON object+ - If you return something else than JSON the universe will come to an end+ - 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()}++ Example answers from you:+ "{+ "queries": [+ {"q": "goal", "offset": 0, "limit": 10, "start_date": "2024-07-21T11:30:25Z", "end_date": "2024-07-21T11:35:25Z"},+ {"q": "stripe", "offset": 0, "limit": 50, "start_date": "2024-07-19T08:00:25Z", "end_date": "2024-07-20T09:00:25Z"},+ {"q": "customer", "offset": 0, "limit": 20, "start_date": "2024-07-19T08:00:25Z", "end_date": "2024-07-20T09:00:25Z"}+ ]+ }"++ or+ "{+ "queries": [+ {"q": "sales", "offset": 0, "limit": 10, "start_date": "2024-07-21T11:30:25Z", "end_date": "2024-07-21T11:35:25Z"},+ {"q": "customer", "offset": 0, "limit": 20, "start_date": "2024-07-19T08:00:25Z", "end_date": "2024-07-20T09:00:25Z"},+ {"q": "goal", "offset": 0, "limit": 10, "start_date": "2024-07-19T08:00:25Z", "end_date": "2024-07-20T09:00:25Z"}+ ]+ }"++ 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?+ `,+ },+ {+ role: "user",+ content: inputMessage,+ },+ ],+ // maxToolRoundtrips: 5, // allow up to 5 tool roundtrips+ // prompt: inputMessage,+ });++ setIsLoading(false);++ console.log("text", text);++ setMessages((prevMessages) => [+ ...prevMessages,+ { id: nanoid(), role: "assistant", content: text.toolCalls },+ { id: nanoid(), role: "tool", content: text.toolResults },+ ]);++ const { textStream } = await streamText({+ model: provider("gpt-4o"),+ messages: [+ {+ role: "user",+ content: inputMessage,+ },+ {+ role: "assistant",+ content: text.toolCalls,+ },+ {+ role: "tool",+ content: text.toolResults,+ },+ ],+ });++ // create new assistant+ const assistantMessageId = nanoid();+ setMessages((prevMessages) => [+ ...prevMessages,+ { id: assistantMessageId, role: "assistant", content: "" },+ ]);++ let fullResponse = "";+ for await (const chunk of textStream) {+ fullResponse += chunk;+ setMessages((prevMessages) =>+ prevMessages.map((msg) =>+ msg.id === assistantMessageId+ ? { ...msg, content: fullResponse }+ : msg+ )+ );+ }+ } catch (error) {+ console.error(error);+ } finally {+ setIsLoading(false);+ }+ };++ return (+ <div+ className="grid md:grid-cols-[520] min-h-screen w-full"+ ref={scrollRef}+ >+ <div className="flex flex-col">+ <div className="sticky top-0 p-2">+ <DropdownMenu>+ <DropdownMenuTrigger asChild disabled>+ <Button+ variant="ghost"+ className="gap-1 rounded-xl px-3 h-10 data-[state=open]:bg-muted text-lg"+ >+ llama <span className="text-muted-foreground">3.1-8B</span>+ <ChevronDownIcon className="w-4 h-4 text-muted-foreground" />+ </Button>+ </DropdownMenuTrigger>+ <DropdownMenuContent align="start" className="max-w-[300px]">+ <DropdownMenuItem className="items-start gap-2">+ <SparkleIcon className="w-4 h-4 mr-2 translate-y-1 shrink-0" />+ <div>+ <div className="font-medium">GPT-4</div>+ <div className="text-muted-foreground/80">+ With DALL-E, browing and analysis. Limit 40 messages / 3+ hours+ </div>+ </div>+ </DropdownMenuItem>+ <DropdownMenuSeparator />+ <DropdownMenuItem className="items-start gap-2">+ <ZapIcon className="w-4 h-4 mr-2 translate-y-1 shrink-0" />+ <div>+ <div className="font-medium">GPT-3</div>+ <div className="text-muted-foreground/80">+ Great for everyday tasks+ </div>+ </div>+ </DropdownMenuItem>+ </DropdownMenuContent>+ </DropdownMenu>+ </div>+ <div+ 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} />+ ))}++ {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 && (+ <div className="max-w-2xl w-full sticky bottom-0 mx-auto py-2 flex flex-col gap-1.5 px-4 bg-background">+ <div className="relative">+ <Textarea+ placeholder="Message screenpipe..."+ name="message"+ id="message"+ rows={1}+ className="min-h-[48px] rounded-2xl resize-none p-4 border border-neutral-400 shadow-sm pr-16"+ value={inputMessage}+ onChange={(e) => setInputMessage(e.target.value)}+ onKeyPress={(e) => {+ if (e.key === "Enter" && !e.shiftKey) {+ e.preventDefault();+ handleSendMessage();+ }+ }}+ />+ <Button+ type="submit"+ size="icon"+ className="absolute w-8 h-8 top-3 right-3"+ onClick={handleSendMessage}+ disabled={isLoading || !inputMessage.trim()}+ >+ <ArrowUpIcon className="w-4 h-4" />+ <span className="sr-only">Send</span>+ </Button>+ </div>+ <p className="text-xs font-medium text-center text-neutral-700">+ screenpipe canNOT make mistakes. Consider checking important+ information.+ </p>+ </div>+ )}+ </div>+ </div>+ );+}++export function SpinnerMessage() {+ return (+ <div className="group relative flex items-start md:-ml-12">+ <div className="flex size-[24px] shrink-0 select-none items-center justify-center rounded-md border bg-primary text-primary-foreground shadow-sm">+ <IconOpenAI />+ </div>+ <div className="ml-4 h-[24px] flex flex-row items-center flex-1 space-y-2 overflow-hidden px-1">+ {spinner}+ </div>+ </div>+ );+}++// 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 (+ <svg+ {...props}+ xmlns="http://www.w3.org/2000/svg"+ width="24"+ height="24"+ viewBox="0 0 24 24"+ fill="none"+ stroke="currentColor"+ strokeWidth="2"+ strokeLinecap="round"+ strokeLinejoin="round"+ >+ <path d="m5 12 7-7 7 7" />+ <path d="M12 19V5" />+ </svg>+ );+}++function BotIcon(props) {+ return (+ <svg+ {...props}+ xmlns="http://www.w3.org/2000/svg"+ width="24"+ height="24"+ viewBox="0 0 24 24"+ fill="none"+ stroke="currentColor"+ strokeWidth="2"+ strokeLinecap="round"+ strokeLinejoin="round"+ >+ <path d="M12 8V4H8" />+ <rect width="16" height="12" x="4" y="8" rx="2" />+ <path d="M2 14h2" />+ <path d="M20 14h2" />+ <path d="M15 13v2" />+ <path d="M9 13v2" />+ </svg>+ );+}++function ChevronDownIcon(props) {+ return (+ <svg+ {...props}+ xmlns="http://www.w3.org/2000/svg"+ width="24"+ height="24"+ viewBox="0 0 24 24"+ fill="none"+ stroke="currentColor"+ strokeWidth="2"+ strokeLinecap="round"+ strokeLinejoin="round"+ >+ <path d="m6 9 6 6 6-6" />+ </svg>+ );+}++function ClipboardIcon(props) {+ return (+ <svg+ {...props}+ xmlns="http://www.w3.org/2000/svg"+ width="24"+ height="24"+ viewBox="0 0 24 24"+ fill="none"+ stroke="currentColor"+ strokeWidth="2"+ strokeLinecap="round"+ strokeLinejoin="round"+ >+ <rect width="8" height="4" x="8" y="2" rx="1" ry="1" />+ <path d="M16 4h2a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2h2" />+ </svg>+ );+}++function PenIcon(props) {+ return (+ <svg+ {...props}+ xmlns="http://www.w3.org/2000/svg"+ width="24"+ height="24"+ viewBox="0 0 24 24"+ fill="none"+ stroke="currentColor"+ strokeWidth="2"+ strokeLinecap="round"+ strokeLinejoin="round"+ >+ <path d="M17 3a2.85 2.83 0 1 1 4 4L7.5 20.5 2 22l1.5-5.5Z" />+ </svg>+ );+}++function RefreshCcwIcon(props) {+ return (+ <svg+ {...props}+ xmlns="http://www.w3.org/2000/svg"+ width="24"+ height="24"+ viewBox="0 0 24 24"+ fill="none"+ stroke="currentColor"+ strokeWidth="2"+ strokeLinecap="round"+ strokeLinejoin="round"+ >+ <path d="M21 12a9 9 0 0 0-9-9 9.75 9.75 0 0 0-6.74 2.74L3 8" />+ <path d="M3 3v5h5" />+ <path d="M3 12a9 9 0 0 0 9 9 9.75 9.75 0 0 0 6.74-2.74L21 16" />+ <path d="M16 16h5v5" />+ </svg>+ );+}++function SparkleIcon(props) {+ return (+ <svg+ {...props}+ xmlns="http://www.w3.org/2000/svg"+ width="24"+ height="24"+ viewBox="0 0 24 24"+ fill="none"+ stroke="currentColor"+ strokeWidth="2"+ strokeLinecap="round"+ strokeLinejoin="round"+ >+ <path d="M9.937 15.5A2 2 0 0 0 8.5 14.063l-6.135-1.582a.5.5 0 0 1 0-.962L8.5 9.936A2 2 0 0 0 9.937 8.5l1.582-6.135a.5.5 0 0 1 .963 0L14.063 8.5A2 2 0 0 0 15.5 9.937l6.135 1.581a.5.5 0 0 1 0 .964L15.5 14.063a2 2 0 0 0-1.437 1.437l-1.582 6.135a.5.5 0 0 1-.963 0z" />+ </svg>+ );+}++function ThumbsDownIcon(props) {+ return (+ <svg+ {...props}+ xmlns="http://www.w3.org/2000/svg"+ width="24"+ height="24"+ viewBox="0 0 24 24"+ fill="none"+ stroke="currentColor"+ strokeWidth="2"+ strokeLinecap="round"+ strokeLinejoin="round"+ >+ <path d="M17 14V2" />+ <path d="M9 18.12 10 14H4.17a2 2 0 0 1-1.92-2.56l2.33-8A2 2 0 0 1 6.5 2H20a2 2 0 0 1 2 2v8a2 2 0 0 1-2 2h-2.76a2 2 0 0 0-1.79 1.11L12 22h0a3.13 3.13 0 0 1-3-3.88Z" />+ </svg>+ );+}++function ThumbsUpIcon(props) {+ return (+ <svg+ {...props}+ xmlns="http://www.w3.org/2000/svg"+ width="24"+ height="24"+ viewBox="0 0 24 24"+ fill="none"+ stroke="currentColor"+ strokeWidth="2"+ strokeLinecap="round"+ strokeLinejoin="round"+ >+ <path d="M7 10v12" />+ <path d="M15 5.88 14 10h5.83a2 2 0 0 1 1.92 2.56l-2.33 8A2 2 0 0 1 17.5 22H4a2 2 0 0 1-2-2v-8a2 2 0 0 1 2-2h2.76a2 2 0 0 0 1.79-1.11L12 2h0a3.13 3.13 0 0 1 3 3.88Z" />+ </svg>+ );+}++function XIcon(props) {+ return (+ <svg+ {...props}+ xmlns="http://www.w3.org/2000/svg"+ width="24"+ height="24"+ viewBox="0 0 24 24"+ fill="none"+ stroke="currentColor"+ strokeWidth="2"+ strokeLinecap="round"+ strokeLinejoin="round"+ >+ <path d="M18 6 6 18" />+ <path d="m6 6 12 12" />+ </svg>+ );+}++function ZapIcon(props) {+ return (+ <svg+ {...props}+ xmlns="http://www.w3.org/2000/svg"+ width="24"+ height="24"+ viewBox="0 0 24 24"+ fill="none"+ stroke="currentColor"+ strokeWidth="2"+ strokeLinecap="round"+ strokeLinejoin="round"+ >+ <path d="M4 14a1 1 0 0 1-.78-1.63l9.9-10.2a.5.5 0 0 1 .86.46l-1.92 6.02A1 1 0 0 0 13 10h7a1 1 0 0 1 .78 1.63l-9.9 10.2a.5.5 0 0 1-.86-.46l1.92-6.02A1 1 0 0 0 11 14z" />+ </svg>+ );+}diff --git a/examples/apps/screenpipe-app-tauri/components/chat-message-v2.tsx b/examples/apps/screenpipe-app-tauri/components/chat-message-v2.tsxnew file mode 100644index 000000000..dd573404a--- /dev/null+++ b/examples/apps/screenpipe-app-tauri/components/chat-message-v2.tsx@@ -0,0 +1,84 @@+// Inspired by Chatbot-UI and modified to fit the needs of this project+// @see https://github.com/mckaywrigley/chatbot-ui/blob/main/components/Chat/ChatMessage.tsx++import { Message } from "ai";+import remarkGfm from "remark-gfm";+import remarkMath from "remark-math";++import { cn } from "@/lib/utils";+import { CodeBlock } from "@/components/ui/codeblock";+import { MemoizedReactMarkdown } from "@/components/markdown";+import { IconOpenAI, IconUser } from "@/components/ui/icons";+import { ChatMessageActions } from "@/components/chat-message-actions";++export interface ChatMessageProps {+ message: Message;+}++export function ChatMessage({ message, ...props }: ChatMessageProps) {+ return (+ <div+ className={cn("group relative mb-4 flex items-start md:-ml-12")}+ {...props}+ >+ <div+ className={cn(+ "flex size-8 shrink-0 select-none items-center justify-center rounded-md border shadow",+ message.role === "user"+ ? "bg-background"+ : "bg-primary text-primary-foreground"+ )}+ >+ {message.role === "user" ? <IconUser /> : <IconOpenAI />}+ </div>+ <div className="flex-1 px-1 ml-4 space-y-2 overflow-hidden">+ <MemoizedReactMarkdown+ className="prose break-words dark:prose-invert prose-p:leading-relaxed prose-pre:p-0"+ 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}+ />+ );+ },+ }}+ >+ {message.content}+ </MemoizedReactMarkdown>+ <ChatMessageActions message={message} />+ </div>+ </div>+ );+}diff --git a/examples/apps/screenpipe-app-tauri/components/chat-message.tsx b/examples/apps/screenpipe-app-tauri/components/chat-message.tsxindex 9aa2a90ae..bff39a3d3 100644--- a/examples/apps/screenpipe-app-tauri/components/chat-message.tsx+++ b/examples/apps/screenpipe-app-tauri/components/chat-message.tsx@@ -19,9 +19,10 @@ import { oneDark } from "react-syntax-highlighter/dist/esm/styles/prism";import { Badge } from "@/components/ui/badge";import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";+import { Message } from 'ai'export interface ChatMessageProps {- message: any;+ message: Message;}function FunctionCall({diff --git a/examples/apps/screenpipe-app-tauri/components/spinner.tsx b/examples/apps/screenpipe-app-tauri/components/spinner.tsxnew file mode 100644index 000000000..68e47ccbd--- /dev/null+++ b/examples/apps/screenpipe-app-tauri/components/spinner.tsx@@ -0,0 +1,16 @@+"use client";++export const spinner = (+ <svg+ fill="none"+ stroke="currentColor"+ strokeWidth="1.5"+ viewBox="0 0 24 24"+ strokeLinecap="round"+ strokeLinejoin="round"+ xmlns="http://www.w3.org/2000/svg"+ className="size-5 animate-spin stroke-zinc-400"+ >+ <path d="M12 3v3m6.366-.366-2.12 2.12M21 12h-3m.366 6.366-2.12-2.12M12 21v-3m-6.366.366 2.12-2.12M3 12h3m-.366-6.366 2.12 2.12"></path>+ </svg>+);diff --git a/examples/apps/screenpipe-app-tauri/lib/hooks/use-scroll-anchor.tsx b/examples/apps/screenpipe-app-tauri/lib/hooks/use-scroll-anchor.tsxnew file mode 100644index 000000000..3f968f8a0--- /dev/null+++ b/examples/apps/screenpipe-app-tauri/lib/hooks/use-scroll-anchor.tsx@@ -0,0 +1,87 @@+import { useCallback, useEffect, useRef, useState } from "react";++export const useScrollAnchor = () => {+ const messagesRef = useRef<HTMLDivElement>(null);+ const scrollRef = useRef<HTMLDivElement>(null);+ const visibilityRef = useRef<HTMLDivElement>(null);++ const [isAtBottom, setIsAtBottom] = useState(true);+ const [isVisible, setIsVisible] = useState(false);++ const scrollToBottom = useCallback(() => {+ if (messagesRef.current) {+ messagesRef.current.scrollIntoView({+ block: "end",+ behavior: "smooth",+ });+ }+ }, []);++ useEffect(() => {+ if (messagesRef.current) {+ if (isAtBottom && !isVisible) {+ messagesRef.current.scrollIntoView({+ block: "end",+ });+ }+ }+ }, [isAtBottom, isVisible]);++ useEffect(() => {+ const { current } = scrollRef;++ if (current) {+ const handleScroll = (event: Event) => {+ const target = event.target as HTMLDivElement;+ const offset = 25;+ const isAtBottom =+ target.scrollTop + target.clientHeight >=+ target.scrollHeight - offset;++ setIsAtBottom(isAtBottom);+ };++ current.addEventListener("scroll", handleScroll, {+ passive: true,+ });++ return () => {+ current.removeEventListener("scroll", handleScroll);+ };+ }+ }, []);++ useEffect(() => {+ if (visibilityRef.current) {+ let observer = new IntersectionObserver(+ (entries) => {+ entries.forEach((entry) => {+ if (entry.isIntersecting) {+ setIsVisible(true);+ } else {+ setIsVisible(false);+ }+ });+ },+ {+ rootMargin: "0px 0px -150px 0px",+ }+ );++ observer.observe(visibilityRef.current);++ return () => {+ observer.disconnect();+ };+ }+ });++ return {+ messagesRef,+ scrollRef,+ visibilityRef,+ scrollToBottom,+ isAtBottom,+ isVisible,+ };+};diff --git a/examples/apps/screenpipe-app-tauri/package.json b/examples/apps/screenpipe-app-tauri/package.jsonindex 2a444d22d..a9d24675d 100644--- a/examples/apps/screenpipe-app-tauri/package.json+++ b/examples/apps/screenpipe-app-tauri/package.json@@ -11,6 +11,7 @@"clean": "rm -rf out && cargo clean && rm -rf src-tauri/{screenpipe,tesseract,ffmpeg}"},"dependencies": {+ "@ai-sdk/openai": "^0.0.39","@mlc-ai/web-llm": "^0.2.51","@radix-ui/react-avatar": "^1.1.0","@radix-ui/react-dropdown-menu": "^2.1.1",@@ -21,6 +22,7 @@"@tauri-apps/plugin-shell": "2.0.0-beta.8","@tauri-apps/plugin-store": "2.0.0-beta.7","@tauri-apps/plugin-updater": "2.0.0-beta.7",+ "ai": "^3.2.35","class-variance-authority": "^0.7.0","clsx": "^2.1.1","lucide-react": "^0.414.0",diff --git a/examples/apps/screenpipe-app-tauri/src-tauri/src/main.rs b/examples/apps/screenpipe-app-tauri/src-tauri/src/main.rsindex 6ce14ebb9..bb25100f1 100755--- a/examples/apps/screenpipe-app-tauri/src-tauri/src/main.rs+++ b/examples/apps/screenpipe-app-tauri/src-tauri/src/main.rs@@ -159,7 +159,7 @@ use tokio::io::{AsyncBufReadExt, BufReader};use tokio::time::{interval, Duration};async fn start_server() -> anyhow::Result<()> {- let restart_interval = Duration::from_secs(20 * 60); // Restart every 20 minutes+ let restart_interval = Duration::from_secs(2 * 60); // Restart every 2 minutes ! HACKlet server_handle: Arc<tokio::sync::Mutex<Option<tokio::task::JoinHandle<()>>>> =Arc::new(tokio::sync::Mutex::new(None));let server_handle_clone = Arc::clone(&server_handle);diff --git a/screenpipe-core/Cargo.toml b/screenpipe-core/Cargo.tomlindex b0b9c7aa5..0a741d731 100644--- a/screenpipe-core/Cargo.toml+++ b/screenpipe-core/Cargo.toml@@ -8,6 +8,17 @@ license = { workspace = true }edition = { workspace = true }[dependencies]+serde = { version = "1.0", features = ["derive"] }+serde_json = "1.0"which = "6.0.1"log = "0.4.17"+anyhow = "1.0.86"+candle = { workspace = true }+candle-nn = { workspace = true }+candle-transformers = { workspace = true }+tokenizers = { workspace = true }+hf-hub = { workspace = true, features = ["tokio"] }+++diff --git a/screenpipe-core/src/lib.rs b/screenpipe-core/src/lib.rsindex 8fc20b869..33b85c25e 100644--- a/screenpipe-core/src/lib.rs+++ b/screenpipe-core/src/lib.rs@@ -1,2 +1,4 @@pub mod ffmpeg;pub use ffmpeg::find_ffmpeg_path;+pub mod llm;+pub use llm::*;diff --git a/examples/apps/screenpipe-app-tauri/src-tauri/src/llm.rs b/screenpipe-core/src/llm-llama.rssimilarity index 51%rename from examples/apps/screenpipe-app-tauri/src-tauri/src/llm.rsrename to screenpipe-core/src/llm-llama.rsindex fb40b310f..5bea5d600 100755--- a/examples/apps/screenpipe-app-tauri/src-tauri/src/llm.rs+++ b/screenpipe-core/src/llm-llama.rs@@ -1,10 +1,37 @@-use anyhow::{bail, Result};+use anyhow::Result;use candle::{DType, Device, Tensor};use candle_nn::VarBuilder;use candle_transformers::models::llama::{Cache, Llama, LlamaConfig};use hf_hub::{api::sync::Api, Repo, RepoType};use tokenizers::Tokenizer;+/// Loads the safetensors files for a model from the hub based on a json index file.+pub fn hub_load_safetensors(+ repo: &hf_hub::api::sync::ApiRepo,+ json_file: &str,+) -> Result<Vec<std::path::PathBuf>> {+ let json_file = repo.get(json_file).map_err(candle::Error::wrap)?;+ let json_file = std::fs::File::open(json_file)?;+ let json: serde_json::Value =+ serde_json::from_reader(&json_file).map_err(candle::Error::wrap)?;+ let weight_map = match json.get("weight_map") {+ None => anyhow::bail!("no weight map in {json_file:?}"),+ Some(serde_json::Value::Object(map)) => map,+ Some(_) => anyhow::bail!("weight map in {json_file:?} is not a map"),+ };+ let mut safetensors_files = std::collections::HashSet::new();+ for value in weight_map.values() {+ if let Some(file) = value.as_str() {+ safetensors_files.insert(file.to_string());+ }+ }+ let safetensors_files = safetensors_files+ .iter()+ .map(|v| repo.get(v).map_err(anyhow::Error::from))+ .collect::<Result<Vec<_>, anyhow::Error>>()?;+ Ok(safetensors_files)+}+pub fn load_llama_model(device: &Device) -> Result<(Llama, Tokenizer, Cache)> {let api = Api::new()?;let model_id = "meta-llama/Meta-Llama-3-8B-Instruct";@@ -24,7 +51,7 @@ pub fn load_llama_model(device: &Device) -> Result<(Llama, Tokenizer, Cache)> {let dtype = DType::BF16; // You can change this to F16 if preferredlet cache = Cache::new(true, dtype, &config, device)?;- let filenames = candle_examples::hub_load_safetensors(&api, "model.safetensors.index.json")?;+ let filenames = hub_load_safetensors(&api, "model.safetensors.index.json")?;let vb = unsafe { VarBuilder::from_mmaped_safetensors(&filenames, dtype, device)? };let model = Llama::load(vb, &config)?;@@ -33,23 +60,6 @@ pub fn load_llama_model(device: &Device) -> Result<(Llama, Tokenizer, Cache)> {Ok((model, tokenizer, cache))}-pub fn generate_text(- model: &Llama,- tokenizer: &Tokenizer,- cache: &mut Cache,- prompt: &str,- max_tokens: usize,- temperature: f64,- device: &Device,-) -> Result<String> {- // Implement text generation logic here- // This would include tokenization, forward passes, and token sampling- // You can refer to the main() function in the GitHub example for details-- // Placeholder return- Ok("Generated text placeholder".to_string())-}-pub fn generate_text_streaming<F>(model: &Llama,tokenizer: &Tokenizer,@@ -58,43 +68,45 @@ pub fn generate_text_streaming<F>(max_tokens: usize,temperature: f64,device: &Device,- callback: F,+ mut callback: F,) -> Result<()>whereF: FnMut(String) -> Result<()>,{- let mut rng = rand::rngs::StdRng::seed_from_u64(299792458);let mut logits_processor =- candle_transformers::generation::LogitsProcessor::new(299792458, temperature, None);+ candle_transformers::generation::LogitsProcessor::new(42, Some(temperature), None);let mut tokens = tokenizer.encode(prompt, true).map_err(anyhow::Error::msg)?;let mut generated_tokens = 0;- let mut callback = callback;let eos_token = tokenizer.token_to_id("</s>");let bos_token = tokenizer.token_to_id("<s>");- if let Some(bos_token) = bos_token {- tokens.insert(0, bos_token);- }-- let mut all_tokens = tokens.clone();-+ let mut all_tokens = if let Some(bos_token) = bos_token {+ std::iter::once(bos_token)+ .chain(tokens.get_ids().iter().cloned())+ .collect::<Vec<_>>()+ } else {+ tokens.get_ids().to_vec()+ };for index in 0..max_tokens {- let context_size = if index > 0 { 1 } else { tokens.len() };- let start_pos = tokens.len().saturating_sub(context_size);- let input = Tensor::new(&tokens[start_pos..], device)?;+ let context_size = if index > 0 { 1 } else { tokens.get_ids().len() };+ let start_pos = tokens.get_ids().len().saturating_sub(context_size);+ let input = Tensor::new(&tokens.get_ids()[start_pos..], device)?;let logits = model.forward(&input, start_pos, cache)?;let logits = logits.squeeze(0)?;let logits = if temperature == 0. {logits} else {- logits.div(temperature)?+ let temp_tensor = Tensor::new(&[temperature], device)?;+ logits.div(&temp_tensor)?};-let next_token = logits_processor.sample(&logits)?;- tokens.push(next_token);+ let text = tokenizer+ .decode(&[next_token], false)+ .map_err(anyhow::Error::msg)?;+ tokens = tokenizer.encode(text, true).map_err(anyhow::Error::msg)?;all_tokens.push(next_token);if let Some(eos_token) = eos_token {@@ -103,39 +115,13 @@ where}}- if let Some(text) = tokenizer+ let text = tokenizer.decode(&[next_token], true)- .map_err(anyhow::Error::msg)?- {- callback(text)?;- }+ .map_err(anyhow::Error::msg)?;+ callback(text)?;generated_tokens += 1;}Ok(())}--fn main() {- let device = Device::new_metal(0).unwrap_or(Device::new_cuda(0).unwrap_or(Device::Cpu));- let (model, tokenizer, cache) = load_llama_model(&device).unwrap();- let prompt = "Hello, world!";- let max_tokens = 10;- let temperature = 0.1;- let callback = |text| {- println!("Generated text: {}", text);- Ok(())- };- // streaming- generate_text_streaming(- &model,- &tokenizer,- &mut cache,- &prompt,- max_tokens,- temperature,- &device,- callback,- )- .unwrap();-}diff --git a/screenpipe-core/src/llm.rs b/screenpipe-core/src/llm.rsnew file mode 100755index 000000000..1d2d9049b--- /dev/null+++ b/screenpipe-core/src/llm.rs@@ -0,0 +1,128 @@+use anyhow::Result;+use candle::{DType, Device, Tensor};+use candle_nn::VarBuilder;+use candle_transformers::models::llama::{Cache, Llama, LlamaConfig};+use candle_transformers::models::phi3::{Config as Phi3Config, Model as Phi3};++use hf_hub::{api::sync::Api, Repo, RepoType};+use tokenizers::Tokenizer;++/// Loads the safetensors files for a model from the hub based on a json index file.+pub fn hub_load_safetensors(+ repo: &hf_hub::api::sync::ApiRepo,+ json_file: &str,+) -> Result<Vec<std::path::PathBuf>> {+ let json_file = repo.get(json_file).map_err(candle::Error::wrap)?;+ let json_file = std::fs::File::open(json_file)?;+ let json: serde_json::Value =+ serde_json::from_reader(&json_file).map_err(candle::Error::wrap)?;+ let weight_map = match json.get("weight_map") {+ None => anyhow::bail!("no weight map in {json_file:?}"),+ Some(serde_json::Value::Object(map)) => map,+ Some(_) => anyhow::bail!("weight map in {json_file:?} is not a map"),+ };+ let mut safetensors_files = std::collections::HashSet::new();+ for value in weight_map.values() {+ if let Some(file) = value.as_str() {+ safetensors_files.insert(file.to_string());+ }+ }+ let safetensors_files = safetensors_files+ .iter()+ .map(|v| repo.get(v).map_err(anyhow::Error::from))+ .collect::<Result<Vec<_>, anyhow::Error>>()?;+ Ok(safetensors_files)+}++pub fn load_llama_model(device: &Device) -> Result<(Phi3, Tokenizer)> {+ let api = Api::new()?;+ let model_id = "microsoft/Phi-3-mini-4k-instruct";+ let revision = "main";++ let api = api.repo(Repo::with_revision(+ model_id.to_string(),+ RepoType::Model,+ revision.to_string(),+ ));+ let tokenizer_filename = api.get("tokenizer.json")?;+ let config_filename = api.get("config.json")?;++ let config: Phi3Config = serde_json::from_slice(&std::fs::read(config_filename)?)?;++ // https://github.com/huggingface/candle/blob/ddafc61055601002622778b7762c15bd60057c1f/candle-examples/examples/phi/main.rs#L364+ // let dtype = DType::BF16;+ let dtype = DType::F32;++ let filenames = hub_load_safetensors(&api, "model.safetensors.index.json")?;+ let vb = unsafe { VarBuilder::from_mmaped_safetensors(&filenames, dtype, device)? };++ let model = Phi3::new(&config, vb)?;+ let tokenizer = Tokenizer::from_file(tokenizer_filename).map_err(anyhow::Error::msg)?;++ Ok((model, tokenizer))+}++pub fn generate_text_streaming<F>(+ model: &mut Phi3,+ tokenizer: &Tokenizer,+ prompt: &str,+ max_tokens: usize,+ temperature: f64,+ device: &Device,+ mut callback: F,+) -> Result<()>+where+ F: FnMut(String) -> Result<()>,+{+ let mut logits_processor =+ candle_transformers::generation::LogitsProcessor::new(42, Some(temperature), None);++ let mut tokens = tokenizer.encode(prompt, true).map_err(anyhow::Error::msg)?;+ let mut generated_tokens = 0;++ let eos_token = tokenizer.token_to_id("</s>");+ let bos_token = tokenizer.token_to_id("<s>");++ let mut all_tokens = if let Some(bos_token) = bos_token {+ std::iter::once(bos_token)+ .chain(tokens.get_ids().iter().cloned())+ .collect::<Vec<_>>()+ } else {+ tokens.get_ids().to_vec()+ };+ for index in 0..max_tokens {+ let context_size = if index > 0 { 1 } else { tokens.get_ids().len() };+ let start_pos = tokens.get_ids().len().saturating_sub(context_size);+ let input = Tensor::new(&tokens.get_ids()[start_pos..], device)?.unsqueeze(0)?; // Add a batch dimension++ let logits = model.forward(&input, start_pos)?;+ let logits = logits.squeeze(0)?.to_dtype(DType::F32)?;+ let logits = if temperature == 0. {+ logits+ } else {+ let temp_tensor = Tensor::new(&[temperature], device)?;+ logits.div(&temp_tensor)?+ };+ let next_token = logits_processor.sample(&logits)?;+ let text = tokenizer+ .decode(&[next_token], false)+ .map_err(anyhow::Error::msg)?;+ tokens = tokenizer.encode(text, true).map_err(anyhow::Error::msg)?;+ all_tokens.push(next_token);++ if let Some(eos_token) = eos_token {+ if next_token == eos_token {+ break;+ }+ }++ let text = tokenizer+ .decode(&[next_token], true)+ .map_err(anyhow::Error::msg)?;+ callback(text)?;++ generated_tokens += 1;+ }++ Ok(())+}diff --git a/screenpipe-core/tests/llm_test.rs b/screenpipe-core/tests/llm_test.rsnew file mode 100644index 000000000..857a2fa24--- /dev/null+++ b/screenpipe-core/tests/llm_test.rs@@ -0,0 +1,39 @@+#[cfg(test)]+mod tests {+ use anyhow::Result;+ use candle::Device;+ use screenpipe_core::{generate_text_streaming, load_llama_model};+ #[test]+ #[ignore]+ fn test_generate_text_streaming() -> Result<()> {+ let device = Device::new_metal(0).unwrap_or(Device::new_cuda(0).unwrap_or(Device::Cpu));++ let (mut model, tokenizer) = load_llama_model(&device)?;++ let prompt = "Hello, world!";+ let max_tokens = 5;+ let temperature = 0.7;++ let mut generated_text = String::new();+ let callback = |text: String| {+ generated_text.push_str(&text);+ println!("{}", text);+ Ok(())+ };++ generate_text_streaming(+ &mut model,+ &tokenizer,+ prompt,+ max_tokens,+ temperature,+ &device,+ callback,+ )?;++ assert!(!generated_text.is_empty());+ assert!(generated_text.len() > prompt.len());++ Ok(())+ }+}diff --git a/screenpipe-server/src/core.rs b/screenpipe-server/src/core.rsindex 332714419..b727e0d48 100644--- a/screenpipe-server/src/core.rs+++ b/screenpipe-server/src/core.rs@@ -137,7 +137,7 @@ async fn record_video(let video_capture = VideoCapture::new(&output_path, fps, new_chunk_callback, save_text_files);while is_running.load(Ordering::SeqCst) {- // let queue_length = video_capture.ocr_frame_queue.lock().await.len();+ // let queue_lenglth = video_capture.ocr_frame_queue.lock().await.len();// debug!("record_video: Checking for latest frame. Number of frames in OCR queue: {}", queue_length);if let Some(frame) = video_capture.ocr_frame_queue.lock().await.pop_front() {match db.insert_frame().await {diff --git a/screenpipe-server/src/server.rs b/screenpipe-server/src/server.rsindex c5fcf0872..0a2d958dc 100644--- a/screenpipe-server/src/server.rs+++ b/screenpipe-server/src/server.rs@@ -533,7 +533,7 @@ curl "http://localhost:3030/search?q=libmp3&limit=5&offset=0&content_type=all" |# Search for content from the last 30 minutes-curl "http://localhost:3035/search?q=test&limit=5&offset=0&content_type=all&start_time=$(date -u -v-5M +%Y-%m-%dT%H:%M:%SZ)" | jq+curl "http://localhost:3030/search?limit=5&offset=0&content_type=all&start_time=$(date -u -v-5M +%Y-%m-%dT%H:%M:%SZ)" | jq# Search for content up to 1 hour agocurl "http://localhost:3030/search?q=test&limit=5&offset=0&content_type=all&end_time=$(date -u -v-1H +%Y-%m-%dT%H:%M:%SZ)" | jq