### Install Dependencies and Start React App Source: https://github.com/hypermodeinc/docs/blob/main/dgraph/guides/message-board-app/react-ui/react-app-boiler-plate.mdx Install project dependencies using yarn and start the React development server. The app is typically served at http://localhost:3000, but the port may vary. ```sh yarn install yarn start ``` -------------------------------- ### Install Badger Go Library Source: https://github.com/hypermodeinc/docs/blob/main/badger/quickstart.mdx Run this command to get the Badger library for your Go project. ```sh go get github.com/dgraph-io/badger/v4 ``` -------------------------------- ### Install and Create Modus Project Source: https://context7.com/hypermodeinc/docs/llms.txt Installs the Modus CLI, creates a new project, and starts the local development server. Also includes commands for installing and logging into the Hyp CLI for Hypermode-hosted models. ```bash # Install Modus CLI npm install -g @hypermode/modus-cli # Create a new Modus app (choose Go or AssemblyScript) modus new # Start local development server modus dev # Install Hyp CLI for Hypermode-hosted models npm install -g @hypermode/hyp-cli # Authenticate with Hypermode hyp login ``` -------------------------------- ### Start Dgraph Servers with Encryption Source: https://github.com/hypermodeinc/docs/blob/main/dgraph/enterprise/encryption-at-rest.mdx This example shows how to start Dgraph Zero and Alpha servers with encryption enabled using a local key file. Ensure the key file path is correct. If using multiple Alpha nodes, apply the --encryption flag to each. ```bash dgraph zero --my="localhost:5080" --replicas 1 --raft "idx=1" dgraph alpha --encryption key-file="./enc_key_file" --my="localhost:7080" --zero="localhost:5080" ``` -------------------------------- ### Example: Start Dgraph Zero and Alpha with ACL (CLI) Source: https://github.com/hypermodeinc/docs/blob/main/dgraph/enterprise/access-control-lists.mdx Demonstrates starting Dgraph Zero and Alpha nodes using the command line with ACL enabled. This requires creating the HMAC secret file first and running each command in a separate terminal. ```sh ## Create ACL secret key file with 32 ASCII characters echo '' > hmac_secret_file ## Start Dgraph Zero in different terminal tab or window dgraph zero --my=localhost:5080 --replicas 1 --raft idx=1 ## Start Dgraph Alpha in different terminal tab or window dgraph alpha --my=localhost:7080 --zero=localhost:5080 \ --acl secret-file="./hmac_secret_file" \ --security whitelist="10.0.0.0/8,172.0.0.0/8,192.168.0.0/16" ``` -------------------------------- ### Import PostgreSQL Package Source: https://github.com/hypermodeinc/docs/blob/main/modus/sdk/go/postgresql.mdx Import the PostgreSQL package to start using its functionalities. This is the initial setup step for interacting with PostgreSQL databases. ```go import "github.com/hypermodeinc/modus/sdk/go/pkg/postgresql" ``` -------------------------------- ### Create React App Source: https://github.com/hypermodeinc/docs/blob/main/dgraph/guides/to-do-app/ui.mdx Use create-react-app to scaffold a new React project. Navigate into the project directory and start the development server to verify the setup. ```sh npx create-react-app todo-react-app ``` ```sh cd todo-react-app npm start ``` -------------------------------- ### Install Mintlify CLI Source: https://github.com/hypermodeinc/docs/blob/main/README.md Install the Mintlify CLI globally to preview documentation changes locally. ```sh npm i -g mintlify ``` -------------------------------- ### Install Badger CLI Utility Source: https://github.com/hypermodeinc/docs/blob/main/badger/quickstart.mdx Install the Badger command line utility into your GOBIN path. ```sh go install github.com/dgraph-io/badger/v4/badger@latest ``` -------------------------------- ### Install Dgraph Go Client Source: https://github.com/hypermodeinc/docs/blob/main/dgraph/sdks/go.mdx Installs the Dgraph Go client using go get. Ensure GO111MODULE is set to 'on' and requires Go 1.23 or later. ```sh Requires at least Go 1.23 export GO111MODULE=on go get -u -v github.com/dgraph-io/dgo/v240 ``` -------------------------------- ### Run Dgraph All-in-One Docker Image Source: https://github.com/hypermodeinc/docs/blob/main/dgraph/graphql/api.mdx Use this command to quickly start a Dgraph instance with GraphQL enabled. This is intended for quickstarts and does not persist data. ```bash docker run -it -p 8080:8080 dgraph/standalone:%VERSION_HERE ``` -------------------------------- ### Start Development Server Source: https://github.com/hypermodeinc/docs/blob/main/dgraph/guides/to-do-app/auth0-jwt.mdx Command to start the Node.js development server for the frontend application. ```bash npm start ``` -------------------------------- ### MCP Server Search Tool Call Example Source: https://github.com/hypermodeinc/docs/blob/main/hypermode-docs-mcp.mdx This is an example of how to call the 'search' tool provided by the Hypermode docs MCP server. Use this tool to find relevant information, code examples, API references, and guides within the Hypermode documentation. The 'query' parameter is required. ```json { "name": "search", "arguments": { "query": "DQL query examples" } } ``` -------------------------------- ### Clone and Checkout Boilerplate React App Source: https://github.com/hypermodeinc/docs/blob/main/dgraph/guides/message-board-app/react-ui/react-app-boiler-plate.mdx Clone the tutorial repository and checkout the 'tutorial-boilerplate' tag to get the initial React app setup. This command fetches all tags and checks out the specified tag into a new branch. ```sh git clone https://github.com/dgraph-io/discuss-tutorial cd discuss-tutorial git fetch --all --tags git checkout tags/tutorial-boilerplate -b learn-tutorial ``` -------------------------------- ### Example Interaction Prompt Source: https://github.com/hypermodeinc/docs/blob/main/agents/30-days-of-agents/day-1.mdx Use this prompt to guide Sidekick in personalizing its approach based on your interactions. This helps tailor future responses to your work style and interests. ```text Based on our interactions today, what do you think I should focus on learning about agents? What seems most relevant to my work style and interests? ``` -------------------------------- ### Install kubectl with Chocolatey on Windows Source: https://github.com/hypermodeinc/docs/blob/main/dgraph/self-managed/managed-kubernetes.mdx Install the Kubernetes CLI (kubectl) on Windows using the Chocolatey package manager. This simplifies the installation process. ```bash choco install kubernetes-cli ``` -------------------------------- ### Install eksctl and kubectl on AWS Source: https://github.com/hypermodeinc/docs/blob/main/dgraph/self-managed/managed-kubernetes.mdx Install the eksctl command-line tool for managing Amazon EKS clusters, which includes the installation of kubectl. ```bash # Install eksctl (EKS CLI) curl --silent --location "https://github.com/weaveworks/eksctl/releases/latest/download/eksctl_$(uname -s)_amd64.tar.gz" | tar xz -C /tmp sudo mv /tmp/eksctl /usr/local/bin # kubectl is automatically installed with eksctl ``` -------------------------------- ### Install Trunk CLI Source: https://github.com/hypermodeinc/docs/blob/main/README.md Install the Trunk CLI globally for formatting and linting code changes. ```sh npm i -g @trunkio/launcher ``` -------------------------------- ### Install Project Dependencies Source: https://github.com/hypermodeinc/docs/blob/main/dgraph/guides/to-do-app/ui.mdx Install the required npm packages for the to-do app, including CSS for styling and libraries for routing and GraphQL. ```sh npm install todomvc-app-css classnames graphql-tag history react-router-dom ``` -------------------------------- ### Agent Implementation Example Source: https://github.com/hypermodeinc/docs/blob/main/modus/sdk/assemblyscript/agents.mdx Example of implementing a simple counter agent with event streaming. ```APIDOC ### Agent Implementation ```typescript import { Agent, AgentEvent } from "@hypermode/modus-sdk-as" export class CounterAgent extends Agent { get name(): string { return "Counter" } private count: i32 = 0 getState(): string | null { return this.count.toString() } setState(data: string | null): void { if (data == null) { return } this.count = i32.parse(data) } onInitialize(): void { console.info("Counter agent started") } onReceiveMessage(name: string, data: string | null): string | null { if (name == "count") { return this.count.toString() } if (name == "increment") { if (data != null) { this.count += i32.parse(data) } else { this.count++ } // Publish an event to subscribers this.publishEvent(new CountUpdated(this.count)) return this.count.toString() } return null } } // Custom event for count updates @json class CountUpdated extends AgentEvent { constructor(public count: i32) { super("countUpdated") } } ``` ``` -------------------------------- ### Start Dgraph Zero for Vault Integration Source: https://github.com/hypermodeinc/docs/blob/main/dgraph/enterprise/encryption-at-rest.mdx This command starts a Dgraph Zero server, which is a prerequisite for starting Dgraph Alpha servers configured to use HashiCorp Vault for encryption keys. ```bash dgraph zero --my=localhost:5080 --replicas 1 --raft "idx=1" ``` -------------------------------- ### Start Binary Backup Source: https://github.com/hypermodeinc/docs/blob/main/dgraph/graphql/api.mdx Starts a binary backup of the Dgraph cluster. Refer to the documentation for details on creating backups. ```graphql mutation { backup(input: BackupInput!) { BackupPayload } } ``` -------------------------------- ### lsbackup Examples Source: https://github.com/hypermodeinc/docs/blob/main/dgraph/enterprise/lsbackup.mdx Practical examples demonstrating how to use the `lsbackup` command with different storage providers like S3, MinIO, and local file systems. ```APIDOC ### Examples #### S3 Example Checking information about backups stored in an AWS S3 bucket: ```sh dgraph lsbackup -l s3:///s3.west-2.amazonaws.com/dgraph_backup ``` *Note: You may need to set AWS access and secret key environment variables.* #### MinIO Example Checking information about backups stored in a MinIO bucket: ```sh dgraph lsbackup -l "minio://localhost:9000/?secure=false" ``` *Note: Ensure `MINIO_ACCESS_KEY` and `MINIO_SECRET_KEY` environment variables are set. Use `secure=false` if TLS is not enabled on the MinIO server.* #### Local Example Checking information about backups stored locally on disk: ```sh dgraph lsbackup -l ~/dgraph_backup ``` ``` -------------------------------- ### Install Project Dependencies Source: https://github.com/hypermodeinc/docs/blob/main/getting-started-with-hyper-commerce.mdx Installs necessary Python packages for the project. Ensure you are in the project directory before running. ```sh pip install -r requirements.txt ``` -------------------------------- ### Dgraph Query Example Source: https://github.com/hypermodeinc/docs/blob/main/dgraph/concepts/queries-process.mdx This is an example of a Dgraph query. It specifies the starting UID and the relationships to traverse, including nested relationships. ```graphql { me(func: uid(0x1)) { rel_A rel_B { rel_B1 rel_B2 } rel_C { rel_C1 rel_C2 { rel_C2_1 } } } } ``` -------------------------------- ### Initialize Dgraph Clients in Go Source: https://github.com/hypermodeinc/docs/blob/main/agents/30-days-of-agents/day-22.mdx Demonstrates creating Dgraph clients for both local development and production environments. Ensure correct connection strings and SSL configuration for production. ```go localAgent, err := NewNewsGraphClient("dgraph://localhost:9080") if err != nil { log.Fatal("Failed to create local client:", err) } // Production with SSL prodAgent, err := NewNewsGraphClient("dgraph://dgraph.example.com:443?ssl=true") if err != nil { log.Fatal("Failed to create production client:", err) } ``` -------------------------------- ### Example JSON Config (Snake_Case) Source: https://github.com/hypermodeinc/docs/blob/main/dgraph/self-managed/config.mdx An example of a JSON configuration file using snake_case for keys. This format is an alternative to kebab-case. ```json { "badger": { "compression": "zstd:1" }, "trace": { "jaeger": "http://jaeger:14268" }, "security": { "whitelist": "10.0.0.0/8,172.0.0.0/8,192.168.0.0/16" }, "tls": { "ca_cert": "/dgraph/tls/ca.crt", "client_auth_type": "REQUIREANDVERIFY", "server_cert": "/dgraph/tls/node.crt", "server_key": "/dgraph/tls/node.key", "use_system_ca": true, "internal_port": true, "client_cert": "/dgraph/tls/client.dgraphuser.crt", "client_key": "/dgraph/tls/client.dgraphuser.key" } } ``` -------------------------------- ### Start Local Mintlify Server Source: https://github.com/hypermodeinc/docs/blob/main/README.md Run this command in the root of the docs repository to spin up a local development server for previewing documentation. ```sh mintlify dev ``` -------------------------------- ### Urql Client Setup with Subscriptions Source: https://github.com/hypermodeinc/docs/blob/main/dgraph/graphql/subscriptions.mdx Instantiate a urql client with a subscriptionExchange using a SubscriptionClient. Ensure to configure connection parameters for authentication. ```javascript import { Client, Provider, cacheExchange, fetchExchange, subscriptionExchange, } from "urql" import { SubscriptionClient } from "subscriptions-transport-ws" const subscriptionClient = new SubscriptionClient( process.env.REACT_APP_DGRAPH_WSS, { reconnect: true, connectionParams: { "X-Dgraph-AuthToken": props.token } }, ) const client = new Client({ url: process.env.REACT_APP_DGRAPH_ENDPOINT, fetchOptions: { headers: { "X-Dgraph-AuthToken": `Bearer ${props.token}` } }, exchanges: [ cacheExchange, fetchExchange, subscriptionExchange({ forwardSubscription: (request) => subscriptionClient.request(request), }), ], }) ``` -------------------------------- ### Start Dgraph Standalone Source: https://github.com/hypermodeinc/docs/blob/main/dgraph/guides/to-do-app/schema-design.mdx Command to start a Dgraph standalone instance using Docker. Ensure Docker is installed and replace %VERSION_HERE% with the desired Dgraph version. ```sh docker run -it -p 8080:8080 dgraph/standalone:%VERSION_HERE% ``` -------------------------------- ### Start Docker Compose for Dgraph with ACL Source: https://github.com/hypermodeinc/docs/blob/main/dgraph/enterprise/access-control-lists.mdx Starts the Docker Compose setup for Dgraph with ACL enabled. Ensure the HMAC secret file is created before running this command. ```sh ## Create ACL secret key file with 32 ASCII characters echo '' > hmac_secret_file ## Start Docker Compose docker-compose up ``` -------------------------------- ### Setup Apollo Client Source: https://github.com/hypermodeinc/docs/blob/main/dgraph/guides/to-do-app/ui.mdx Install Apollo Client dependencies and configure an ApolloClient instance with your GraphQL API endpoint. This setup enables data fetching and mutations within the React application. ```sh npm install @apollo/react-hooks apollo-cache-inmemory apollo-client apollo-link-http graphql apollo-link-context react-todomvc @auth0/auth0-react ``` ```javascript import React from "react" import ApolloClient from "apollo-client" import { InMemoryCache } from "apollo-cache-inmemory" import { ApolloProvider } from "@apollo/react-hooks" import { createHttpLink } from "apollo-link-http" import "./App.css" const createApolloClient = () => { const httpLink = createHttpLink({ uri: "http://localhost:8080/graphql", options: { reconnect: true, }, }) return new ApolloClient({ link: httpLink, cache: new InMemoryCache(), }) } const App = () => { const client = createApolloClient() return (

todos

) } export default App ``` -------------------------------- ### Initialize and Configure Badger Stream Source: https://github.com/hypermodeinc/docs/blob/main/badger/quickstart.mdx Demonstrates how to initialize a new stream, set optional configurations like the number of goroutines, key prefix, and logging prefix. It also shows how to define custom functions for choosing keys and converting values. ```go stream := db.NewStream() // db.NewStreamAt(readTs) for managed mode. // -- Optional settings stream.NumGo = 16 // Set number of goroutines to use for iteration. stream.Prefix = []byte("some-prefix") // Leave nil for iteration over the whole DB. stream.LogPrefix = "Badger.Streaming" // For identifying stream logs. Outputs to Logger. // ChooseKey is called concurrently for every key. If left nil, assumes true by default. stream.ChooseKey = func(item *badger.Item) bool { return bytes.HasSuffix(item.Key(), []byte("er")) } // KeyToList is called concurrently for chosen keys. This can be used to convert // Badger data into custom key-values. If nil, uses stream.ToList, a default // implementation, which picks all valid key-values. stream.KeyToList = nil // -- End of optional settings. // Send is called serially, while Stream.Orchestrate is running. stream.Send = func(list *pb.KVList) error { return proto.MarshalText(w, list) // Write to w. } // Run the stream if err := stream.Orchestrate(context.Background()); err != nil { return err } // Done. ``` -------------------------------- ### Start Agent Instance in Go Source: https://github.com/hypermodeinc/docs/blob/main/modus/sdk/go/agents.mdx Create and start a new agent instance by providing its name. The name must match the Name() method returned by the agent implementation. ```Go func Start(agentName string) (AgentInfo, error) ``` -------------------------------- ### GraphQL Mutations and Queries for Agent Control Source: https://github.com/hypermodeinc/docs/blob/main/modus/sdk/go/agents.mdx Demonstrates GraphQL operations for managing agents, including starting, getting counts, incrementing, and asynchronous updates. Use agent IDs obtained from starting or listing agents. ```graphql # Start a new agent mutation { startCounterAgent { id name status } } # Get the current count query { getCount(agentId: "agent_abc123") } # Increment the count mutation { updateCount(agentId: "agent_abc123") } # Increment asynchronously mutation { updateCountAsync(agentId: "agent_abc123", qty: 5) } # Subscribe to real-time events subscription { agentEvent(agentId: "agent_abc123") { name data timestamp } } ``` -------------------------------- ### Set up Google Cloud Project and Enable APIs Source: https://github.com/hypermodeinc/docs/blob/main/dgraph/self-managed/cloud-run.mdx Configure your Google Cloud project and enable necessary services for Dgraph deployment. Ensure your project ID is set. ```bash # Set your project ID export PROJECT_ID="your-project-id" gcloud config set project $PROJECT_ID # Enable required APIs gcloud services enable run.googleapis.com gcloud services enable containerregistry.googleapis.com gcloud services enable cloudbuild.googleapis.com gcloud services enable file.googleapis.com gcloud services enable vpcaccess.googleapis.com ``` -------------------------------- ### Agent Event: Mission Started Source: https://github.com/hypermodeinc/docs/blob/main/modus/agents.mdx Example JSON payload for an 'mission_started' agent event, including mission details and priority. ```json { "data": { "agentEvent": { "name": "mission_started", "data": { "missionName": "Deep Matrix Surveillance", "priority": "HIGH", "estimatedDuration": "180s" }, "timestamp": "2025-06-04T14:30:00Z" } } } ``` -------------------------------- ### Get Graph Schema Response Source: https://github.com/hypermodeinc/docs/blob/main/graphs/graph-mcp.mdx This is an example response from the `get_schema` tool, detailing the predicates, their types, and indexing information for your graph database. ```json { "schema": [ { "predicate": "account_number", "type": "string", "index": true, "tokenizer": ["exact"] }, { "predicate": "balance", "type": "float" }, { "predicate": "amount", "type": "float" }, { "predicate": "status", "type": "string", "index": true, "tokenizer": ["exact"] }, { "predicate": "from_account", "type": "uid" }, { "predicate": "to_account", "type": "uid" } ] } ``` -------------------------------- ### Main function to run example usage Source: https://github.com/hypermodeinc/docs/blob/main/agents/30-days-of-agents/day-22.mdx The main entry point for the Go program, which calls the ExampleUsage function to demonstrate Dgraph client operations. ```go func main() { ExampleUsage() } ``` -------------------------------- ### Aggregation: Basic Count Source: https://github.com/hypermodeinc/docs/blob/main/agents/30-days-of-agents/day-22.mdx Perform a basic count aggregation to get the total number of nodes of a specific type. This example counts all articles. ```graphql { total_articles(func: type(Article)) { count(uid) } } ``` -------------------------------- ### Install Dgraph on Linux Source: https://github.com/hypermodeinc/docs/blob/main/dgraph/self-managed/linux.mdx Download and install the Dgraph binary, move it to the system path, create a dedicated 'dgraph' user, and set up the necessary directories for data and logs. Ensure the directories are owned by the 'dgraph' user. ```bash # Download and install Dgraph (run on all nodes) curl -sSf https://get.dgraph.io | bash # Move to system path sudo mv dgraph /usr/local/bin/ # Create dgraph user sudo useradd -r -s /bin/false dgraph # Create directories sudo mkdir -p /opt/dgraph/{data,logs} sudo chown -R dgraph:dgraph /opt/dgraph ``` -------------------------------- ### Example YAML Config (Kebab-Case) Source: https://github.com/hypermodeinc/docs/blob/main/dgraph/self-managed/config.mdx An example of a YAML configuration file using kebab-case for keys. YAML offers a more human-readable syntax. ```yaml badger: compression: zstd:1 trace: jaeger: http://jaeger:14268 security: whitelist: 10.0.0.0/8,172.0.0.0/8,192.168.0.0/16 tls: ca-cert: /dgraph/tls/ca.crt client-auth-type: REQUIREANDVERIFY server-cert: /dgraph/tls/node.crt server-key: /dgraph/tls/node.key use-system-ca: true internal-port: true client-cert: /dgraph/tls/client.dgraphuser.crt client-key: /dgraph/tls/client.dgraphuser.key ``` -------------------------------- ### Badger Key-Value Store Operations in Go Source: https://context7.com/hypermodeinc/docs/llms.txt Demonstrates opening a Badger database, performing write and read transactions with TTL support, iterating with prefix scans, and setting up garbage collection. ```go package main import ( "fmt" "time" badger "github.com/dgraph-io/badger/v4" ) func main() { // Open database (creates if doesn't exist) db, err := badger.Open(badger.DefaultOptions("/tmp/badger")) if err != nil { panic(err) } defer db.Close() // Write data in a transaction err = db.Update(func(txn *badger.Txn) error { // Simple key-value set if err := txn.Set([]byte("user:1"), []byte("Alice")); err != nil { return err } // Set with TTL (expires in 1 hour) entry := badger.NewEntry([]byte("session:abc"), []byte("active")). WithTTL(time.Hour) return txn.SetEntry(entry) }) // Read data err = db.View(func(txn *badger.Txn) error { item, err := txn.Get([]byte("user:1")) if err != nil { return err } return item.Value(func(val []byte) error { fmt.Printf("Value: %s\n", val) return nil }) }) // Iterate with prefix scan err = db.View(func(txn *badger.Txn) error { opts := badger.DefaultIteratorOptions opts.PrefetchSize = 10 it := txn.NewIterator(opts) defer it.Close() prefix := []byte("user:") for it.Seek(prefix); it.ValidForPrefix(prefix); it.Next() { item := it.Item() item.Value(func(v []byte) error { fmt.Printf("key=%s, value=%s\n", item.Key(), v) return nil }) } return nil }) // Garbage collection (run periodically) ticker := time.NewTicker(5 * time.Minute) defer ticker.Stop() go func() { for range ticker.C { for db.RunValueLogGC(0.7) == nil {} } }() } ``` -------------------------------- ### Handle Transaction Conflicts and Size Limits Source: https://github.com/hypermodeinc/docs/blob/main/badger/quickstart.mdx This example demonstrates how to handle ErrConflict by retrying operations and ErrTxnTooBig by committing the current transaction and starting a new one. ```go updates := make(map[string]string) txn := db.NewTransaction(true) for k,v := range updates { if err := txn.Set([]byte(k),[]byte(v)); err == badger.ErrTxnTooBig { _ = txn.Commit() txn = db.NewTransaction(true) _ = txn.Set([]byte(k),[]byte(v)) } } _ = txn.Commit() ``` -------------------------------- ### Create and Navigate to a New App Source: https://github.com/hypermodeinc/docs/blob/main/apps/develop-app.mdx Scaffold a new Hypermode App and change into its directory. This sets up the basic project structure. ```bash modus new my-app cd my-app ``` -------------------------------- ### Custom HTTP Resolvers for REST APIs Source: https://github.com/hypermodeinc/docs/blob/main/dgraph/graphql/schema/directives/custom.mdx Examples of using the @custom directive with HTTP GET and POST methods to resolve GraphQL fields from REST APIs. ```APIDOC ## Custom HTTP Resolvers ### Description Defines custom resolvers for GraphQL fields that fetch data from external HTTP endpoints. ### Endpoint: getCustomPost #### Method GET #### Endpoint https://my.api.com/post/$id #### Parameters - **id** (ID!) - Required - The ID of the post to fetch. #### Response - **Post** - Expected to return a JSON object with fields `id`, `title`, `datePublished`, and `author`. ### Endpoint: getPosts #### Method GET #### Endpoint https://my.api.com/person/$authorID/posts?limit=$numToFetch #### Parameters - **authorID** (ID!) - Required - The ID of the author. - **numToFetch** (Int!) - Required - The number of posts to fetch. #### Response - **[Post]** - Expected to return a JSON array of Post objects. ``` -------------------------------- ### Example JSON Config (Kebab-Case) Source: https://github.com/hypermodeinc/docs/blob/main/dgraph/self-managed/config.mdx An example of a JSON configuration file using kebab-case for keys. This format is common for many configurations. ```json { "badger": { "compression": "zstd:1" }, "trace": { "jaeger": "http://jaeger:14268" }, "security": { "whitelist": "10.0.0.0/8,172.0.0.0/8,192.168.0.0/16" }, "tls": { "ca-cert": "/dgraph/tls/ca.crt", "client-auth-type": "REQUIREANDVERIFY", "server-cert": "/dgraph/tls/node.crt", "server-key": "/dgraph/tls/node.key", "use-system-ca": true, "internal-port": true, "client-cert": "/dgraph/tls/client.dgraphuser.crt", "client-key": "/dgraph/tls/client.dgraphuser.key" } } ``` -------------------------------- ### Create start.sh for Dgraph Source: https://github.com/hypermodeinc/docs/blob/main/dgraph/self-managed/render.mdx This bash script initiates Dgraph Zero and Dgraph Alpha processes using the provided configuration file. ```bash #!/bin/bash # Start Dgraph Zero dgraph zero --config /dgraph/config/dgraph-config.yml & # Start Dgraph Alpha dgraph alpha --config /dgraph/config/dgraph-config.yml & # Wait for all processes to finish wait ``` -------------------------------- ### Create DgraphClientStub and DgraphClient Source: https://github.com/hypermodeinc/docs/blob/main/dgraph/sdks/javascript-http.mdx Initialize a DgraphClientStub with the server address and an optional legacy API flag. Then, create a DgraphClient instance using the stub. This is the basic setup for connecting to a Dgraph instance. ```javascript const dgraph = require("dgraph-js-http") const clientStub = new dgraph.DgraphClientStub( // addr: optional, default: "http://localhost:8080" "http://localhost:8080", // legacyApi: optional, default: false. Set to true when connecting to Dgraph v1.0.x false, ) const dgraphClient = new dgraph.DgraphClient(clientStub) ``` -------------------------------- ### Get user information Source: https://github.com/hypermodeinc/docs/blob/main/dgraph/enterprise/access-control-lists.mdx This query retrieves detailed information about a specific user, including their name and the groups they are a part of. The example demonstrates fetching information for the user 'alice'. ```APIDOC ## Get user information ### Description Retrieves detailed information for a specific user, including their name and the groups they belong to. The example fetches data for the user 'alice'. ### Method `QUERY` ### Endpoint `/graphql` ### Parameters #### Query Parameters - **name** (string) - Required - The name of the user to retrieve information for. ### Request Example ```graphql query { getUser(name: "alice") { name groups { name } } } ``` ### Response #### Success Response (200) - **getUser** (object) - Information about the specified user. - **name** (string) - The name of the user. - **groups** (array of objects) - The groups the user belongs to. - **name** (string) - The name of the group. #### Response Example ```json { "data": { "getUser": { "name": "alice", "groups": [ { "name": "dev" } ] } } } ``` ``` -------------------------------- ### lsbackup Output Example Source: https://github.com/hypermodeinc/docs/blob/main/dgraph/enterprise/lsbackup.mdx Standard output of the `lsbackup` command, showing basic backup details. ```json [ { "path": "/home/user/Dgraph/20.11/backup/manifest.json", "since": 30005, "backup_id": "reverent_vaughan0", "backup_num": 1, "encrypted": false, "type": "full" } ] ``` -------------------------------- ### Advanced Query Example: Home Office Upgrade Source: https://github.com/hypermodeinc/docs/blob/main/agents/30-days-of-agents/day-18.mdx This query tests sophisticated retrieval patterns for upgrading a home office setup, considering budget and daily usage. ```text "I want to upgrade my home office setup for better productivity and comfort. I have a $1000 budget and work from home 8 hours a day." ``` -------------------------------- ### MCP Tool Call for Search Source: https://github.com/hypermodeinc/docs/blob/main/hypermode-docs-mcp.mdx This JSON object represents a tool call to the 'search' function, specifying a query to find Stripe agent connection setup guides. ```json { "name": "search", "arguments": { "query": "Stripe agent connection setup guide" } } ``` -------------------------------- ### GraphQL Schema Deprecation Example Source: https://github.com/hypermodeinc/docs/blob/main/dgraph/graphql/schema/directives/deprecated.mdx Demonstrates how to apply the @deprecated directive to fields and enum values within a GraphQL schema. Include a reason for deprecation to guide users. ```graphql type MyType { id: ID! oldField: String @deprecated(reason: "oldField is deprecated. Use newField instead.") newField: String deprecatedField: String @deprecated } ``` -------------------------------- ### Install and Use Render CLI for Logs Source: https://github.com/hypermodeinc/docs/blob/main/dgraph/self-managed/render.mdx Install the Render CLI globally using npm and then use the 'render logs' command to view logs for a specific service. Replace 'your-service-id' with your actual service ID. ```bash # Install Render CLI npm install -g @render-com/cli # View logs render logs -s your-service-id ``` -------------------------------- ### Boilerplate for using a GraphQL mutation Source: https://github.com/hypermodeinc/docs/blob/main/dgraph/guides/message-board-app/react-ui/react-ui-graphql-mutations.mdx Example of the boilerplate code for using a GraphQL mutation hook in a React component. It shows how to get a function to execute the mutation and configure callbacks. ```javascript const [addPost] = useAddPostMutation({ /* what happens after the mutation is executed */ }) ``` -------------------------------- ### Get group information Source: https://github.com/hypermodeinc/docs/blob/main/dgraph/enterprise/access-control-lists.mdx This query retrieves detailed information about a specific group, including its name, members, and ACL rules. The example demonstrates fetching information for the 'dev' group. ```APIDOC ## Get group information ### Description Retrieves detailed information for a specific group, including its name, associated users, and ACL rules. The example fetches data for the 'dev' group. ### Method `QUERY` ### Endpoint `/graphql` ### Parameters #### Query Parameters - **name** (string) - Required - The name of the group to retrieve information for. ### Request Example ```graphql query { getGroup(name: "dev") { name users { name } rules { permission predicate } } } ``` ### Response #### Success Response (200) - **getGroup** (object) - Information about the specified group. - **name** (string) - The name of the group. - **users** (array of objects) - The users belonging to the group. - **name** (string) - The name of the user. - **rules** (array of objects) - The ACL rules for the group. - **permission** (integer) - The permission level. - **predicate** (string) - The predicate for the rule. #### Response Example ```json { "data": { "getGroup": { "name": "dev", "users": [ { "name": "alice" } ], "rules": [ { "permission": 7, "predicate": "friend" }, { "permission": 7, "predicate": "~friend" } ] } } } ``` ``` -------------------------------- ### Configure Base System on Linux Source: https://github.com/hypermodeinc/docs/blob/main/dgraph/self-managed/linux.mdx Update system packages, install essential utilities, configure the firewall to allow Dgraph ports, and set up swap space. Run these commands on all nodes. ```bash sudo apt update && sudo apt upgrade -y sudo apt install -y curl wget unzip htop iotop sudo ufw allow ssh sudo ufw allow 8080 # Dgraph Alpha HTTP sudo ufw allow 9080 # Dgraph Alpha gRPC sudo ufw allow 5080 # Dgraph Zero sudo ufw allow 6080 # Dgraph Zero HTTP sudo ufw enable sudo fallocate -l 4G /swapfile sudo chmod 600 /swapfile sudo mkswap /swapfile sudo swapon /swapfile echo '/swapfile none swap sw 0 0' | sudo tee -a /etc/fstab ``` -------------------------------- ### Multi-hop Reasoning Query Example Source: https://github.com/hypermodeinc/docs/blob/main/agents/30-days-of-agents/day-20.mdx This query guides the agent to analyze the indirect influence of a specific investment on competition between companies, requiring multi-step graph traversal and reasoning about competitive dynamics. ```text Find all the ways that Microsoft's investment in OpenAI might influence competition with Google's AI products. Consider indirect effects and network implications. ``` -------------------------------- ### Practice Iterative Problem-Solving with Agents Source: https://github.com/hypermodeinc/docs/blob/main/agents/30-days-of-agents/day-17.mdx Use this prompt structure to guide agents through complex topics using an iterative, problem-solving approach. It encourages starting with a high-level overview and then drilling down into specifics. ```text "Let's practice iterative problem-solving. Start by giving me a high-level overview of [complex topic relevant to your work]. Then we'll drill down into specifics based on what I find most interesting or useful." ``` -------------------------------- ### Modus Project Structure Example Source: https://github.com/hypermodeinc/docs/blob/main/apps/develop-app.mdx An example of the standard file and directory structure for a Modus App. This outlines the key configuration and code files. ```text my-app/ ├── main.go # Functions and agent definitions ├── modus.json # App configuration and manifest ├── .env.dev.local # Local environment variables ├── go.mod # Dependencies (Go projects) └── README.md # Project documentation ``` -------------------------------- ### Start Dgraph Services with Docker Compose Source: https://github.com/hypermodeinc/docs/blob/main/dgraph/self-managed/single-host-setup.mdx Execute the docker-compose up command to launch the Dgraph Zero, Alpha, and Ratel services defined in your docker-compose.yml file. Ensure you have Docker and Docker Compose installed. ```sh sudo docker-compose up ``` -------------------------------- ### Troubleshoot EKS LoadBalancer External IP Issues Source: https://github.com/hypermodeinc/docs/blob/main/dgraph/self-managed/managed-kubernetes.mdx For EKS LoadBalancers not getting an external IP, verify the AWS Load Balancer Controller deployment, check service events, and ensure the controller is installed. ```bash # Check AWS Load Balancer Controller kubectl get deployment -n kube-system aws-load-balancer-controller ``` ```bash # Check service events kubectl describe service dgraph-alpha-public -n dgraph ``` ```bash # Install AWS Load Balancer Controller if missing helm repo add eks https://aws.github.io/eks-charts helm install aws-load-balancer-controller eks/aws-load-balancer-controller -n kube-system ``` -------------------------------- ### Start Development Server Source: https://github.com/hypermodeinc/docs/blob/main/apps/connect-app.mdx Use the `modus dev` command to start the development server. This command is used for local testing and debugging. ```bash modus dev ``` -------------------------------- ### Build Your App Source: https://github.com/hypermodeinc/docs/blob/main/apps/develop-app.mdx Compile your Hypermode App for deployment. This command bundles your code and assets. ```bash modus build ``` -------------------------------- ### Local GraphQL Endpoint Example Source: https://github.com/hypermodeinc/docs/blob/main/dgraph/graphql/connecting.mdx This is the default GraphQL endpoint for a local Dgraph installation. The actual URL may vary based on your configuration, including port offsets, TLS settings, and load balancer usage. ```bash http://localhost:8080/graphql ``` -------------------------------- ### Custom HTTP Endpoint for Single Post Retrieval Source: https://github.com/hypermodeinc/docs/blob/main/dgraph/graphql/schema/directives/custom.mdx This example defines a 'getCustomPost' query that fetches a single 'Post' object from a remote HTTP endpoint. It uses the @custom directive with an HTTP GET request, passing the 'id' from the query argument to the URL. ```graphql getCustomPost(id: ID!): Post @custom(http: { url: "https://my.api.com/post/$id", method: GET }) ``` -------------------------------- ### Export Public Functions in Go Source: https://github.com/hypermodeinc/docs/blob/main/modus/api-generation.mdx Functions written in Go use starting capital letters to expose functions as public. Modus creates an external API for public functions from any file that belongs to the `main` package. This example demonstrates classifying text using a pre-trained model. ```go package main import ( "errors" "fmt" "github.com/hypermodeinc/modus/sdk/go/models" "github.com/hypermodeinc/modus/sdk/go/models/experimental" ) const modelName = "my-classifier" // this function takes input text and a probability threshold, and returns the // classification label determined by the model, if the confidence is above the // threshold; otherwise, it returns an empty string func ClassifyText(text string, threshold float32) (string, error) { predictions, err:= classify(text) if err != nil { return "", err } prediction := predictions[0] if prediction.Confidence < threshold { return "", nil } return prediction.Label, nil } func classify(texts ...string) ([]experimental.ClassifierResult, error) { model, err := models.GetModel[experimental.ClassificationModel](modelName) if err != nil { return nil, err } input, err := model.CreateInput(texts...) if err != nil { return nil, err } output, err := model.Invoke(input) if err != nil { return nil, err } if len(output.Predictions) != len(texts) { word := "prediction" if len(texts) > 1 { word += "s" } return nil, fmt.Errorf("expected %d %s, got %d", len(texts), word, len(output.Predictions)) } return output.Predictions, nil } ``` -------------------------------- ### Python Dgraph Client Setup Source: https://github.com/hypermodeinc/docs/blob/main/agents/30-days-of-agents/day-22.mdx Sets up a Dgraph client connection using Python. Ensure the Dgraph instance is running and accessible at the specified address. ```python import pydgraph import grpc import json from datetime import datetime # Create Dgraph client def create_client(): stub = pydgraph.DgraphClientStub('localhost:9080') client =pydgraph.open("dgraph://") return client ``` -------------------------------- ### Define and Publish Custom Agent Events in Go Source: https://github.com/hypermodeinc/docs/blob/main/modus/agents.mdx Define custom event types that implement the `AgentEvent` interface and use the `PublishEvent` method to emit them during agent operations. This example shows publishing various events like mission start, progress updates, AI analysis, and threat detection. ```go // Custom event types implement the AgentEvent interface type ThreatDetected struct { ThreatLevel string `json:"threatLevel"` Confidence float64 `json:"confidence"` Analysis string `json:"analysis"` } func (e ThreatDetected) EventName() string { return "threat_detected" } // Other event types can be defined similarly... func (a *IntelligenceAgent) analyzeMatrixActivity( data string, ) (*string, error) { // Emit mission start event err := a.PublishEvent(MissionStarted{ MissionName: "Matrix Surveillance Analysis", Priority: "HIGH", ActivityData: len(*data), }) if err != nil { return nil, err } // Store new intelligence in persistent memory a.intelligenceReports = append(a.intelligenceReports, *data) a.lastContact = time.Now() // Emit progress update a.PublishEvent(SurveillanceProgress{ ReportsProcessed: len(a.intelligenceReports), Phase: "Processing Matrix surveillance data", Progress: 0.3, }) // Build context from all accumulated intelligence accumulatedReports := strings.Join(a.intelligenceReports, "\n") // AI analysis using complete operational history model, err := models.GetModel[openai.ChatModel]("analyst-model") if err != nil { return nil, err } systemPrompt := `You are a resistance operative in the Matrix. Analyze patterns from accumulated surveillance reports and provide threat assessment for anomalous Agent behavior.` userPrompt := fmt.Sprintf(`All Matrix Intelligence: %s Provide threat assessment:`, accumulatedReports) input, err := model.CreateInput( openai.NewSystemMessage(systemPrompt), openai.NewUserMessage(userPrompt), ) if err != nil { return nil, err } // Emit AI processing event a.PublishEvent(AIAnalysisStarted{ ModelName: "analyst-model", ContextSize: len(accumulatedReports), ReportCount: len(a.intelligenceReports), }) output, err := model.Invoke(input) if err != nil { return nil, err } analysis := output.Choices[0].Message.Content // Update threat level based on data volume and AI analysis a.threatLevel = float64(len(a.intelligenceReports)) / 10.0 if a.threatLevel > 1.0 { a.threatLevel = 1.0 } // Check for Agent threats and emit alerts if strings.Contains(strings.ToLower(analysis), "critical") || strings.Contains(strings.ToLower(analysis), "agent smith") { a.threatLevel = math.Min(a.threatLevel + 0.2, 1.0) a.PublishEvent(ThreatDetected{ ThreatLevel: "HIGH", Confidence: a.threatLevel, Analysis: analysis, }) } // Emit mission completion a.PublishEvent(MissionCompleted{ MissionName: "Matrix Surveillance Analysis", Confidence: a.threatLevel, ReportsAnalyzed: len(a.intelligenceReports), Status: "SUCCESS", }) result := fmt.Sprintf(`Matrix surveillance complete: %s (Threat level: %.2f based on %d intelligence reports)`, analysis, a.threatLevel, len(a.intelligenceReports)) return &result, nil } ``` -------------------------------- ### lsbackup MinIO Example Source: https://github.com/hypermodeinc/docs/blob/main/dgraph/enterprise/lsbackup.mdx Check backups in a MinIO bucket using `lsbackup`. Configure `secure=false` if TLS is not used and set MinIO access/secret keys as environment variables. ```sh dgraph lsbackup -l "minio://localhost:9000/?secure=false" ``` -------------------------------- ### Install Dependencies for Data Population Source: https://github.com/hypermodeinc/docs/blob/main/getting-started-with-hyper-commerce.mdx Install the necessary Python libraries for the data population script. Ensure you have Python installed. ```sh pip install requests gql requests_toolbelt pandas numpy ``` -------------------------------- ### POST /admin - Create Backup to MinIO Source: https://github.com/hypermodeinc/docs/blob/main/dgraph/enterprise/binary-backups.mdx Initiates a binary backup to a MinIO bucket. ```APIDOC ## POST /admin - Create Backup to MinIO ### Description Initiates a binary backup to a MinIO bucket. ### Method POST ### Endpoint /admin ### Parameters #### Query Parameters None #### Request Body None (Mutation is sent via GraphQL client) ### Request Example ```graphql mutation { backup(input: { destination: "minio://127.0.0.1:9000/" }) { response { message code } taskId } } ``` ### Response #### Success Response (200) - **response** (object) - Contains the status message and code of the backup operation. - **taskId** (string) - The unique identifier for the backup task. #### Response Example ```json { "response": { "message": "Backup initiated successfully.", "code": 200 }, "taskId": "123e4567-e89b-12d3-a456-426614174000" } ``` ``` -------------------------------- ### Advanced Query Example: Beginner Cook Tools Source: https://github.com/hypermodeinc/docs/blob/main/agents/30-days-of-agents/day-18.mdx This query tests retrieval for beginner cooks seeking impactful kitchen tools to make healthier meals with limited time. ```text "I'm a beginner cook who wants to make healthier meals but has limited time. What kitchen tools would be most impactful?" ```