### Install and Start Srcbook with npm Source: https://github.com/srcbookdev/srcbook/blob/main/README.md Use npx to run the latest version of Srcbook and start the server. This is the recommended installation method. ```bash npx srcbook@latest start ``` -------------------------------- ### Install and Start Srcbook with pnpm Source: https://github.com/srcbookdev/srcbook/blob/main/README.md Use pnpm dlx to run the latest version of Srcbook and start the server. ```bash pnpm dlx srcbook@latest start ``` -------------------------------- ### Srcbook CLI Help Source: https://github.com/srcbookdev/srcbook/blob/main/README.md Display the usage and available commands for the Srcbook CLI. This includes options for starting the server, importing notebooks, and getting help. ```bash $srcbook -h Usage: srcbook [options] [command] Srcbook is a interactive programming environment for TypeScript Options: -V, --version output the version number -h, --help display help for command Commands: start [options] Start the Srcbook server import [options] Import a notebook help [command] display help for command ``` -------------------------------- ### Install Dependencies Source: https://github.com/srcbookdev/srcbook/blob/main/CONTRIBUTING.md Installs all project dependencies using pnpm. Ensure Node.js 18+ and pnpm 9.5+ are installed. ```shell pnpm install ``` -------------------------------- ### Project Dependencies Source: https://github.com/srcbookdev/srcbook/blob/main/packages/api/srcbook/examples/langgraph-web-agent.src.md Install necessary LangChain and Node.js packages for building the web agent. ```json { "type": "module", "dependencies": { "@langchain/community": "^0.2.20", "@langchain/core": "^0.2.17", "@langchain/langgraph": "^0.0.29", "@langchain/openai": "^0.2.4", "better-sqlite3": "latest", "@types/node": "latest", "tsx": "latest", "typescript": "latest", "zod": "^3.23.8" } } ``` -------------------------------- ### Running a Simple JavaScript Code Cell Source: https://github.com/srcbookdev/srcbook/blob/main/packages/api/prompts/code-updater-javascript.txt Demonstrates how to execute a basic JavaScript command in a Srcbook code cell. This is a fundamental example for getting started with Srcbook execution. ```javascript // This is a trivial code cell. You can run me by // clicking 'Run' or using the shortcut `cmd` + `enter`. console.log("Hello, Srcbook!") ``` -------------------------------- ### Install ws library Source: https://github.com/srcbookdev/srcbook/blob/main/packages/api/srcbook/examples/websockets.src.md Add the 'ws' library as a dependency to your Node.js project. ```json { "type": "module", "dependencies": { "ws": "^8.17.1" } } ``` -------------------------------- ### Install React Router Source: https://github.com/srcbookdev/srcbook/blob/main/packages/api/test/plan-chunks-2.txt This command installs the react-router package using npm. Ensure you have Node.js and npm installed to run this command. ```bash npm install react-router ``` -------------------------------- ### Example Usage of BFS Source: https://github.com/srcbookdev/srcbook/blob/main/packages/api/prompts/code-updater-typescript.txt Demonstrates how to use the BFS algorithm with the Graph class. Creates a sample graph, performs BFS, and logs the traversal order. Requires Graph and bfs implementations. ```typescript import { Graph } from './graph.ts'; import { bfs } from './bfs.ts'; const graph = new Graph(); graph.addVertex(1); graph.addVertex(2); graph.addVertex(3); graph.addVertex(4); graph.addVertex(5); graph.addEdge(1, 2); graph.addEdge(1, 3); graph.addEdge(2, 4); graph.addEdge(3, 5); const bfsResult = bfs(graph, 1); console.log('BFS Traversal Order:', bfsResult); ``` -------------------------------- ### Simple WebSocket Server Source: https://github.com/srcbookdev/srcbook/blob/main/packages/api/srcbook/examples/websockets.src.md Implement a basic WebSocket server that listens for incoming connections and logs received messages. Ensure the server is running before starting the client. ```javascript import { WebSocketServer } from 'ws'; // Start this simple server on port 5405 const wss = new WebSocketServer({ port: 5405 }); wss.on('connection', (socket) => { socket.on('message', (data) => { console.log('Server received: %s', data); }); console.log("New client connected") }); ``` -------------------------------- ### Run Development Servers Source: https://github.com/srcbookdev/srcbook/blob/main/CONTRIBUTING.md Starts both the Vite development server and the Express API server for local development. Access the application at http://localhost:5173. ```shell pnpm run dev ``` -------------------------------- ### Simple JSON Code Block Source: https://github.com/srcbookdev/srcbook/blob/main/packages/api/test/srcmd_files/mock_srcbook/README.md A basic JSON code block example. ```json { "simple": "codeblock" } ``` -------------------------------- ### Example TypeScript Code Cell Source: https://github.com/srcbookdev/srcbook/blob/main/packages/api/prompts/cell-generator-typescript.txt Demonstrates a TypeScript code cell with type definitions and exported variables. Filename is specified using a heading 6. ```typescript type IsString = T extends string ? "Yes" : "No"; export type A = IsString; // "Yes" export type B = IsString; // "No" console.log(`Is string: ${A}`); // Output: Is string: Yes console.log(`Is string: ${B}`); // Output: Is string: No ``` -------------------------------- ### BFS Algorithm Implementation Source: https://github.com/srcbookdev/srcbook/blob/main/packages/api/prompts/code-updater-typescript.txt Implements the Breadth-First Search algorithm in TypeScript. It takes a Graph instance and a starting vertex, returning the order of visited vertices. Requires the Graph class. ```typescript import { Graph } from './graph.ts'; export function bfs(graph: Graph, startVertex: number): number[] { const visited: Set = new Set(); const queue: number[] = [startVertex]; const result: number[] = []; while (queue.length > 0) { const vertex = queue.shift()!; if (!visited.has(vertex)) { visited.add(vertex); result.push(vertex); const neighbors = graph.getNeighbors(vertex); for (const neighbor of neighbors) { if (!visited.has(neighbor)) { queue.push(neighbor); } } } } return result; } ``` -------------------------------- ### Generating a Random Word with npm Dependency Source: https://github.com/srcbookdev/srcbook/blob/main/packages/api/prompts/code-updater-javascript.txt Shows how to import and use a package from npm ('random-words') within a Srcbook code cell. Ensure the 'random-words' dependency is listed in the package.json cell and installed. ```javascript import {generate} from 'random-words'; console.log(generate()) ``` -------------------------------- ### Generate Random Words Source: https://github.com/srcbookdev/srcbook/blob/main/packages/api/srcbook/examples/getting-started.src.md This JavaScript code imports the 'random-words' library to generate and log four random words. Ensure the 'random-words' dependency is installed. ```javascript import { generate } from 'random-words'; for (let i = 0; i < 4; i++) { console.log(`Word ${i + 1}: ${generate()}`); } ``` -------------------------------- ### Export Vader Line Function Source: https://github.com/srcbookdev/srcbook/blob/main/packages/api/srcbook/examples/getting-started.src.md An example of exporting a function from one cell to be used in another. This cell defines and exports a function that formats a Star Wars quote. ```javascript export const vaderLine = (name) => `I am your father, ${name}` ``` -------------------------------- ### WebSocket Client Implementation Source: https://github.com/srcbookdev/srcbook/blob/main/packages/api/prompts/srcbook-generator.txt This snippet shows how to establish WebSocket connections, handle incoming messages, and send messages from multiple clients. It includes simulated delays for connection and disconnection events. ```javascript import WebSocket from 'ws'; console.log("Starting up"); const client1 = new WebSocket('ws://localhost:5406'); client1.on('message', (data) => { const message = JSON.parse(data); console.log(`Client 1 received ${message.type} message: ${message.payload}`) }); // Simulate latency in between clients connecting await new Promise((resolve) => setTimeout(resolve, 1500)); const client2 = new WebSocket('ws://localhost:5406'); client2.on('message', (data) => { const message = JSON.parse(data); console.log(`Client 2 received ${message.type} message: ${message.payload}`) }); // We put this inside the open event to ensure the client has // finished connecting to the server before sending a message. client2.on('open', () => { // Client 2 sends a 'broadcast' message which the server will // broadcast all other connected clients. client2.send(JSON.stringify({type: 'broadcast', payload: 'Hello'})); }); // Simulate latency in between clients disconnecting await new Promise((resolve) => setTimeout(resolve, 1500)); client1.close(); // Simulate latency before second client disconnects await new Promise((resolve) => setTimeout(resolve, 1500)); client2.close(); console.log("Shutting down"); ``` -------------------------------- ### Build and Run Srcbook with Docker Source: https://github.com/srcbookdev/srcbook/blob/main/README.md Build a Docker image for Srcbook and run it as a container. This method maps port 2150 and mounts local directories for data persistence and npm cache. ```bash # Build the Docker image docker build -t srcbook . # Run the container # The -p flag maps port 2150 from the container to your host machine # First -v flag mounts your local .srcbook directory to persist data # Second -v flag shares your npm cache for better performance docker run -p 2150:2150 -v ~/.srcbook:/root/.srcbook -v ~/.npm:/root/.npm srcbook ``` -------------------------------- ### Initialize Srcbook Theme Handling Source: https://github.com/srcbookdev/srcbook/blob/main/packages/web/index.html This snippet initializes Srcbook by checking the stored theme from localStorage and applying the appropriate class to the HTML element. It runs immediately upon script load. ```javascript Srcbook (function (theme) { if (theme === null) { return; } const html = document.querySelector('html'); if (theme === 'light') { html.classList.remove('dark'); html.classList.add('light'); } })(localStorage.getItem('sb:theme')); ``` -------------------------------- ### Create a Changeset Source: https://github.com/srcbookdev/srcbook/blob/main/CONTRIBUTING.md Generates a changeset for tracking changes and automating the release process. This prompts for details about the changes (major, minor, patch). ```shell pnpm changeset ``` -------------------------------- ### Accessing Secrets Source: https://github.com/srcbookdev/srcbook/blob/main/packages/api/srcbook/examples/getting-started.src.md Demonstrates how to access secrets stored as environment variables. It checks for 'SECRET_API_KEY' and logs a message accordingly. Ensure the secret is configured in your environment. ```javascript const secret = process.env.SECRET_API_KEY console.log(secret ? `The secret is: ${secret}` : 'SECRET_API_KEY not set') ``` -------------------------------- ### Manually Apply Database Migrations Source: https://github.com/srcbookdev/srcbook/blob/main/CONTRIBUTING.md Executes all pending database migrations manually. Migrations are typically applied automatically on application startup. ```shell pnpm run migrate ``` -------------------------------- ### Import and Use Add Function Source: https://github.com/srcbookdev/srcbook/blob/main/packages/api/test/srcmd_files/srcbook.src.md Imports the add function from index.mjs and logs the result of adding 2 and 3. ```javascript import {add} from './index.mjs'; const res = add(2, 3); console.log(res); ``` -------------------------------- ### Package JSON Configuration Source: https://github.com/srcbookdev/srcbook/blob/main/packages/api/srcbook/examples/getting-started.src.md This is the package.json file for a Srcbook project, defining its type as a module and listing dependencies. ```json { "type": "module", "dependencies": { "random-words": "^2.0.1" } } ``` -------------------------------- ### Project Dependencies Source: https://github.com/srcbookdev/srcbook/blob/main/packages/api/test/srcmd_files/srcbook.src.md Defines the dependencies for the Srcbook project. ```json { "dependencies": {} } ``` -------------------------------- ### Configure Global Srcbook API Settings Source: https://github.com/srcbookdev/srcbook/blob/main/packages/web/index.html Sets the global configuration for Srcbook's API, including host and origin, using environment variables. This configuration is essential for API communication. ```javascript globalThis.SRCBOOK_CONFIG = { api: { host: %VITE_SRCBOOK_API_HOST%, origin: %VITE_SRCBOOK_API_ORIGIN%, }, }; ``` -------------------------------- ### Generate Database Migration Source: https://github.com/srcbookdev/srcbook/blob/main/CONTRIBUTING.md Generates a new database migration file after modifying the schema. Replace with a descriptive name for the migration. ```shell # This will generate the migration pnpm run generate --name ``` -------------------------------- ### Stateful WebSocket Server with Client Management Source: https://github.com/srcbookdev/srcbook/blob/main/packages/api/srcbook/examples/websockets.src.md Develop a WebSocket server that manages multiple client connections, assigns unique IDs, and broadcasts messages between clients. It handles client connections, disconnections, and message broadcasting, ensuring clients don't receive their own broadcasted messages. Remember to remove disconnected sockets from the server's state. ```javascript import { WebSocketServer } from 'ws'; // Start this simple server on port 5405 const wss = new WebSocketServer({ port: 5406 }); // Utility to create auto-incrementing ids for clients const createClientId = ((id) => () => ++id)(0); const connectedClients = []; function broadcast(senderId, message) { for (const client of connectedClients) { // The client who is sending the message should not receive it if (client.id !== senderId) { client.socket.send(JSON.stringify(message)); } } } wss.on('connection', (socket) => { const clientId = createClientId(); // Store the client connection connectedClients.push({id: clientId, socket}); // Inform others a new client has connected broadcast(clientId, { type: 'client:connected', payload: `Client ${clientId} connected` }); // When the server receives a broadcast message, // send it to all the other connected clients socket.on('message', (data) => { const message = JSON.parse(data); if (message.type === 'broadcast') { broadcast(clientId, { type: "broadcast", payload: message.payload }) } }); socket.on('close', () => { // Inform others a client has disconnected broadcast(clientId, { type: 'client:disconnected', payload: `Client ${clientId} disconnected` }); // Important: remember to remove the socket from // server state when the connection is closed. const idx = connectedClients.findIndex(({id}) => id === clientId); connectedClients.splice(idx, 1); }); }); ``` -------------------------------- ### WebSocket Package JSON Configuration Source: https://github.com/srcbookdev/srcbook/blob/main/packages/api/prompts/srcbook-generator.txt Specifies the project type as a module and lists 'ws' as a dependency for building WebSocket client and server applications in Node.js. ```json { "type": "module", "dependencies": { "ws": "^8.17.1" } } ``` -------------------------------- ### Environment Variable Check Source: https://github.com/srcbookdev/srcbook/blob/main/packages/api/srcbook/examples/langgraph-web-agent.src.md Ensure required API keys (OpenAI and Tavily) are set in the environment before running the agent. ```typescript import assert from 'node:assert'; assert.ok(process.env.OPENAI_API_KEY, 'You need to set OPENAI_API_KEY'); assert.ok(process.env.TAVILY_API_KEY, 'You need to set TAVILY_API_KEY'); ``` -------------------------------- ### Import and Use Vader Line Function Source: https://github.com/srcbookdev/srcbook/blob/main/packages/api/srcbook/examples/getting-started.src.md This cell imports the 'vaderLine' function from './star-wars.js' and uses it to print personalized Star Wars quotes. ```javascript import { vaderLine } from './star-wars.js'; console.log(vaderLine("Luke")); console.log(vaderLine("Leia")); ``` -------------------------------- ### LangGraph Web Agent Dependencies Source: https://github.com/srcbookdev/srcbook/blob/main/packages/api/prompts/srcbook-generator.txt Defines the necessary dependencies for a LangGraph web agent project in a `package.json` file. Includes LangChain and related libraries. ```json { "type": "module", "dependencies": { "@langchain/community": "^0.2.12", "@langchain/core": "^0.2.8", "@langchain/langgraph": "^0.0.24", "@langchain/openai": "^0.1.3", "@types/node": "^20.14.7", "better-sqlite3": "^9.6.0", "tsx": "latest", "typescript": "latest" } } ``` -------------------------------- ### Update Mock Album Data Source: https://github.com/srcbookdev/srcbook/blob/main/packages/api/test/plan-chunks.txt This snippet shows how to update the mock album data by adding classic rock bands. Ensure the Album type is correctly imported and used. ```typescript import { Album, PlaylistItem } from '../types'; export const albums: Album[] = [ { id: '1', title: 'Abbey Road', artist: 'The Beatles', cover: 'https://picsum.photos/seed/beatles/300/300', }, { id: '2', title: 'Remain in Light', artist: 'Talking Heads', cover: 'https://picsum.photos/seed/talking/300/300', }, { id: '3', title: 'American Beauty', artist: 'Grateful Dead', cover: 'https://picsum.photos/seed/dead/300/300', }, { id: '4', title: 'OK Computer', artist: 'Radiohead', cover: 'https://picsum.photos/seed/radiohead/300/300', }, { id: '5', title: 'Un Ve Rano Sin Ti', artist: 'Bad Bunny', cover: 'https://picsum.photos/seed/5/300/300', }, { id: '6', title: '30', artist: 'Adele', cover: 'https://picsum.photos/seed/6/300/300', }, ]; export const playlists: PlaylistItem[] = [ { id: '1', name: 'Liked Songs', icon: '❤️' }, { id: '2', name: 'Your Episodes', icon: '🎙️' }, { id: '3', name: 'Rock Classics', icon: '🎸' }, { id: '4', name: 'Chill Vibes', icon: '🌊' }, ]; ``` -------------------------------- ### Accessing Secrets as Environment Variables Source: https://github.com/srcbookdev/srcbook/blob/main/packages/api/prompts/code-updater-javascript.txt Shows how to securely access secrets stored as environment variables within a Srcbook code cell. Secrets should be managed via the secrets mechanism and accessed using process.env. ```javascript const API_KEY = process.env.SECRET_API_KEY; const token = auth(API_KEY); ``` -------------------------------- ### Update Mock Data with Phish Albums Source: https://github.com/srcbookdev/srcbook/blob/main/packages/api/test/plan-chunks-2.txt This snippet shows the updated mock data for albums, now including Phish albums with real album information. It defines an array of Album objects, each with an id, title, artist, and cover image URL. ```typescript import { Album, PlaylistItem } from '../types'; export const albums: Album[] = [ { id: '1', title: 'A Picture of Nectar', artist: 'Phish', cover: 'https://i.scdn.co/image/ab67616d0000b273f3912f c6e6533d0aae3c58d', }, { id: '2', title: 'Billy Breathes', artist: 'Phish', cover: 'https://i.scdn.co/image/ab67616d0000b273f4c8d14 e6c2d8b0651388be6', }, { id: '3', title: 'Farmhouse', artist: 'Phish', cover: 'https://i.scdn.co/image/ab67616d0000b273f5a0be2976c3 df8baae5d5b1', }, { id: '4', title: 'Story of the Ghost', artist: 'Phish', cover: 'https://i.scdn.co/image/ab67616d0000b273f00669d9866452 b5f49f4989', }, { id: '5', title: 'Hoist', artist: 'Phish', cover: 'https://i.scdn.co/image/ab67616d0000b273f5c500e2fa5f1 d0ae5dce4df', }, { id: '6', title: 'Sigma Oasis', artist: 'Phish', cover: 'https://i.scdn.co/image/ab67616d0000b273a0c79aba3b83f5f016 f47737', }, ]; export const playlists: PlaylistItem[] = [ { id: '1', name: 'Liked Songs', icon: '❤' }, { id: '2', name: 'Your Episodes', icon: '🎙️' }, { id: '3', name: 'Rock Classics', icon: '🎸' }, { id: '4', name: 'Chill Vibes', icon: '🌊' }, ]; ``` -------------------------------- ### Importing a Function from Another Cell Source: https://github.com/srcbookdev/srcbook/blob/main/packages/api/prompts/code-updater-javascript.txt Demonstrates how to import and use an exported function from another Srcbook code cell. This relies on the cells being treated as ES6 modules. ```javascript import {func} from './star-wars.js'; console.log(func("Luke")); ``` -------------------------------- ### Run Package Scripts Source: https://github.com/srcbookdev/srcbook/blob/main/CONTRIBUTING.md Executes a script defined in the top-level package.json. Use the --filter flag to run scripts within specific packages. ```shell pnpm run check-types ``` ```shell pnpm run check-types --filter=@srcbook/api ``` -------------------------------- ### WebSocket Client Connection and Messaging Source: https://github.com/srcbookdev/srcbook/blob/main/packages/api/srcbook/examples/websockets.src.md This client connects to a WebSocket server, listens for incoming messages, and sends a broadcast message. It simulates client connections and disconnections with delays. ```javascript import WebSocket from 'ws'; console.log("Starting up"); const client1 = new WebSocket('ws://localhost:5406'); client1.on('message', (data) => { const message = JSON.parse(data); console.log(`Client 1 received ${message.type} message: ${message.payload}`) }); // Simulate latency in between clients connecting await new Promise((resolve) => setTimeout(resolve, 1500)); const client2 = new WebSocket('ws://localhost:5406'); client2.on('message', (data) => { const message = JSON.parse(data); console.log(`Client 2 received ${message.type} message: ${message.payload}`) }); // We put this inside the open event to ensure the client has // finished connecting to the server before sending a message. client2.on('open', () => { // Client 2 sends a 'broadcast' message which the server will // broadcast all other connected clients. client2.send(JSON.stringify({type: 'broadcast', payload: 'Hello'})); }); // Simulate latency in between clients disconnecting await new Promise((resolve) => setTimeout(resolve, 1500)); client1.close(); // Simulate latency before second client disconnects await new Promise((resolve) => setTimeout(resolve, 1500)); client2.close(); console.log("Shutting down"); ``` -------------------------------- ### Add npm Dependency to API Package Source: https://github.com/srcbookdev/srcbook/blob/main/CONTRIBUTING.md Adds a dependency from the npm registry to the API package. Use -D for development dependencies. ```shell # Add npm dependency to the API package pnpm add --filter api # Add npm dev dependency to the API package pnpm add -D --filter api ``` -------------------------------- ### Uninstall Srcbook Source: https://github.com/srcbookdev/srcbook/blob/main/README.md Remove Srcbook from your system by deleting its local directory and uninstalling the package manager. Adjust the uninstall command based on the package manager used. ```bash rm -rf ~/.srcbook # if you configured a global install npm uninstall -g srcbook ``` -------------------------------- ### JavaScript WebSocket Client Source: https://github.com/srcbookdev/srcbook/blob/main/packages/api/prompts/cell-generator-javascript.txt Connects to a WebSocket server, sends a message, and then closes the connection. Ensure the server is running on ws://localhost:5405. ```javascript import WebSocket from 'ws'; // Reference the same port the server is running on const ws = new WebSocket('ws://localhost:5405'); ws.on('open', () => { ws.send('Hello from simple-client.js'); ws.close(); }); ``` -------------------------------- ### Add Function Definition Source: https://github.com/srcbookdev/srcbook/blob/main/packages/api/test/srcmd_files/srcbook.src.md Defines a simple addition function. ```javascript // A code snippet here. export function add(a, b) { return a + b } ``` -------------------------------- ### Agent Definition with SQLite Memory Source: https://github.com/srcbookdev/srcbook/blob/main/packages/api/prompts/srcbook-generator.txt Defines the agent's state, tools, model, and workflow using LangGraph. It includes a conditional edge to route to tools or end the conversation and compiles the graph with SQLite memory for persistence. ```typescript import { HumanMessage } from "@langchain/core/messages"; import { TavilySearchResults } from "@langchain/community/tools/tavily_search"; import { ChatOpenAI } from "@langchain/openai"; import { END, START, StateGraph, StateGraphArgs } from "@langchain/langgraph"; import { SqliteSaver } from "@langchain/langgraph/checkpoint/sqlite" // import { MemorySaver } from "@langchain/langgraph"; import { ToolNode } from "@langchain/langgraph/prebuilt"; // Define the state interface interface AgentState { messages: HumanMessage[]; } // We'll use a local sqlite DB for memory export const DB_NAME = 'langgraph_memory.db' // Define the graph state const graphState: StateGraphArgs["channels"] = { messages: { value: (x: HumanMessage[], y: HumanMessage[]) => x.concat(y), default: () => [], }, }; // Define the tools for the agent to use const tools = [new TavilySearchResults({ maxResults: 1 })]; const toolNode = new ToolNode(tools); const model = new ChatOpenAI({ model: 'gpt-4o', temperature: 0 }).bindTools(tools); // Define the function that determines whether to continue or not function shouldContinue(state: AgentState): "tools" | typeof END { const messages = state.messages; const lastMessage = messages[messages.length - 1]; // If the LLM makes a tool call, then we route to the "tools" node if (lastMessage.additional_kwargs.tool_calls) { return "tools"; } // Otherwise, we stop (reply to the user) return END; } // Define the function that calls the model async function callModel(state: AgentState) { const messages = state.messages; const response = await model.invoke(messages); // We return a list, because this will get added to the existing list return { messages: [response] }; } // Define a new graph const workflow = new StateGraph({ channels: graphState }) .addNode("agent", callModel) .addNode("tools", toolNode) .addEdge(START, "agent") .addConditionalEdges("agent", shouldContinue) .addEdge("tools", "agent"); // Initialize memory to persist state between graph runs export const memory = SqliteSaver.fromConnString(DB_NAME); // const checkpointer = new MemorySaver(); // Finally, we compile it! // This compiles it into a LangChain Runnable. // Note that we're (optionally) passing the memory when compiling the graph export const app = workflow.compile({ checkpointer: memory }); ``` -------------------------------- ### Invoke Agent for NY Weather (Context Retained) Source: https://github.com/srcbookdev/srcbook/blob/main/packages/api/srcbook/examples/langgraph-web-agent.src.md Invokes the agent again with the same thread ID to demonstrate conversation context retention and retrieve weather information for New York. ```typescript import { app } from './agent.ts'; import { HumanMessage } from '@langchain/core/messages'; const nextState = await app.invoke( { messages: [new HumanMessage('what about ny')] }, { configurable: { thread_id: '42' } }, ); console.log(nextState.messages[nextState.messages.length - 1].content); ``` -------------------------------- ### Add Workspace Dependency to API Package Source: https://github.com/srcbookdev/srcbook/blob/main/CONTRIBUTING.md Adds a dependency from within the workspace to the API package. Use --workspace and -D for dev dependencies. ```shell # Add the shared package to the API package. pnpm add @srcbook/shared --workspace --filter api # Add the shared package as a dev dependency to the API package. pnpm add -D @srcbook/shared --workspace --filter api ``` -------------------------------- ### LangGraph Agent Definition Source: https://github.com/srcbookdev/srcbook/blob/main/packages/api/srcbook/examples/langgraph-web-agent.src.md Defines the agent's state, tools, model, and workflow logic, including routing and state persistence with SQLite. ```typescript import { HumanMessage, AIMessage } from '@langchain/core/messages'; import { DynamicStructuredTool } from "@langchain/core/tools"; import { z } from "zod"; import { TavilySearchResults } from '@langchain/community/tools/tavily_search'; import { ChatOpenAI } from '@langchain/openai'; import { END, START, StateGraph, StateGraphArgs } from '@langchain/langgraph'; import { SqliteSaver } from '@langchain/langgraph/checkpoint/sqlite'; import { ToolNode } from '@langchain/langgraph/prebuilt'; // Define the state interface interface AgentState { messages: HumanMessage[]; } // We'll use a local sqlite DB for memory export const DB_NAME = 'langgraph_memory.db'; // Define the graph state const graphState: StateGraphArgs['channels'] = { messages: { value: (x: HumanMessage[], y: HumanMessage[]) => x.concat(y), default: () => [], }, }; // Define the tools for the agent to use const tools = [new TavilySearchResults({ maxResults: 1 })]; const toolNode = new ToolNode(tools); const model = new ChatOpenAI({ model: 'gpt-4o', temperature: 0 }).bindTools(tools); // Define the function that determines whether to continue or not function shouldContinue(state: AgentState): 'tools' | typeof END { const messages = state.messages; const lastMessage = messages[messages.length - 1] as AIMessage; // If the LLM makes a tool call, then we route to the "tools" node if (lastMessage.tool_calls?.length) { return 'tools'; } // Otherwise, we stop (reply to the user) return END; } // Define the function that calls the model async function callModel(state: AgentState) { const messages = state.messages; const response = await model.invoke(messages); // We return a list, because this will get added to the existing list return { messages: [response] }; } // Define a new graph const workflow = new StateGraph({ channels: graphState }) .addNode('agent', callModel) .addNode('tools', toolNode) .addEdge(START, 'agent') .addConditionalEdges('agent', shouldContinue) .addEdge('tools', 'agent'); // Initialize memory to persist state between graph runs export const memory = SqliteSaver.fromConnString(DB_NAME); // Finally, we compile it! // This compiles it into a LangChain Runnable. // Note that we're (optionally) passing the memory when compiling the graph export const app = workflow.compile({ checkpointer: memory }); ``` -------------------------------- ### Exporting a Function for Inter-Cell Use Source: https://github.com/srcbookdev/srcbook/blob/main/packages/api/prompts/code-updater-javascript.txt Illustrates how to export a function from a Srcbook code cell, making it available for import in other cells. This utilizes standard ES6 module export syntax. ```javascript export const func = (name) => `I am your father, ${name}` ``` -------------------------------- ### Basic Console Log Source: https://github.com/srcbookdev/srcbook/blob/main/packages/api/srcbook/examples/getting-started.src.md A simple JavaScript code cell that logs a message to the console. It can be run directly within the Srcbook environment. ```javascript // You can run me by clicking 'Run' or using the shortcut `cmd` + `enter`. console.log("Hello, Srcbook!") ``` -------------------------------- ### Invoke Agent for SF Weather Source: https://github.com/srcbookdev/srcbook/blob/main/packages/api/srcbook/examples/langgraph-web-agent.src.md Invokes the compiled LangGraph agent with an initial message and a specific thread ID to retrieve weather information for San Francisco. ```typescript import { app } from './agent.ts'; import { HumanMessage } from '@langchain/core/messages'; // Reference a thread const thread = { configurable: { thread_id: '42' } }; // Use the Runnable const finalState = await app.invoke( { messages: [new HumanMessage('what is the weather in sf')] }, thread, ); console.log(finalState.messages[finalState.messages.length - 1].content); ``` -------------------------------- ### Disable Analytics Source: https://github.com/srcbookdev/srcbook/blob/main/README.md Run Srcbook with the SRCBOOK_DISABLE_ANALYTICS environment variable set to true to disable behavioral analytics collection. ```bash SRCBOOK_DISABLE_ANALYTICS=true ``` -------------------------------- ### Invoke Agent with Thread ID Source: https://github.com/srcbookdev/srcbook/blob/main/packages/api/prompts/srcbook-generator.txt Invokes the compiled LangGraph agent with an initial message and a specific thread ID to retrieve weather information. The thread ID ensures conversation context is maintained. ```typescript import {app} from './agent.ts'; import { HumanMessage } from "@langchain/core/messages"; // Reference a thread const thread = { configurable: { thread_id: "42" }}; // Use the Runnable const finalState = await app.invoke( { messages: [new HumanMessage("what is the weather in sf")] }, thread ); console.log(finalState.messages[finalState.messages.length - 1].content) ``` -------------------------------- ### Continue Conversation with Same Thread ID Source: https://github.com/srcbookdev/srcbook/blob/main/packages/api/prompts/srcbook-generator.txt Continues a previous conversation by invoking the agent with a new message and the same thread ID. This demonstrates state persistence, allowing the agent to remember the context. ```typescript import {app} from './agent.ts'; import { HumanMessage } from '@langchain/core/messages'; const nextState = await app.invoke( { messages: [new HumanMessage("what about ny")] }, { configurable: { thread_id: "42"} } ); console.log(nextState.messages[nextState.messages.length - 1].content); ``` -------------------------------- ### Clear SQLite Memory Database Source: https://github.com/srcbookdev/srcbook/blob/main/packages/api/srcbook/examples/langgraph-web-agent.src.md Removes the SQLite database file used for persisting conversation state, effectively clearing the agent's memory. ```typescript import { DB_NAME } from './agent.ts'; import fs from 'node:fs'; // I can't find good documentation on the memory module, so let's apply the nuclear method fs.rmSync(DB_NAME); ``` -------------------------------- ### Graph Class Definition Source: https://github.com/srcbookdev/srcbook/blob/main/packages/api/prompts/code-updater-typescript.txt Defines a Graph class with methods to manage vertices and edges, essential for graph algorithms. It uses a Map to store the adjacency list. ```typescript export class Graph { private adjacencyList: Map; constructor() { this.adjacencyList = new Map(); } addVertex(vertex: number) { if (!this.adjacencyList.has(vertex)) { this.adjacencyList.set(vertex, []); } } addEdge(vertex1: number, vertex2: number) { if (this.adjacencyList.has(vertex1) && this.adjacencyList.has(vertex2)) { this.adjacencyList.get(vertex1)?.push(vertex2); this.adjacencyList.get(vertex2)?.push(vertex1); } } getNeighbors(vertex: number): number[] { return this.adjacencyList.get(vertex) || []; } } ``` -------------------------------- ### Fixing Factorial Bug Source: https://github.com/srcbookdev/srcbook/blob/main/packages/api/srcbook/examples/getting-started.src.md This code cell contains a bug in the factorial function. The AI feature can be used to identify and fix this bug. The assertion checks if the factorial of 5 is correctly calculated. ```javascript function factorial(n) { if (n === 0 || n === 1) { return 1; } return n * factorial(n - 2); } console.assert(factorial(5) === 120, 'Factorial of 5 should be 120'); ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.