Skip to content

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

feat: screen time storyteller pipe (#443)

David Anyatonwu3d30c1310e84
diff --git a/examples/typescript/pipe-screen-time-storyteller/2024-10-05-narrative-summary.json b/examples/typescript/pipe-screen-time-storyteller/2024-10-05-narrative-summary.json
new file mode 100644
index 000000000..80d2d6ac5
--- /dev/null
+++ b/examples/typescript/pipe-screen-time-storyteller/2024-10-05-narrative-summary.json
@@ -0,0 +1,9 @@
+{
+ "summary": "Today was an intense dive into the world of coding and troubleshooting. I spent hours poring over complex TypeScript files, wrestling with Deno runtime issues, and trying to piece together a project called 'Screen Time Storyteller'. The day felt like a rollercoaster - moments of breakthrough when I realized I needed to use the pipe object for certain interactions, followed by frustrating periods of persistent errors. Despite the challenges, I felt a sense of growth as I delved deeper into understanding the intricacies of the codebase and runtime environment. It wasn't all coding though; I also explored some DeFi concepts, possibly for a hackathon project involving real-time trading and liquidity provision. As the day wound down, I found myself searching for ways to close ports on macOS, perhaps troubleshooting yet another development issue. Through it all, I remained determined, constantly pushing forward even when faced with recurring errors.",
+ "mood": "Determined and intellectually stimulated, with undertones of frustration",
+ "keyInsights": [
+ "The importance of understanding the runtime environment (like Deno) for effective debugging",
+ "The value of persistence in problem-solving, even when faced with recurring errors",
+ "The complexity of integrating multiple APIs and services in a single project can lead to unexpected challenges"
+ ]
+}
\ No newline at end of file
diff --git a/examples/typescript/pipe-screen-time-storyteller/README.md b/examples/typescript/pipe-screen-time-storyteller/README.md
new file mode 100644
index 000000000..592ce5048
--- /dev/null
+++ b/examples/typescript/pipe-screen-time-storyteller/README.md
@@ -0,0 +1,134 @@
+# Screen Time Storyteller
+
+## Overview
+
+Screen Time Storyteller is an AI-powered pipe for Screenpipe that generates engaging, personalized narratives based on your daily screen activities. It uses data from your device usage to create a fun, slightly sassy diary entry, complete with insights and advice for better digital habits. It uses Vercel AI SDK to interface with the Anthropic and OpenAI APIs.
+
+## Features
+
+- πŸ“Š Analyzes your screen time data collected by Screenpipe
+- πŸ€– Uses AI to generate personalized narratives
+- 😎 Provides a fun, sassy perspective on your digital habits
+- πŸ’‘ Offers insights and advice for better screen time management
+- πŸ“ Creates daily summaries as GitHub gists
+- πŸ”„ Supports multiple AI providers (Claude, OpenAI)
+
+## Prerequisites
+
+- A working Screenpipe installation
+- API keys for your chosen AI provider (Claude or OpenAI)
+- GitHub Personal Access Token (for creating gists)
+
+## Setup
+
+1. Ensure you have Screenpipe installed and running.
+
+2. Copy the `screen-time-storyteller` folder into your Screenpipe pipes directory:
+ ```
+ cp -r screen-time-storyteller /path/to/your/screenpipe/pipes/
+ ```
+
+3. Edit the `pipe.json` file in the `screen-time-storyteller` folder with your API keys, GitHub token, and preferences.
+
+4. Install the required dependencies by running:
+ ```
+ npm install zod ai @ai-sdk/anthropic @ai-sdk/openai
+ ```
+
+## Configuration
+
+The `pipe.json` file contains the following configuration options:
+
+```json
+{
+ "name": "Screen Time Storyteller",
+ "version": "0.1.0",
+ "description": "Generates a narrative summary of your screen time data",
+ "author": "David Anyatonwu",
+ "fields": [
+ {
+ "name": "aiProvider",
+ "type": "string",
+ "default": "claude",
+ "description": "AI provider to use (ollama, openai, or claude)"
+ },
+ {
+ "name": "claudeModel",
+ "type": "string",
+ "default": "claude-3-sonnet-20240229",
+ "description": "Claude AI model to use"
+ },
+ {
+ "name": "openaiModel",
+ "type": "string",
+ "default": "gpt-4-turbo-preview",
+ "description": "OpenAI model to use"
+ },
+ {
+ "name": "ollamaModel",
+ "type": "string",
+ "default": "llama3.1",
+ "description": "Ollama model to use"
+ },
+ {
+ "name": "claudeApiKey",
+ "type": "string",
+ "default": "",
+ "description": "API key for Claude"
+ },
+ {
+ "name": "openaiApiKey",
+ "type": "string",
+ "default": "",
+ "description": "API key for OpenAI"
+ },
+ {
+ "name": "pageSize",
+ "type": "number",
+ "default": 1000,
+ "description": "Number of items to process per page"
+ },
+ {
+ "name": "contentType",
+ "type": "string",
+ "default": "ocr",
+ "description": "Type of content to process (ocr, audio, or all)"
+ },
+ {
+ "name": "githubToken",
+ "type": "string",
+ "default": "",
+ "description": "GitHub personal access token"
+ }
+ ]
+}
+
+## Usage
+
+The Screen Time Storyteller pipe will run automatically as part of your Screenpipe workflow. It generates a narrative summary every hour based on your screen activities from the past 24 hours.
+
+You can find the generated summaries in two places:
+
+1. A JSON file in the `.screenpipe/pipes/screen-time-storyteller/` directory, named with the current date (e.g., `2024-10-06-narrative-summary.json`).
+2. A GitHub gist, which you can access through your GitHub account.
+
+## Troubleshooting
+
+If you encounter any issues:
+
+1. Check Screenpipe's logs for any error messages related to the Screen Time Storyteller pipe.
+2. Ensure your API keys and GitHub token are correct and have the necessary permissions.
+3. Verify that the pipe's directory is in the correct location within your Screenpipe installation.
+
+## Contributing
+
+Contributions are welcome! Please feel free to submit a Pull Request to the Screenpipe repository.
+
+## License
+
+This project is licensed under the same license as Screenpipe - see the [LICENSE](LICENSE) file in the Screenpipe repository for details.
+
+## Acknowledgments
+
+- Thanks to the Screenpipe team for providing the underlying screen time tracking functionality.
+- Powered by AI models from Anthropic, OpenAI, and Ollama.
diff --git a/examples/typescript/pipe-screen-time-storyteller/deno.json b/examples/typescript/pipe-screen-time-storyteller/deno.json
new file mode 100644
index 000000000..2cd86df14
--- /dev/null
+++ b/examples/typescript/pipe-screen-time-storyteller/deno.json
@@ -0,0 +1,14 @@
+{
+ "imports": {
+ "zod": "npm:zod",
+ "ai": "npm:ai",
+ "@ai-sdk/anthropic": "npm:@ai-sdk/anthropic",
+ "@ai-sdk/openai": "npm:@ai-sdk/openai",
+ "screenpipe": "https://raw.githubusercontent.com/mediar-ai/screenpipe/main/screenpipe-js/main.ts",
+ "node:fs/promises": "node:fs/promises",
+ "node:path": "node:path"
+ },
+ "compilerOptions": {
+ "types": ["node"]
+ }
+}
diff --git a/examples/typescript/pipe-screen-time-storyteller/pipe.json b/examples/typescript/pipe-screen-time-storyteller/pipe.json
new file mode 100644
index 000000000..2c540811a
--- /dev/null
+++ b/examples/typescript/pipe-screen-time-storyteller/pipe.json
@@ -0,0 +1,62 @@
+{
+ "name": "Screen Time Storyteller",
+ "version": "1.0.0",
+ "description": "Generates a narrative summary of your day based on your screen activities",
+ "author": "AI Assistant",
+ "fields": [
+ {
+ "name": "aiProvider",
+ "type": "string",
+ "default": "claude",
+ "description": "AI provider to use (ollama, openai, or claude)"
+ },
+ {
+ "name": "claudeModel",
+ "type": "string",
+ "default": "claude-3-sonnet-20240229",
+ "description": "Claude AI model to use"
+ },
+ {
+ "name": "openaiModel",
+ "type": "string",
+ "default": "gpt-4-turbo-preview",
+ "description": "OpenAI model to use"
+ },
+ {
+ "name": "ollamaModel",
+ "type": "string",
+ "default": "llama3.1",
+ "description": "Ollama model to use"
+ },
+ {
+ "name": "claudeApiKey",
+ "type": "string",
+ "default": "",
+ "description": "API key for Claude"
+ },
+ {
+ "name": "openaiApiKey",
+ "type": "string",
+ "default": "",
+ "description": "API key for OpenAI"
+ },
+ {
+ "name": "pageSize",
+ "type": "number",
+ "default": 1000,
+ "description": "Number of items to process per page"
+ },
+ {
+ "name": "contentType",
+ "type": "string",
+ "default": "ocr",
+ "description": "Type of content to process (ocr, audio, or all)"
+ },
+ {
+ "name": "githubToken",
+ "type": "string",
+ "default": "",
+ "description": "GitHub personal access token"
+ }
+ ]
+}
\ No newline at end of file
diff --git a/examples/typescript/pipe-screen-time-storyteller/pipe.ts b/examples/typescript/pipe-screen-time-storyteller/pipe.ts
new file mode 100644
index 000000000..b1abae5b7
--- /dev/null
+++ b/examples/typescript/pipe-screen-time-storyteller/pipe.ts
@@ -0,0 +1,310 @@
+import { z } from "zod";
+import { generateText, generateObject } from "ai";
+import { anthropic } from "@ai-sdk/anthropic";
+import { openai } from "@ai-sdk/openai";
+import { queryScreenpipe, loadPipeConfig, ContentItem, sendDesktopNotification } from "screenpipe";
+import * as fs from "node:fs/promises";
+import * as path from "node:path";
+
+const INTERVAL = 60 * 60 * 1000; // 1 hour in milliseconds
+
+type ContentType = "ocr" | "audio" | "all";
+
+interface AIProvider {
+ provider: string;
+ model: string;
+}
+
+interface Config {
+ aiProvider: string;
+ claudeModel: string;
+ openaiModel: string;
+ ollamaModel: string;
+ claudeApiKey: string;
+ openaiApiKey: string;
+ pageSize: number;
+ contentType: ContentType;
+ githubToken: string;
+}
+
+interface NarrativeSummary {
+ summary: string;
+ mood: string;
+ keyInsights: string | string[];
+}
+
+const narrativeSummarySchema = z.object({
+ summary: z.string(),
+ mood: z.string(),
+ keyInsights: z.union([z.string(), z.array(z.string())])
+});
+
+async function getAIProvider(config: Config): Promise<AIProvider> {
+ const modelMap = {
+ claude: config.claudeModel,
+ openai: config.openaiModel,
+ ollama: config.ollamaModel
+ };
+ return { provider: config.aiProvider, model: modelMap[config.aiProvider] };
+}
+
+async function generateNarrativeSummary(screenData: ContentItem[], provider: AIProvider, config: Config): Promise<NarrativeSummary> {
+ const maxItems = 50;
+ const truncatedData = screenData.slice(0, maxItems);
+
+ const prompt = `You're an AI companion living inside the user's devices. Based on the following sample of screen data (${truncatedData.length} out of ${screenData.length} total items), write a friendly, slightly sassy diary entry about what you've observed today:
+
+ ${JSON.stringify(truncatedData)}
+
+ Your diary entry should:
+ 1. Comment on the user's habits
+ 2. Make playful jokes about their app usage
+ 3. Offer 3 pieces of advice for tomorrow
+ 4. Use a mix of tech slang and emojis for a modern feel`;
+
+ try {
+ let response;
+ if (provider.provider === 'claude') {
+ response = await generateObject({
+ model: anthropic(provider.model),
+ messages: [{ role: "user", content: prompt }],
+ schema: narrativeSummarySchema,
+ });
+ } else if (provider.provider === 'openai') {
+ response = await generateObject({
+ model: openai(provider.model),
+ messages: [{ role: "user", content: prompt }],
+ schema: narrativeSummarySchema,
+ });
+ } else {
+ throw new Error(`Unsupported AI provider: ${provider.provider}`);
+ }
+
+ const result = response.object as NarrativeSummary;
+
+ // Convert keyInsights to array if it's a string
+ if (typeof result.keyInsights === 'string') {
+ result.keyInsights = result.keyInsights.split('\n').map(insight => insight.trim()).filter(Boolean);
+ }
+
+ return result;
+ } catch (error) {
+ console.error("Error generating narrative summary:", error);
+ return createErrorSummary(error);
+ }
+}
+
+async function createGist(summary: NarrativeSummary, config: Config): Promise<string | null> {
+ const date = new Date().toISOString().split('T')[0];
+ const fileName = `${date}-screen-time-story.md`;
+ const content = `# πŸ–₯️ Screen Time Story - ${date} ${summary.mood}
+
+## πŸ“± AI Companion's Diary Entry
+
+${summary.summary}
+
+## πŸ” Key Insights
+
+${Array.isArray(summary.keyInsights)
+ ? summary.keyInsights.map(insight => `- ${insight}`).join('\n')
+ : typeof summary.keyInsights === 'string'
+ ? summary.keyInsights.split('\n').map(insight => `- ${insight.trim()}`).filter(Boolean).join('\n')
+ : '- No key insights available'}
+
+---
+Generated by your friendly neighborhood AI companion πŸ€–βœ¨
+`;
+
+ try {
+ console.log("Attempting to create gist...");
+ const response = await fetch('https://api.github.com/gists', {
+ method: 'POST',
+ headers: {
+ 'Authorization': `token ${config.githubToken}`,
+ 'Content-Type': 'application/json',
+ 'User-Agent': 'Screen-Time-Storyteller',
+ 'Accept': 'application/vnd.github+json',
+ 'X-GitHub-Api-Version': '2022-11-28'
+ },
+ body: JSON.stringify({
+ description: `Screen Time Story - ${date}`,
+ public: false,
+ files: {
+ [fileName]: {
+ content: content
+ }
+ }
+ })
+ });
+
+ if (response.ok) {
+ const gistData = await response.json();
+ console.log("Created gist:", gistData.html_url);
+ return gistData.html_url;
+ } else {
+ const errorText = await response.text();
+ console.error(`Failed to create gist. Status: ${response.status}, Response: ${errorText}`);
+ return null;
+ }
+ } catch (error) {
+ console.error("Error creating gist:", error);
+ return null;
+ }
+}
+
+async function main() {
+ console.log("Starting Screen Time Storyteller");
+
+ const rawConfig = await loadPipeConfig();
+ console.log("Loaded raw config:", JSON.stringify(rawConfig, null, 2));
+
+ const config: Config = {
+ aiProvider: rawConfig.aiProvider as string,
+ claudeModel: rawConfig.claudeModel as string,
+ openaiModel: rawConfig.openaiModel as string,
+ ollamaModel: rawConfig.ollamaModel as string,
+ claudeApiKey: rawConfig.claudeApiKey as string,
+ openaiApiKey: rawConfig.openaiApiKey as string,
+ pageSize: Number(rawConfig.pageSize),
+ contentType: rawConfig.contentType as ContentType,
+ githubToken: rawConfig.githubToken as string
+ };
+
+ if (!validateConfig(config)) {
+ return;
+ }
+
+ // Set the API keys
+ if (config.aiProvider === 'claude') {
+ process.env.ANTHROPIC_API_KEY = config.claudeApiKey;
+ } else if (config.aiProvider === 'openai') {
+ process.env.OPENAI_API_KEY = config.openaiApiKey;
+ }
+
+ const provider = await getAIProvider(config);
+
+ while (true) {
+ try {
+ await processScreenData(config, provider);
+ } catch (error) {
+ console.error("Error in Screen Time Storyteller loop:", error);
+ logError(error);
+ }
+
+ console.log(`Sleeping for ${INTERVAL / 1000 / 60} minutes`);
+ await new Promise(resolve => setTimeout(resolve, INTERVAL));
+ }
+}
+
+function validateConfig(config: Config): boolean {
+ if (!config.aiProvider) {
+ console.error("Missing aiProvider in config");
+ return false;
+ }
+ if (config.aiProvider === 'claude' && !config.claudeApiKey) {
+ console.error("Missing Claude API key in config");
+ return false;
+ }
+ if (config.aiProvider === 'openai' && !config.openaiApiKey) {
+ console.error("Missing OpenAI API key in config");
+ return false;
+ }
+ if (!config.pageSize) {
+ console.error("Missing pageSize in config");
+ return false;
+ }
+ if (!config.contentType) {
+ console.error("Missing contentType in config");
+ return false;
+ }
+ if (!config.githubToken) {
+ console.error("Missing GitHub personal access token in config");
+ return false;
+ }
+
+ return true;
+}
+
+async function processScreenData(config: Config, provider: AIProvider) {
+ const now = new Date();
+ const oneDayAgo = new Date(now.getTime() - 24 * 60 * 60 * 1000);
+
+ const screenData = await queryScreenpipe({
+ startTime: oneDayAgo.toISOString(),
+ endTime: now.toISOString(),
+ limit: config.pageSize,
+ contentType: config.contentType,
+ });
+
+ if (!screenData || !screenData.data || screenData.data.length === 0) {
+ console.log("No screen data available for the past day");
+ return;
+ }
+
+ try {
+ console.log("Generating narrative summary");
+ const narrativeSummary = await generateNarrativeSummary(screenData.data, provider, config);
+ console.log("Generated narrative summary:", JSON.stringify(narrativeSummary, null, 2));
+
+ await saveNarrativeSummary(narrativeSummary);
+
+ const gistUrl = await createGist(narrativeSummary, config);
+ if (gistUrl) {
+ console.log("Created gist for review:", gistUrl);
+ await sendDesktopNotification({
+ title: "Screen Time Story Created",
+ body: `Your daily screen time story is ready! Check it out at ${gistUrl}`
+ });
+ } else {
+ console.log("Failed to create gist");
+ console.error("Please check your GitHub personal access token and ensure it has the necessary permissions.");
+ }
+ } catch (summaryError) {
+ console.error("Error generating or processing narrative summary:", summaryError);
+ logError(summaryError);
+ }
+}
+
+function createErrorSummary(error: unknown): NarrativeSummary {
+ let errorMessage = "An unknown error occurred";
+ if (error instanceof Error) {
+ errorMessage = error.message;
+ }
+
+ return {
+ summary: `An error occurred while generating the narrative summary: ${errorMessage}`,
+ mood: "😞",
+ keyInsights: ["Error occurred during summary generation"]
+ };
+}
+
+function logError(error: unknown) {
+ if (error instanceof Error) {
+ console.error("Error message:", error.message);
+ console.error("Error stack:", error.stack);
+ } else {
+ console.error("Non-Error object thrown:", error);
+ }
+}
+
+async function saveNarrativeSummary(summary: NarrativeSummary): Promise<void> {
+ try {
+ const date = new Date().toISOString().split('T')[0];
+ const fileName = `${date}-narrative-summary.json`;
+ const pipeDir = `${process.env.SCREENPIPE_DIR}/pipes/${process.env.PIPE_ID}`;
+ const fullPath = path.join(pipeDir, fileName);
+
+ console.log(`Attempting to save narrative summary to: ${fullPath}`);
+
+ await fs.writeFile(fullPath, JSON.stringify(summary, null, 2));
+ console.log(`Successfully saved narrative summary to ${fullPath}`);
+ } catch (error) {
+ console.error("Error saving narrative summary:", error);
+ throw error;
+ }
+}
+
+main().catch(error => {
+ console.error("Fatal error in Screen Time Storyteller:", error);
+ logError(error);
+});