### Install dotenv Package for Node.js Projects Source: https://docs.graphlit.dev/getting-started/quickstart This bash command installs the 'dotenv' package, which is required for managing environment variables in Node.js projects, often used for API keys and other configurations. ```bash npm install dotenv ``` -------------------------------- ### Python Workflow Example Source: https://docs.graphlit.dev/platform/key-concepts This Python code snippet demonstrates the initialization of a Graphlit client, which is the starting point for defining and executing workflows within the Graphlit platform. It requires the 'graphlit' and 'graphlit_api' libraries. ```python from graphlit import Graphlit from graphlit_api import * graphlit = Graphlit() ``` -------------------------------- ### Quick Start: Ingest Text with Graphlit Python SDK Source: https://docs.graphlit.dev/sdk-setup/for-python-developers A basic example demonstrating how to initialize the Graphlit client and ingest text content. The SDK automatically reads necessary credentials from environment variables. This snippet shows the core process of sending data to Graphlit for processing. ```python import asyncio import os from graphlit import Graphlit from graphlit_api import * async def main(): # Reads from environment variables automatically graphlit = Graphlit() # Ingest content response = await graphlit.client.ingest_text( name="Product Requirements", text="Our AI agent needs persistent memory across sessions..." ) print(f"✅ Memory created: {response.ingest_text.id}") asyncio.run(main()) ``` -------------------------------- ### Run Deep Research Agent using uv and pip Source: https://docs.graphlit.dev/examples/deep-research/agno Provides command-line examples for running the Deep Research Agent. It demonstrates how to use `uv` for execution, specifying search queries or URLs, and redirecting output to a file. It also shows how to install the package using `pip` and run the agent directly. ```bash # With uv (recommended): uv run deep-research --search "knowledge graphs" # With pip: pip install -e . deep-research --url "https://en.wikipedia.org/wiki/RAG" # Save to file: uv run deep-research --search "AI agents" > report.md # Cleanup after (deletes collection, workflow, and content): uv run deep-research --search "test query" --cleanup # Alternative commands (all equivalent): python -m deep_research --search "query" # Works after install python -m deep_research.main --search "query" # Always works ``` -------------------------------- ### Define a Custom Database Query Tool for Graphlit Source: https://docs.graphlit.dev/getting-started/quickstart This TypeScript example defines a custom tool for the Graphlit SDK named 'query_database'. The tool is designed to query a customer database and expects a SQL query string as input, as defined by its JSON schema. ```typescript // Add a database query tool const dbTool: ToolDefinitionInput = { name: 'query_database', description: 'Query the customer database', schema: JSON.stringify({ type: 'object', properties: { query: { type: 'string', description: 'SQL query' }, }, required: ['query'], }), }; ``` -------------------------------- ### Pattern 2: Reusable Project Defaults Setup (TypeScript) Source: https://docs.graphlit.dev/platform/specifications Provides an example of setting up reusable default specifications for project initialization. This function creates default completion and text embedding specifications and stores their IDs for later use. ```typescript // Set up once during project initialization async function setupProjectSpecs() { const specs = { completion: await graphlit.createSpecification({ name: 'Default Completion', type: SpecificationTypes.Completion, serviceType: ModelServiceTypes.Anthropic, anthropic: { model: AnthropicModels.Claude_4_5Sonnet } }), embedding: await graphlit.createSpecification({ name: 'Default Embeddings', type: SpecificationTypes.TextEmbedding, serviceType: ModelServiceTypes.OpenAi, openAI: { model: OpenAiModels.Embedding_3Large } }) }; // Store IDs in database/config await db.config.setMultiple({ default_completion_spec: specs.completion.createSpecification.id, default_embedding_spec: specs.embedding.createSpecification.id }); return specs; } ``` -------------------------------- ### Create View using C# Source: https://docs.graphlit.dev/api-guides/use-cases/views/view-create Shows how to create a view using the Graphlit C# SDK. This example initializes the Graphlit client, defines a `ViewInput` object with a name and state, and then calls the `CreateView` method. Ensure the 'Graphlit' NuGet package is installed. ```csharp using Graphlit; var client = new Graphlit(); // Create view (PascalCase) var viewInput = new ViewInput { Name = "Product Documentation Search", State = EntityState.Enabled }; var response = await graphlit.CreateView(viewInput); var viewId = response.CreateView.Id; Console.WriteLine($"View created: {viewId}"); ``` -------------------------------- ### Synchronous Document Ingestion in Graphlit SDK Source: https://docs.graphlit.dev/getting-started/quickstart This TypeScript example demonstrates how to ensure a document is fully processed before proceeding by using the `isSynchronous: true` option in the `ingestUri` function. This is useful for preventing 'Content not finished processing' errors. ```typescript await graphlit.ingestUri(url, name, undefined, undefined, true); ``` -------------------------------- ### Graphlit SDK Installation Source: https://docs.graphlit.dev/why-graphlit Provides the command to install the Graphlit client library using npm. This is the first step to integrating Graphlit into your project. ```bash npm install graphlit-client ``` -------------------------------- ### Verify Graphlit Setup with TypeScript Source: https://docs.graphlit.dev/index A basic TypeScript script to verify that your Graphlit credentials are set up correctly and you can connect to your project. This is the first step in the Graphlit quick start guide. ```typescript import { Graphlit } from 'graphlit-client'; const graphlit = new Graphlit(); async function main() { const project = await graphlit.getProject(); console.log(`✅ Connected: ${project.project.name}`); } main(); ``` -------------------------------- ### Project Setup with uv (Bash) Source: https://docs.graphlit.dev/examples/deep-research/agno Sets up a new project directory, initializes it for uv, and adds necessary Python packages. This is the recommended setup process. ```bash mkdir deep-research && cd deep-research uv init uv add agno graphlit-client python-dotenv rich openai ``` -------------------------------- ### Project Setup with pip (Bash) Source: https://docs.graphlit.dev/examples/deep-research/agno Sets up a new project directory and creates a virtual environment using pip. This is an alternative setup method if uv is not used. ```bash mkdir deep-research && cd deep-research python -m venv venv source venv/bin/activate pip install agno graphlit-client python-dotenv ``` -------------------------------- ### Example MCP Prompt: Ingest a File Source: https://docs.graphlit.dev/mcp-integration/mcp-integration An example of an MCP command to ingest a local file into Graphlit. This prompt specifies the file path, an optional workflow to trigger, and whether the ingestion should be synchronous. ```bash @graphlit ingest_file path="./runbooks/cache-playbook.pdf" workflow={"id":"${WORKFLOW_ID}"} isSynchronous=true ``` -------------------------------- ### Real-Time Streaming - Explain concepts with streaming output Source: https://docs.graphlit.dev/getting-started/quickstart This endpoint demonstrates how to stream AI responses in real-time, providing a dynamic output similar to ChatGPT's typing effect. This feature is currently specific to the TypeScript SDK. ```APIDOC ## POST /api/createSpecification ### Description Creates a specification for an AI model, defining its behavior and parameters. ### Method POST ### Endpoint /api/createSpecification ### Parameters #### Request Body - **name** (string) - Required - The name of the specification. - **type** (string) - Required - The type of specification (e.g., 'Completion'). - **serviceType** (string) - Required - The type of AI service (e.g., 'OpenAi'). - **openAI** (object) - Optional - Configuration for OpenAI models. - **model** (string) - Required - The OpenAI model to use (e.g., 'GPT_4_OMN'). - **temperature** (number) - Optional - Controls randomness in output. ### Request Example ```typescript import { Graphlit } from 'graphlit-client'; import { SpecificationTypes, ModelServiceTypes, OpenAiModels, } from 'graphlit-client/dist/generated/graphql-types'; const graphlit = new Graphlit(); async function createSpec() { const spec = await graphlit.createSpecification({ name: 'Assistant', type: SpecificationTypes.Completion, serviceType: ModelServiceTypes.OpenAi, openAI: { model: OpenAiModels.Gpt4O_128K, temperature: 0.7 } }); console.log(spec.createSpecification.id); } createSpec(); ``` ## POST /api/streamAgent ### Description Streams a response from an agent, processing events as they arrive. ### Method POST ### Endpoint /api/streamAgent ### Parameters #### Query Parameters - **prompt** (string) - Required - The prompt to send to the agent. - **eventHandler** (function) - Required - A callback function to handle incoming events. - **event.type** (string) - The type of event (e.g., 'message_update'). - **event.message** (object) - The message content. - **message** (string) - The text of the message. - **event.isStreaming** (boolean) - Indicates if streaming is ongoing. - **conversationId** (string) - Optional - The ID of an existing conversation. - **specificationId** (object) - Optional - The ID of a specification to use. - **id** (string) - Required - The ID of the specification. ### Request Example ```typescript import { Graphlit } from 'graphlit-client'; import { OpenAI } from 'openai'; import { SpecificationTypes, ModelServiceTypes, OpenAiModels, } from 'graphlit-client/dist/generated/graphql-types'; const graphlit = new Graphlit(); graphlit.setOpenAIClient(new OpenAI()); // Ensure OpenAI client is set for streaming async function streamResponse() { const spec = await graphlit.createSpecification({ name: 'Assistant', type: SpecificationTypes.Completion, serviceType: ModelServiceTypes.OpenAi, openAI: { model: OpenAiModels.Gpt4O_128K, temperature: 0.7 } }); await graphlit.streamAgent( 'Explain transformer attention in simple terms', (event) => { if (event.type === 'message_update') { process.stdout.write(event.message.message); if (!event.isStreaming) { console.log('\n[complete]'); } } }, undefined, { id: spec.createSpecification.id }, ); } streamResponse(); ``` ### Response This endpoint streams events. The `eventHandler` function processes these events. #### Success Response (Streamed Events) - **message_update**: Contains partial or complete message updates. - **message.message**: The text content of the update. - **isStreaming**: Boolean indicating if more updates are expected. #### Response Example (Output to console) ``` Transformer attention is a mechanism that allows the model to focus on different parts of the input when processing each token. Think of it like highlighting the most relevant words in a sentence when trying to understand each word's meaning. [complete] ``` ``` -------------------------------- ### Example MCP Prompt: Prompt a Conversation Source: https://docs.graphlit.dev/mcp-integration/mcp-integration An example of an MCP command to interact with a conversation within Graphlit. This prompt targets a specific conversation ID and asks a question, with the server streaming token updates back to the IDE. ```bash @graphlit prompt_conversation id="${CONVERSATION_ID}" prompt="Summarize the last three incidents for Acme Corp and list remaining blockers." ``` -------------------------------- ### Manage Collections and Query Content (.NET) Source: https://docs.graphlit.dev/platform/key-concepts This .NET example illustrates how to create a collection, ingest a PDF document into it, and subsequently query for content belonging to that collection using the Graphlit client. It covers the essential steps for collection-based data management in C#. ```csharp using GraphlitClient; using System.Net.Http; using StrawberryShake; using var httpClient = new HttpClient(); var client = new Graphlit(httpClient); // Create collection var collInput = new CollectionInput(name: "Acme Corp"); var collResponse = await client.CreateCollection.ExecuteAsync(collInput); collResponse.EnsureNoErrors(); var collection = collResponse.Data?.CreateCollection; // Add content during ingestion var ingestResponse = await client.IngestUri.ExecuteAsync( uri: "https://example.com/acme-doc.pdf", collections: new[] { new EntityReferenceInput(id: collection.Id) } ); ingestResponse.EnsureNoErrors(); var content = ingestResponse.Data?.IngestUri; // Query by collection var filter = new ContentFilter( collections: new[] { new EntityReferenceFilter(id: collection.Id) } ); var queryResponse = await client.QueryContents.ExecuteAsync(filter); queryResponse.EnsureNoErrors(); var results = queryResponse.Data?.QueryContents?.Results; ``` -------------------------------- ### Example MCP Prompt: Scope Search by Collection and Entity Source: https://docs.graphlit.dev/mcp-integration/mcp-integration An example of an MCP command to perform a scoped search within Graphlit. This prompt searches for 'pricing' within a specific collection and scopes the observation to a particular organization. ```bash @graphlit query_contents search="pricing" searchType=HYBRID collections=["${GRAPHLIT_COLLECTION_SUPPORT}"] observations=[{"type":"ORGANIZATION","observable":{"id":"${GRAPHLIT_ORG_ACME}"}}] ``` -------------------------------- ### Create and Prompt Conversation (.NET) Source: https://docs.graphlit.dev/platform/key-concepts Illustrates the process of initiating a conversation and asking a question using the .NET SDK. Similar to the TypeScript example, it highlights the automatic memory retrieval and the steps involved in generating a cited answer. ```csharp // Create conversation var conversation = await graphlit.CreateConversation( name: "Acme Corp Analysis" ); // Ask questions - memory retrieval automatic var response = await graphlit.PromptConversation( prompt: "What are Acme Corp's main technical concerns?", id: conversation.CreateConversation.Id ); // Behind the scenes: // 1. Parses entities: "Acme Corp" (organization) // 2. Queries knowledge graph for related content // 3. Retrieves relevant content (emails, meetings, documents) // 4. Injects semantic memory (entities, relationships) // 5. Generates answer with citations ``` -------------------------------- ### Example MCP Prompt: Search Company Knowledge Source: https://docs.graphlit.dev/mcp-integration/mcp-integration An example of an MCP command to query company knowledge using the Graphlit MCP Server. This prompt searches for 'redis failover' with a hybrid search type and limits results to 5. ```bash @graphlit query_contents search="redis failover" searchType=HYBRID limit=5 ``` -------------------------------- ### Get Message History Source: https://docs.graphlit.dev/api-guides Retrieves the complete message history for a given conversation. This allows for reviewing past interactions and context. ```python from graphlit import GraphLit graphlit = GraphLit(api_key="YOUR_API_KEY") conversation_id = "conv_12345abcde" messages = graphlit.conversations.get_messages(conversation_id) for message in messages: print(f"{message.sender}: {message.text}") ``` -------------------------------- ### Ask Questions with RAG Conversation using Graphlit SDK (TypeScript) Source: https://docs.graphlit.dev/getting-started/quickstart This snippet demonstrates how to ingest a document, create a conversation scoped to that document, and then ask a question. It utilizes the Graphlit SDK to manage the RAG process and retrieve an answer with citations. ```typescript import { Graphlit } from 'graphlit-client'; const graphlit = new Graphlit(); async function main() { // Reference the document from Step 1 const content = await graphlit.ingestUri( 'https://arxiv.org/pdf/1706.03762.pdf', 'Attention Paper', undefined, undefined, true, ); // Create conversation scoped to this document const conversation = await graphlit.createConversation({ name: 'Q&A Session', filter: { contents: [{ id: content.ingestUri.id }] } }); // Ask questions const answer = await graphlit.promptConversation( 'What are the key innovations in this paper?', conversation.createConversation.id, ); console.log(answer.promptConversation.message?.message); } main(); ``` -------------------------------- ### Create and Prompt Conversation Source: https://docs.graphlit.dev/api-guides Demonstrates how to create a new conversation and immediately prompt an agent within it. This is the starting point for most conversational interactions. ```python from graphlit import GraphLit graphlit = GraphLit(api_key="YOUR_API_KEY") conversation = graphlit.conversations.create("My New Conversation") response = graphlit.conversations.prompt(conversation.id, "Hello, how are you?") print(response.text) ``` -------------------------------- ### Create Preparation Workflow with C# Source: https://docs.graphlit.dev/api-guides/use-cases/workflows/workflow-create-preparation Shows how to create a preparation workflow using C#. This involves instantiating the Graphlit client, creating a specification for a preparation model, and then defining the workflow with its associated preparation jobs. ```csharp using Graphlit; var client = new Graphlit(); // Create specification var specResponse = await graphlit.CreateSpecification(new SpecificationInput { Name = "GPT-4o Vision for PDFs", Type = SpecificationTypes.Preparation, ServiceType = ModelServiceTypes.OpenAi, OpenAI = new OpenAIModelPropertiesInput { Model = OpenAiModels.Gpt4O_128K } }); // Create preparation workflow (PascalCase) var workflowInput = new WorkflowInput { Name = "PDF Preparation with Vision", Preparation = new PreparationWorkflowStageInput { Jobs = new[] { new PreparationWorkflowJobInput { Connector = new FilePreparationConnectorInput { Type = FilePreparationServiceTypes.ModelDocument, ModelDocument = new ModelDocumentPreparationPropertiesInput { Specification = new EntityReferenceInput { Id = specResponse.CreateSpecification.Id } } } } } } }; var response = await graphlit.CreateWorkflow(workflowInput); var workflowId = response.CreateWorkflow.Id; ``` -------------------------------- ### Create Discord Feed Source: https://docs.graphlit.dev/api-guides Provides instructions and code examples for creating a Discord feed. This allows integration with Discord channels to ingest messages or other relevant data. ```json { "feedName": "discordChannelFeed", "type": "discord", "channelId": "1234567890" } ``` -------------------------------- ### Multi-Repository Analysis Setup (TypeScript) Source: https://docs.graphlit.dev/api-guides/use-cases/knowledge-graph/knowledge-graph-from-github This TypeScript code snippet sets up the analysis of multiple GitHub repositories within an organization. It defines repositories, retrieves a GitHub token, creates feeds for each repository, and includes a mechanism to wait for all feeds to complete synchronization. ```typescript const repos = [ { owner: 'graphlit', name: 'graphlit-client-typescript' }, { owner: 'graphlit', name: 'graphlit-client-python' }, { owner: 'graphlit', name: 'graphlit-client-dotnet' } ]; const githubToken = process.env.GITHUB_TOKEN!; const feeds = await Promise.all( repos.map(repo => graphlit.createFeed({ name: `${repo.owner}/${repo.name}`, type: FeedTypes.Site, site: { type: FeedServiceTypes.GitHub, github: { repositoryOwner: repo.owner, repositoryName: repo.name, personalAccessToken: githubToken } }, workflow: { id: workflowId } }) ) ); // Wait for all to sync const waitForAll = async () => { let allDone = false; while (!allDone) { const statuses = await Promise.all( feeds.map(f => graphlit.isFeedDone(f.createFeed.id)) ); allDone = statuses.every(s => s.isFeedDone.result); if (!allDone) { await new Promise(resolve => setTimeout(resolve, 5000)); } } }; await waitForAll(); // Analyze cross-repo entities const allRepos = await graphlit.queryObservables({ filter: { types: [ObservableTypes.Repo] } }); console.log(`Total repositories: ${allRepos.observables.results.length}`); ``` -------------------------------- ### Basic Content Retrieval Source: https://docs.graphlit.dev/api-guides/use-cases/content/content-get A minimal example of retrieving the name of a content item using its ID with the GraphLit SDK. This is useful for quick checks or when only the name is needed. ```typescript const content = await graphlit.getContent(contentId); console.log(content.content.name); ``` -------------------------------- ### Build Network Graph Source: https://docs.graphlit.dev/api-guides/use-cases/knowledge-graph/observable-relationship-queries Provides a function to build a network graph (nodes and edges) starting from a given entity, traversing a specified depth. This is useful for visualizing relationships. ```APIDOC ## POST /queryContents (Network Graph Construction) ### Description Recursively traverses relationships starting from a given entity to build a network graph, including nodes and edges. ### Method POST ### Endpoint /queryContents ### Parameters #### Function Parameters (Conceptual) - **startEntityId** (string) - Required - The ID of the starting entity. - **startEntityType** (ObservableTypes) - Required - The type of the starting entity. - **depth** (number) - Optional - The maximum depth of traversal (default is 2). ### Internal API Calls (Conceptual) This function internally uses `graphlit.queryContents` to fetch related content and entities. ### Request Example (Conceptual Call to buildNetworkGraph) ```typescript const network = await buildNetworkGraph(personId, ObservableTypes.Person, 2); ``` ### Response #### Success Response (Conceptual) - **nodes** (array) - An array of network nodes. - **id** (string) - The node's unique identifier. - **name** (string) - The node's name. - **type** (string) - The node's type. - **edges** (array) - An array of network edges. - **source** (string) - The ID of the source node. - **target** (string) - The ID of the target node. - **weight** (number) - The weight of the edge (currently set to 1). ``` -------------------------------- ### Filter by Type and Date Range (TypeScript) Source: https://docs.graphlit.dev/api-guides/use-cases/content/content-metadata-filtering-strategies Example of filtering content by type (Email) and a creation date range starting from January 1, 2024, using TypeScript. ```typescript const emailsThisYear = await graphlit.queryContents({ types: [ContentTypes.Email], creationDateRange: { from: '2024-01-01' } }); ``` -------------------------------- ### Production Example: Complete PDF Preparation Pipeline Source: https://docs.graphlit.dev/api-guides/use-cases/workflows/workflow-create-preparation Demonstrates a full production pipeline for ingesting a PDF, preparing it with a high-quality vision model (GPT-4o), and extracting markdown content. It covers creating a specification, a workflow, ingesting a URI, and retrieving content. ```typescript // 1. Create vision specification const spec = await graphlit.createSpecification({ name: 'GPT-4o Vision', type: SpecificationTypes.Preparation, serviceType: ModelServiceTypes.OpenAi, openAI: { model: OpenAiModels.Gpt4O_128K } }); // 2. Create preparation workflow const workflow = await graphlit.createWorkflow({ name: 'PDF Preparation', preparation: { jobs: [{ connector: { type: FilePreparationServiceTypes.ModelDocument, modelDocument: { specification: { id: spec.createSpecification.id }, includeImages: true, includeTables: true } } }] } }); // 3. Ingest PDF with workflow const content = await graphlit.ingestUri( pdfUri, undefined, undefined, undefined, true, { id: workflow.createWorkflow.id } ); // 4. Get extracted markdown const result = await graphlit.getContent(content.ingestUri.id); console.log(result.content.markdown); // High-quality markdown ``` -------------------------------- ### Complete Code Example: Building Knowledge Graph from GitHub (TypeScript) Source: https://docs.graphlit.dev/api-guides/use-cases/knowledge-graph/knowledge-graph-from-github This TypeScript code demonstrates the full workflow of using the Graphlit client to ingest data from a GitHub repository and its issues. It covers creating workflows, setting up feeds, syncing data, querying content and entities, and performing basic analysis on the ingested data. Dependencies include the 'graphlit-client' library and a GitHub personal access token set as an environment variable (GITHUB_TOKEN). ```typescript import { Graphlit } from 'graphlit-client'; import { ContentTypes, EntityExtractionServiceTypes, EntityState, FeedServiceTypes, FeedTypes, ObservableTypes } from 'graphlit-client/dist/generated/graphql-types'; const graphlit = new Graphlit(); console.log('=== Building Knowledge Graph from GitHub ===\n'); // Step 1: Create extraction workflow console.log('Step 1: Creating entity extraction workflow...'); const workflow = await graphlit.createWorkflow({ name: "GitHub Entity Extraction", extraction: { jobs: [{ connector: { type: EntityExtractionServiceTypes.ModelText, extractedTypes: [ ObservableTypes.Repo, ObservableTypes.Person, ObservableTypes.Organization, ObservableTypes.Software, ObservableTypes.Category, ObservableTypes.Label ] } }] } }); console.log(`✓ Workflow: ${workflow.createWorkflow.id}\n`); // Step 2: Create GitHub repository feed console.log('Step 2: Creating GitHub repository feed...'); const repoFeed = await graphlit.createFeed({ name: "Graphlit Samples Repo", type: FeedTypes.Site, site: { type: FeedServiceTypes.GitHub, github: { repositoryOwner: 'graphlit', repositoryName: 'graphlit-samples', personalAccessToken: process.env.GITHUB_TOKEN! }, allowedPaths: ['README.md', 'docs/**', 'python/**', 'nextjs/**'], excludedPaths: ['**/node_modules/**', '**/dist/**'] }, workflow: { id: workflow.createWorkflow.id } }); console.log(`✓ Repo Feed: ${repoFeed.createFeed.id}\n`); // Step 3: Create GitHub issues feed console.log('Step 3: Creating GitHub issues feed...'); const issuesFeed = await graphlit.createFeed({ name: "Graphlit Issues", type: FeedTypes.Issue, issue: { type: FeedServiceTypes.GitHubIssues, github: { repositoryOwner: 'graphlit', repositoryName: 'graphlit-samples', personalAccessToken: process.env.GITHUB_TOKEN! }, readLimit: 100 }, workflow: { id: workflow.createWorkflow.id } }); console.log(`✓ Issues Feed: ${issuesFeed.createFeed.id}\n`); // Step 4: Wait for sync console.log('Step 4: Syncing repository...'); let repoDone = false; let issuesDone = false; while (!repoDone || !issuesDone) { if (!repoDone) { const repoStatus = await graphlit.isFeedDone(repoFeed.createFeed.id); repoDone = repoStatus.isFeedDone.result; } if (!issuesDone) { const issuesStatus = await graphlit.isFeedDone(issuesFeed.createFeed.id); issuesDone = issuesStatus.isFeedDone.result; } if (!repoDone || !issuesDone) { console.log(' Syncing... (checking again in 5s)'); await new Promise(resolve => setTimeout(resolve, 5000)); } } console.log('✓ Sync complete\n'); // Step 5: Query repository content console.log('Step 5: Querying repository files...'); const repoFiles = await graphlit.queryContents({ types: [ContentTypes.File], feeds: [{ id: repoFeed.createFeed.id }] }); console.log(`✓ Synced ${repoFiles.contents.results.length} files\n`); // Step 6: Query issues console.log('Step 6: Querying issues...'); const issues = await graphlit.queryContents({ types: [ContentTypes.Issue], feeds: [{ id: issuesFeed.createFeed.id }] }); console.log(`✓ Synced ${issues.contents.results.length} issues\n`); // Step 7: Extract repository entities console.log('Step 7: Analyzing repository entities...\n'); // Get all Repo entities const repos = await graphlit.queryObservables({ filter: { types: [ObservableTypes.Repo] } }); console.log(`Repositories: ${repos.observables.results.length}`); // Get contributors (Person entities) const people = await graphlit.queryObservables({ filter: { types: [ObservableTypes.Person] } }); console.log(`Contributors: ${people.observables.results.length}`); // Get dependencies (Software entities) const software = await graphlit.queryObservables({ filter: { types: [ObservableTypes.Software] } }); console.log(`Software/Dependencies: ${software.observables.results.length}\n`); // Step 8: Analyze issue labels console.log('Step 8: Analyzing issue labels...\n'); const labelCounts = new Map(); issues.contents.results.forEach(issue => { (issue.issue?.labels || []).filter(Boolean).forEach(label => { labelCounts.set(label!, (labelCounts.get(label!) || 0) + 1); }); }); console.log('Most common issue labels:'); Array.from(labelCounts.entries()) .sort((a, b) => b[1] - a[1]) .slice(0, 5) .forEach(([label, count]) => { console.log(` ${label}: ${count} issues`); }); // Step 9: Build contributor network console.log('\nStep 9: Building contributor network...\n'); const contributors = new Map(); // Count files by contributor (from observations) repoFiles.contents.results.forEach(file => { file.observations ?.filter(Boolean) ``` -------------------------------- ### Retrieve Basic Feed Information Source: https://docs.graphlit.dev/api-guides/use-cases/feeds/feed-get-details A simple example to retrieve a feed by its ID and log its name. This is a fundamental operation for accessing feed details. Requires the 'graphlit-client' library. ```typescript const feed = await graphlit.getFeed(feedId); console.log(feed.feed.name); ``` -------------------------------- ### Project Setup and Dependencies Source: https://docs.graphlit.dev/examples/deep-research/mastra Installs necessary project dependencies using pnpm for a deep research project. Includes core libraries for Graphlit, AI SDK, and development tools. ```bash mkdir deep-research && cd deep-research pnpm init -y pnpm add @mastra/core @ai-sdk/openai graphlit-client zod dotenv pnpm add -D typescript tsx pnpm add chalk ora boxen cli-table3 gradient-string ``` -------------------------------- ### Install uv Package Manager (Bash) Source: https://docs.graphlit.dev/examples/deep-research/agno Installs the uv package manager, a faster alternative to pip, using a curl script. This is the recommended method for setting up the project environment. ```bash curl -LsSf https://astral.sh/uv/install.sh | sh ``` -------------------------------- ### Build Network Graph (TypeScript) Source: https://docs.graphlit.dev/api-guides/use-cases/knowledge-graph/observable-relationship-queries Constructs a network graph representing relationships between entities, starting from a given entity and traversing a specified depth. It returns a list of nodes and edges suitable for visualization. ```typescript interface NetworkNode { id: string; name: string; type: string; } interface NetworkEdge { source: string; target: string; weight: number; } async function buildNetworkGraph( startEntityId: string, startEntityType: ObservableTypes, depth: number = 2 ): Promise<{ nodes: NetworkNode[]; edges: NetworkEdge[] }> { const nodes = new Map(); const edges: NetworkEdge[] = []; const visited = new Set(); async function traverse(entityId: string, entityType: ObservableTypes, currentDepth: number) { if (currentDepth > depth || visited.has(entityId)) return; visited.add(entityId); // Get content mentioning this entity const content = await graphlit.queryContents({ observations: [{ type: entityType, observable: { id: entityId } }] }); // Extract all other entities from that content content.contents.results.forEach(item => { item.observations?.forEach(obs => { // Add node if (!nodes.has(obs.observable.id)) { nodes.set(obs.observable.id, { id: obs.observable.id, name: obs.observable.name, type: obs.type }); } // Add edge if (obs.observable.id !== entityId) { edges.push({ source: entityId, target: obs.observable.id, weight: 1 }); } // Recursively traverse if (currentDepth < depth) { traverse(obs.observable.id, obs.type, currentDepth + 1); } }); }); } await traverse(startEntityId, startEntityType, 0); return { nodes: Array.from(nodes.values()), edges }; } // Build 2-hop network from person const network = await buildNetworkGraph(personId, ObservableTypes.Person, 2); console.log(`Network: ${network.nodes.length} nodes, ${network.edges.length} edges`); // Export for visualization (D3.js, Cytoscape, etc.) fs.writeFileSync('network.json', JSON.stringify(network, null, 2)); ``` -------------------------------- ### Initializing Agno Agent with Tools and FastAPI Server Source: https://docs.graphlit.dev/examples/deep-research/agno Demonstrates how to initialize an Agno agent with a list of tools and access its built-in FastAPI server. This showcases Agno's integrated web server capabilities for deploying agents. ```python from agno.agent import Agent agent = Agent(tools=[...]) agent.app # Built-in FastAPI server! ``` -------------------------------- ### Manage Multi-Turn Conversations in TypeScript Source: https://docs.graphlit.dev/api-guides/use-cases/conversations/conversation-stream-agent-real-time-ui This example shows how to maintain conversation context across multiple turns using a `conversationId`. The ID is stored when the conversation starts and passed in subsequent calls to `streamAgent`. ```typescript // Store conversation ID across turns let conversationId: string | undefined; // First message await graphlit.streamAgent( 'What is quantum computing?', async (event) => { if (event.type === 'conversation_started') { conversationId = event.conversationId; // Store for next turn } // ... handle other events } ); // Second message (with context from first) await graphlit.streamAgent( 'Can you give an example?', async (event) => { // ... handle events }, conversationId // Same conversation = has context ); ``` -------------------------------- ### Manage Collections and Query Content (TypeScript) Source: https://docs.graphlit.dev/platform/key-concepts This TypeScript example demonstrates creating a collection, ingesting a document into that collection, and then querying for content within that specific collection using the Graphlit client library. It highlights the workflow for organizing and retrieving data by collection. ```typescript import { Graphlit } from 'graphlit-client'; const graphlit = new Graphlit(); // Create collection const collResponse = await graphlit.createCollection({ name: "Acme Corp" }); const collection = collResponse.createCollection; // Add content during ingestion const ingestResponse = await graphlit.ingestUri( "https://example.com/acme-doc.pdf", undefined, undefined, undefined, false, undefined, [{ id: collection.id }] ); const content = ingestResponse.ingestUri; // Query by collection const queryResponse = await graphlit.queryContents({ collections: [{ id: collection.id }] }); const results = queryResponse.queryContents?.results; ``` -------------------------------- ### Configure Optional LLM API Keys for TypeScript Streaming Source: https://docs.graphlit.dev/account-setup-one-time/credentials Configure optional environment variables for LLM API keys if you are using the `streamAgent()` function in TypeScript for real-time responses. This snippet shows examples for OpenAI, Anthropic, and Google. ```env # Use the API key for your chosen LLM provider OPENAI_API_KEY=your_openai_key # OR ANTHROPIC_API_KEY=your_anthropic_key # OR GOOGLE_API_KEY=your_google_key # (etc.) ``` -------------------------------- ### Real-Time Streaming with Graphlit SDK (TypeScript) Source: https://docs.graphlit.dev/getting-started/quickstart This snippet shows how to enable real-time streaming of AI responses using the Graphlit SDK in TypeScript. It requires setting up an OpenAI API key and configuring the SDK to use the OpenAI client for streaming. ```env OPENAI_API_KEY=your_openai_key ``` ```typescript import { Graphlit } from 'graphlit-client'; import { OpenAI } from 'openai'; import { SpecificationTypes, ModelServiceTypes, OpenAiModels, } from 'graphlit-client/dist/generated/graphql-types'; const graphlit = new Graphlit(); // Enable streaming with OpenAI client graphlit.setOpenAIClient(new OpenAI()); async function main() { const spec = await graphlit.createSpecification({ name: 'Assistant', type: SpecificationTypes.Completion, serviceType: ModelServiceTypes.OpenAi, openAI: { model: OpenAiModels.Gpt4O_128K, temperature: 0.7 } }); await graphlit.streamAgent( 'Explain transformer attention in simple terms', (event) => { if (event.type === 'message_update') { process.stdout.write(event.message.message); if (!event.isStreaming) { console.log('\n[complete]'); } } }, undefined, { id: spec.createSpecification.id }, ); } main(); ``` -------------------------------- ### Query Knowledge Graph - C# Source: https://docs.graphlit.dev/api-guides/use-cases/knowledge-graph/observable-query-graph Queries the knowledge graph using the `Graphlit` client in C#. It shows how to retrieve nodes and edges for a specific content ID or the entire graph. This example assumes the Graphlit SDK for C# is installed. ```csharp using Graphlit; var client = new Graphlit(); // Query knowledge graph (PascalCase) var graphResponse = await graphlit.QueryContentsGraph(new ContentFilter { Contents = new[] { new EntityReferenceFilter { Id = contentId } } }); Console.WriteLine($"Nodes: {graphResponse.Graph.Nodes?.Count ?? 0}"); Console.WriteLine($"Edges: {graphResponse.Graph.Edges?.Count ?? 0}"); // Access nodes foreach (var node in graphResponse.Graph.Nodes ?? new List()) { Console.WriteLine($"{node.Type}: {node.Name}"); } // Access edges foreach (var edge in graphResponse.Graph.Edges ?? new List()) { Console.WriteLine($"{edge.From} → {edge.Type} → {edge.To}"); } ``` -------------------------------- ### Create Workflow with Vision Model (.NET) Source: https://docs.graphlit.dev/platform/key-concepts Demonstrates how to create a workflow for document analysis using C# and the Graphlit client library. It configures the workflow for OCR and entity extraction via vision models, specifying the required input parameters. ```csharp using GraphlitClient; using System.Net.Http; using StrawberryShake; using var httpClient = new HttpClient(); var client = new Graphlit(httpClient); // Create workflow with vision model for OCR and entity extraction var input = new WorkflowInput( name: "PDF with Vision", preparation: new PreparationWorkflowStageInput( jobs: new[] { new PreparationWorkflowJobInput( connector: new FilePreparationConnectorInput( type: FilePreparationServiceTypes.ModelDocument ) ) } ), extraction: new ExtractionWorkflowStageInput( jobs: new[] { new ExtractionWorkflowJobInput( connector: new EntityExtractionConnectorInput( type: EntityExtractionServiceTypes.ModelText ) ) } ) ); var response = await client.CreateWorkflow.ExecuteAsync(input); response.EnsureNoErrors(); var workflow = response.Data?.CreateWorkflow; ``` -------------------------------- ### Define and Use a Tool for AI Agent in TypeScript Source: https://docs.graphlit.dev/getting-started/quickstart This snippet demonstrates how to define a tool for an AI agent, implement its handler, and integrate it into the agent's functionality using the Graphlit TypeScript SDK. It sets up a 'search_memory' tool that queries semantic memory and shows how the agent can call this tool and process its results. Dependencies include 'graphlit-client' and 'openai'. ```typescript import { Graphlit } from 'graphlit-client'; import { OpenAI } from 'openai'; import { SpecificationTypes, ModelServiceTypes, OpenAiModels, ToolDefinitionInput, } from 'graphlit-client/dist/generated/graphql-types'; const graphlit = new Graphlit(); graphlit.setOpenAIClient(new OpenAI()); // Define tool const searchTool: ToolDefinitionInput = { name: 'search_memory', description: 'Search semantic memory for documents', schema: JSON.stringify({ type: 'object', properties: { query: { type: 'string', description: 'Search query' }, }, required: ['query'], }), }; // Tool implementation const toolHandlers = { search_memory: async (args: { query: string }) => { const results = await graphlit.queryContents({ search: args.query }); return results.contents.results.map((c) => c.name); }, }; async function main() { const spec = await graphlit.createSpecification({ name: 'Agent with Tools', type: SpecificationTypes.Completion, serviceType: ModelServiceTypes.OpenAi, openAI: { model: OpenAiModels.Gpt4O_128K } }); await graphlit.streamAgent( 'Find documents about attention mechanisms', (event) => { if (event.type === 'tool_update' && event.status === 'completed') { console.log(`\n🔧 Called ${event.toolCall.name}`); } else if (event.type === 'message_update') { process.stdout.write(event.message.message); if (!event.isStreaming) { console.log('\n[complete]'); } } }, undefined, { id: spec.createSpecification.id }, [searchTool], toolHandlers, ); } main(); ``` -------------------------------- ### Base64 Encoding Guide for Files Source: https://docs.graphlit.dev/api-guides/use-cases/content/content-ingest-encoded-file Demonstrates how to encode file data into a Base64 string for use with Graphlit's `ingestEncodedFile` method. Provides examples for both Node.js environments using the 'fs' module and browser environments using the FileReader API. ```typescript // Node.js (filesystem) import { readFileSync } from 'fs'; const buffer = readFileSync('file.pdf'); const base64 = buffer.toString('base64'); // Browser (File input) const file = input.files?.[0]; const base64 = await new Promise((resolve) => { const reader = new FileReader(); reader.onload = () => resolve((reader.result as string).split(',')[1]); reader.readAsDataURL(file); }); ``` -------------------------------- ### Cloning Repository and Running Agno Deep Research Source: https://docs.graphlit.dev/examples/deep-research/agno Provides bash commands to clone the Agno deep research sample repository, install dependencies using uv, set up environment variables, and run the main script with a search query. This is the primary method for trying out the deep research agent. ```bash git clone https://github.com/graphlit/graphlit-samples.git cd graphlit-samples/python/agno-deep-research uv sync cp .env.example .env # Add credentials uv run python -m deep_research.main --search "your query" ``` -------------------------------- ### Vercel AI Gateway Model Examples Source: https://docs.graphlit.dev/api-guides/use-cases/specifications/specification-create-openai-compatible Illustrates using different models with the Vercel AI Gateway, including an example of Claude with caching. ```APIDOC ## POST /specifications ### Description Creates a new AI model specification, demonstrating the use of specific models like Claude with caching enabled via the Vercel AI Gateway. ### Method POST ### Endpoint /specifications #### Query Parameters None #### Request Body - **name** (string) - Required - A descriptive name for the specification. - **type** (enum) - Required - The type of specification, e.g., `Completion`. - **serviceType** (enum) - Required - The service type, e.g., `OpenAi`. - **openAI** (object) - Required - Configuration for the OpenAI compatible service. - **model** (enum) - Required - The model type, use `Custom` for external endpoints. - **endpoint** (string) - Required - The Vercel AI Gateway endpoint URL. - **key** (string) - Required - Your Vercel AI Gateway API key or OIDC token. - **modelName** (string) - Required - The specific model to use (e.g., `anthropic/claude-sonnet-4`). - **temperature** (float) - Optional - Controls randomness. Lower values make output more focused. - **completionTokenLimit** (integer) - Optional - The maximum number of tokens for the completion. ### Request Example ```typescript const cachedClaudeSpec = await graphlit.createSpecification({ name: 'Cached Claude via Vercel', type: SpecificationTypes.Completion, serviceType: ModelServiceTypes.OpenAi, openAI: { model: OpenAiModels.Custom, endpoint: 'https://ai-gateway.vercel.sh/v1', key: process.env.VERCEL_AI_GATEWAY_KEY, modelName: 'anthropic/claude-sonnet-4', temperature: 0.1, completionTokenLimit: 3000 } }); // Repeated queries are cached automatically by Vercel ``` ### Response #### Success Response (200) - **createSpecification** (object) - Contains the details of the created specification. - **id** (string) - The unique identifier for the created specification. #### Response Example ```json { "createSpecification": { "id": "spec_67890fghij" } } ``` ``` -------------------------------- ### Update Content Metadata using TypeScript Source: https://docs.graphlit.dev/api-guides/use-cases/content/content-update-metadata This example demonstrates how to update content metadata using the `updateContent()` method from the `graphlit-client` SDK. It shows how to modify the content's name and custom metadata fields. Ensure the `graphlit-client` library is installed and initialized. ```typescript import { Graphlit } from 'graphlit-client'; const graphlit = new Graphlit(); // Update content await graphlit.updateContent({ id: 'content-id', name: "Updated Document Name", customMetadata: { category: "financial-reports", quarter: "Q4-2024", reviewed: true } }); console.log('Content updated'); ```