### Quick Start Guide Application Source: https://github.com/embabel/guide/blob/main/_autodocs/api-reference/GuideApplication.md Use these commands to start Neo4j, set an LLM API key, and run the Guide Application using Maven. Verify the MCP server is running afterwards. ```bash # Start Neo4j docker compose up neo4j -d # Set LLM key export OPENAI_API_KEY=sk-... # Run the application ./mvnw spring-boot:run # Verify MCP server is running curl -i http://localhost:1337/sse ``` -------------------------------- ### Running the Embabel Guide Application Source: https://github.com/embabel/guide/blob/main/_autodocs/api-reference/GuideApplication.md Examples of how to run the application using Maven, with custom ports, as a packaged JAR, and with environment variables. ```bash # Run from Maven ./mvnw spring-boot:run ``` ```bash # Run with custom port ./mvnw spring-boot:run -Dspring-boot.run.profiles=neo4j -Dserver.port=1338 ``` ```bash # Run packaged JAR java -jar target/guide-0.1.0-SNAPSHOT.jar ``` ```bash # Run with environment variables OPENAI_API_KEY=sk-... docker compose --profile java up --build -d ``` -------------------------------- ### Docker Compose for Guide Application Source: https://github.com/embabel/guide/blob/main/_autodocs/api-reference/GuideApplication.md Commands to start and stop the Guide Application along with Neo4j using Docker Compose. Ensure you use the '--profile java' flag for the Java application. ```bash # Start with Neo4j and Guide application docker compose --profile java up --build -d # Stop docker compose --profile java down ``` -------------------------------- ### Example Code Languages Source: https://github.com/embabel/guide/blob/main/_autodocs/00-START-HERE.txt The Embabel Guide provides code examples in multiple languages to facilitate integration and testing. ```text cURL (HTTP testing) JavaScript (browser clients) Python (integrations) Java/Kotlin (server-side) ``` -------------------------------- ### Quick Start: Set Up Personal User Configuration Source: https://github.com/embabel/guide/blob/main/scripts/user-config/README.md Copy the example user configuration file and set the GUIDE_PROFILE environment variable to customize your local settings. This is the first step to enabling personal Spring profiles. ```bash cp scripts/user-config/application-user.yml.example scripts/user-config/application-myname.yml # Edit to taste, then: echo 'GUIDE_PROFILE=myname' >> .env ./scripts/fresh-ingest.sh ``` -------------------------------- ### Start Docker Compose with Java Profile Source: https://github.com/embabel/guide/blob/main/README.md This command starts the Neo4j and guide applications using Docker Compose with the 'java' profile enabled. It also builds the Docker image if necessary. ```bash docker compose --profile java up --build -d ``` -------------------------------- ### Create Typed Object with Few-Shot Examples Source: https://github.com/embabel/guide/blob/main/data/docs/index.md Enhance object creation by providing strongly typed examples for few-shot prompting. This guides the LLM by including examples in JSON format within the prompt. ```java var story = context.ai() .withDefaultLlm() .withToolGroup( CoreToolGroups .WEB) .withExample("A children's story", new Story ("Once upon a time...")) ① .creating( Story .class) .fromPrompt("Create a story about: " + input.getContent()); ``` -------------------------------- ### Complete WebSocket Example Source: https://github.com/embabel/guide/blob/main/_autodocs/endpoints.md A comprehensive example demonstrating WebSocket connection, message subscription, presence updates, keep-alive signals, and message sending. ```javascript import { Client } from '@stomp/stompjs'; import SockJS from 'sockjs-client'; const client = new Client({ webSocketFactory: () => new SockJS('http://localhost:1337/ws'), onConnect: () => { console.log('✓ Connected to Guide'); // Subscribe to messages client.subscribe('/user/queue/messages', (frame) => { const msg = JSON.parse(frame.body); console.log(`${msg.authorId}: ${msg.body}`); // Acknowledge receipt client.publish({ destination: '/app/message.ack', body: JSON.stringify({ messageId: msg.id }) }); }); // Subscribe to presence updates client.subscribe('/user/queue/status', (frame) => { const status = JSON.parse(frame.body); console.log(`User ${status.fromUserId} is ${status.status}`); }); // Start keep-alive setInterval(() => { client.publish({ destination: '/app/presence.ping', body: JSON.stringify({ status: 'active' }) }); }, 30000); // Send a message client.publish({ destination: '/app/chat.send', body: JSON.stringify({ sessionId: 'my-session', body: 'Hello, what can you help with?' }) }); }, onError: (error) => { console.error('WebSocket error:', error); } }); client.activate(); ``` -------------------------------- ### Start Docker Compose for FalkorDB Source: https://github.com/embabel/guide/blob/main/README.md Use Docker Compose to start the FalkorDB container. This command assumes you have Docker and Docker Compose installed. ```bash docker compose --profile falkordb up -d ``` -------------------------------- ### Start Docker Compose for Neo4j Source: https://github.com/embabel/guide/blob/main/README.md Use Docker Compose to start the Neo4j container. This command assumes you have Docker and Docker Compose installed. ```bash docker compose --profile neo4j up -d ``` -------------------------------- ### Start Docker Compose for Memgraph Source: https://github.com/embabel/guide/blob/main/README.md Use Docker Compose to start the Memgraph container. This command assumes you have Docker and Docker Compose installed. ```bash docker compose --profile memgraph up -d ``` -------------------------------- ### Create and Execute Agent Process with Bindings Source: https://github.com/embabel/guide/blob/main/data/docs/index.md Create an agent process with specific bindings and start its execution. Use `start()` for asynchronous completion or `run()` for synchronous execution. ```kotlin val agentProcess = agentPlatform. createAgentProcess ( agent = myAgent, processOptions = ProcessOptions (), bindings = mapOf ("input" to userRequest) ) val result = agentPlatform. start (agentProcess). get () ``` ```kotlin val completedProcess = agentProcess. run () val result = completedProcess.last< MyResultType >() ``` -------------------------------- ### Source Code Reference Example Source: https://github.com/embabel/guide/blob/main/_autodocs/INDEX.md An example of how source code references are provided in the documentation, allowing direct navigation to implementation details. ```text Source: src/main/java/com/embabel/guide/rag/DataManager.java (lines 99-119) ``` -------------------------------- ### Start Local Neo4j Source: https://github.com/embabel/guide/blob/main/scripts/INGESTION-TESTING.md Starts a Neo4j instance using Docker Compose. This is a prerequisite for running tests with local Neo4j. ```bash docker compose up neo4j -d ``` -------------------------------- ### Health Check Guide Application Source: https://github.com/embabel/guide/blob/main/_autodocs/api-reference/GuideApplication.md Check the health status of the Guide Application by sending a GET request to the /actuator/health endpoint. ```bash # Check application health curl http://localhost:1337/actuator/health ``` -------------------------------- ### GuideProperties Configuration Source: https://github.com/embabel/guide/blob/main/_autodocs/types.md Configuration properties for the Guide application, loaded from application.yml with the 'guide' prefix. It defines settings for content reloading, default persona, project paths, chunking, references, tools, and fetch routes. ```kotlin @Validated @ConfigurationProperties(prefix = "guide") data class GuideProperties( val reloadContentOnStartup: Boolean, @field:NotBlank(message = "defaultPersona must not be blank") val defaultPersona: String, val defaultProvider: LlmProvider? = null, @field:NotBlank(message = "projectsPath must not be blank") val projectsPath: String, @NestedConfigurationProperty val chunkerConfig: ContentChunker.Config?, @DefaultValue("references.yml") @field:NotBlank(message = "referencesFile must not be blank") val referencesFile: String, @NestedConfigurationProperty val content: ContentConfig, @DefaultValue("") val toolPrefix: String, val directories: List?, val toolGroups: Set, val fetchRoutes: List = emptyList() ) ``` -------------------------------- ### WriteAndReviewAgent Example Source: https://github.com/embabel/guide/blob/main/data/docs/index.md An example agent demonstrating how to write and review stories using different LLM configurations and personas. It utilizes @Action and @AchievesGoal annotations for defining agent behavior. ```java @Agent(description = "Agent that writes and reviews stories") public class WriteAndReviewAgent { @Action public Story writeStory ( UserInput userInput, OperationContext context) { // High temperature for creativity var writer = LlmOptions .withModel( OpenAiModels .GPT_4O_MINI) .withTemperature( 0.8 ) .withPersona("You are a creative storyteller"); return context.ai() .withLlm(writer) .createObject("Write a story about: " + userInput.getContent(), Story .class); } @AchievesGoal(description = "Review and improve the story") @Action public ReviewedStory reviewStory ( Story story, OperationContext context) { // Low temperature for analytical review var reviewer = LlmOptions .withModel( OpenAiModels .GPT_4O_MINI) .withTemperature( 0.2 ) .withPersona("You are a careful editor and reviewer"); String prompt = "Review this story and suggest improvements: " + story.text(); return context.ai() .withLlm(reviewer) .createObject(prompt, ReviewedStory .class); } } ``` -------------------------------- ### GuideApplication Main Method Source: https://github.com/embabel/guide/blob/main/_autodocs/api-reference/GuideApplication.md The entry point for launching the Embabel Guide application, configuring it as a SERVLET web application. ```java public static void main(String[] args) { SpringApplication app = new SpringApplication(GuideApplication.class); app.setWebApplicationType(WebApplicationType.SERVLET); app.run(args); } ``` -------------------------------- ### Clone Embale Agent Examples Source: https://github.com/embabel/guide/blob/main/data/docs/index.md Clone the Embale agent examples repository and navigate to the scripts directory. ```shell git clone https://github.com/embabel/embabel-agent-examples cd embabel-agent-examples/scripts/java ./shell.sh ``` -------------------------------- ### Example Versioned Content Configuration Source: https://github.com/embabel/guide/blob/main/_autodocs/types.md An example YAML configuration for versioned content, demonstrating how to specify the base URL and a list of versions. This configuration is used to generate full URLs for accessing different documentation versions. ```yaml content: versioned: base-url: https://docs.embabel.com/embabel-agent/guide/ versions: - 0.4.0-SNAPSHOT - 0.3.0 ``` -------------------------------- ### RAG Adapter Configuration Source: https://github.com/embabel/guide/blob/main/_autodocs/configuration.md Configure the RAG adapter type. Use 'guide' for real Guide chatbot integration or 'fake' for testing purposes. ```yaml rag: adapter: type: guide # or "fake" for testing ``` -------------------------------- ### Switching Application Profiles Source: https://github.com/embabel/guide/blob/main/_autodocs/api-reference/GuideApplication.md Examples of how to switch between different database profiles (FalkorDB, Memgraph) when running the application with Maven. ```bash # Use FalkorDB instead of Neo4j ./mvnw spring-boot:run -Dspring-boot.run.profiles=falkordb ``` ```bash # Use Memgraph ./mvnw spring-boot:run -Dspring-boot.run.profiles=memgraph ``` -------------------------------- ### Set Up and Use a Personal Ingestion Profile Source: https://github.com/embabel/guide/blob/main/scripts/README.md Copy an example profile, customize it with your URLs and settings, and update the environment variable to use your new profile for ingestion. ```bash cp scripts/user-config/application-user.yml.example scripts/user-config/application-yourname.yml # Edit to taste, then: echo 'GUIDE_PROFILE=yourname' >> .env ./scripts/fresh-ingest.sh ``` -------------------------------- ### Example Usage: Writing and Searching Documents Source: https://github.com/embabel/guide/blob/main/_autodocs/api-reference/RagConfiguration.md Demonstrates how to use the DrivineStore to write a document with automatic chunking and embedding, and how to perform a semantic search. ```java // Store a document with automatic chunking and embedding NavigableDocument doc = reader.readFromUrl("https://docs.example.com/"); drivineStore.writeAndChunkDocument(doc); // Search by semantic similarity List results = drivineStore.vectorSearch("what is Embabel?", limit=10); ``` -------------------------------- ### Run Neo4j Only with Docker Compose Source: https://github.com/embabel/guide/blob/main/README.md This command starts only the Neo4j service using Docker Compose, useful for local Java development when the guide application is run separately. ```bash COMPOSE_PROFILES= docker compose up -d ``` ```bash docker compose up neo4j -d ``` -------------------------------- ### JavaScript Presence Ping Example Source: https://github.com/embabel/guide/blob/main/_autodocs/api-reference/PresenceController.md Demonstrates sending presence updates using @stomp/stompjs. Includes examples for sending keep-alive pings every 30 seconds, updating status when typing, and reverting to idle after a delay. ```javascript // Send a keep-alive ping every 30 seconds setInterval(() => { client.publish({ destination: '/app/presence.ping', body: JSON.stringify({ status: 'active' }) }); }, 30000); // Or update status when user starts typing input.addEventListener('keydown', () => { client.publish({ destination: '/app/presence.ping', body: JSON.stringify({ status: 'typing' }) }); }); // Update status when user stops typing (after 2 seconds idle) let typingTimeout; input.addEventListener('keydown', () => { clearTimeout(typingTimeout); typingTimeout = setTimeout(() => { client.publish({ destination: '/app/presence.ping', body: JSON.stringify({ status: 'idle' }) }); }, 2000); }); ``` -------------------------------- ### Guide Directories for Ingestion Source: https://github.com/embabel/guide/blob/main/_autodocs/configuration.md Specify local directories to ingest content from. The system performs a full tree traversal of these directories. Paths can be absolute, relative, or start with `~/` to expand to the user's home directory. ```yaml guide: directories: - /path/to/docs - ./local-content - ~/embabel-projects/my-docs ``` -------------------------------- ### Python Presence Ping Example Source: https://github.com/embabel/guide/blob/main/_autodocs/api-reference/PresenceController.md Provides a Python example using stomp.py to send presence pings. Includes a function to send pings and a background thread for continuous keep-alive signals every 30 seconds. ```python import json import time import threading def send_presence_ping(conn, status='active'): conn.send( body=json.dumps({'status': status}), destination='/app/presence.ping' ) # Keep-alive ping every 30 seconds def keep_alive(conn): while True: send_presence_ping(conn, 'active') time.sleep(30) # Start keep-alive in background thread keep_alive_thread = threading.Thread(target=keep_alive, args=(conn,), daemon=True) keep_alive_thread.start() ``` -------------------------------- ### GuideProperties Constructor Parameters Source: https://github.com/embabel/guide/blob/main/_autodocs/configuration.md Parameters for the GuideProperties constructor. All parameters are read from application.yml with the 'guide' prefix via Spring's @ConfigurationProperties. ```kotlin GuideProperties( reloadContentOnStartup: Boolean, defaultPersona: String, defaultProvider: LlmProvider? = null, projectsPath: String, chunkerConfig: ContentChunker.Config? = null, referencesFile: String = "references.yml", content: ContentConfig, toolPrefix: String = "", directories: List? = null, toolGroups: Set, fetchRoutes: List = emptyList() ) ``` -------------------------------- ### List Available Resources (curl) Source: https://github.com/embabel/guide/blob/main/_autodocs/api-reference/McpResourceConfiguration.md Example using curl to list all available MCP resources. The response is expected to include the 'about' resource. ```bash # List available resources curl http://localhost:1337/mcp/resources/list # Response includes the "about" resource ``` -------------------------------- ### Guide Content Configuration Source: https://github.com/embabel/guide/blob/main/_autodocs/configuration.md Configure versioned documentation sources and supplementary URLs for content ingestion. The system computes the active version and a combined list of all URLs to ingest. ```yaml guide: content: versioned: base-url: https://docs.embabel.com/embabel-agent/guide/ versions: - 0.4.0-SNAPSHOT - 0.3.0 supplementary: - https://medium.com/@springrod/... - https://github.com/... ``` -------------------------------- ### GET /mcp/tools/list Source: https://github.com/embabel/guide/blob/main/_autodocs/api-reference/McpResourceConfiguration.md Lists all available MCP tools, including their names, descriptions, and input schemas. ```APIDOC ## GET /mcp/tools/list ### Description List all available MCP tools. ### Method GET ### Endpoint http://localhost:1337/mcp/tools/list ### Response #### Success Response (200) - **Response Type**: application/json #### Response Example ```json { "tools": [ { "name": "docs_vectorSearch", "description": "Vector search in Embabel documentation", "inputSchema": { "type": "object", "properties": { "query": {"type": "string"}, "limit": {"type": "integer"} }, "required": ["query"] } }, { "name": "embabel_agent_apiReference", "description": "Look up API signatures from Embabel packages", "inputSchema": {} } ] } ``` ``` -------------------------------- ### HierarchicalContentReader Usage Example Source: https://github.com/embabel/guide/blob/main/_autodocs/api-reference/RagConfiguration.md Demonstrates how to use the HierarchicalContentReader to fetch and parse documents from a given URL. ```java // Fetch and parse https://docs.embabel.com/ HierarchicalContentReader reader = hierarchicalContentReader(props); NavigableDocument doc = reader.readFromUrl("https://docs.embabel.com/"); ``` -------------------------------- ### Connect to Neo4j Browser Source: https://github.com/embabel/guide/blob/main/_autodocs/errors.md Open the Neo4j browser interface in your web browser. This is the starting point for interacting with the Neo4j database. ```bash # Connect to Neo4j browser open http://localhost:7474/browser/ ``` -------------------------------- ### Retrieve Repository Statistics (cURL) Source: https://github.com/embabel/guide/blob/main/_autodocs/api-reference/DataManagerController.md Example of how to fetch repository statistics using cURL. ```bash curl -X GET http://localhost:1337/api/v1/data/stats ``` -------------------------------- ### Retrieve Repository Statistics (Python) Source: https://github.com/embabel/guide/blob/main/_autodocs/api-reference/DataManagerController.md Example of how to fetch repository statistics using Python's requests library. ```python import requests response = requests.get('http://localhost:1337/api/v1/data/stats') stats = response.json() print(f"Documents: {stats['documentCount']}, Chunks: {stats['chunkCount']}") ``` -------------------------------- ### Configuration Coverage Summary Source: https://github.com/embabel/guide/blob/main/_autodocs/INDEX.md This section summarizes the coverage of configuration options within the Embabel Guide documentation, detailing what aspects of configuration are documented. ```text ✅ All YAML properties ✅ All environment variables ✅ All constructor parameters ✅ All bean definitions ``` -------------------------------- ### Send Command Result (JavaScript) Source: https://github.com/embabel/guide/blob/main/_autodocs/api-reference/ChatController.md Example of publishing a command result to the '/app/command.result' destination. ```javascript client.publish({ destination: '/app/command.result', body: JSON.stringify({ correlationId: 'cmd-uuid-123', success: true, result: 'Voice changed successfully' }) }); ``` -------------------------------- ### Minimal JavaScript STOMP Client Example Source: https://github.com/embabel/guide/blob/main/README.md This JavaScript snippet demonstrates how to connect to a STOMP server, subscribe to messages, and send a message using `@stomp/stompjs` and `sockjs-client`. ```javascript import {Client} from '@stomp/stompjs'; import SockJS from 'sockjs-client'; const client = new Client({ webSocketFactory: () => new SockJS('http://localhost:1337/ws'), onConnect: () => { // Subscribe to responses client.subscribe('/user/queue/messages', (frame) => { const message = JSON.parse(frame.body); console.log('Received:', message.content); }); // Send a message client.publish({ destination: '/app/chat.sendToJesse', body: JSON.stringify({body: 'Hello!'}) }); } }); client.activate(); ``` -------------------------------- ### Retrieve Repository Statistics (JavaScript) Source: https://github.com/embabel/guide/blob/main/_autodocs/api-reference/DataManagerController.md Example of how to fetch repository statistics using JavaScript's fetch API. ```javascript const response = await fetch('http://localhost:1337/api/v1/data/stats'); const stats = await response.json(); console.log(`Documents: ${stats.documentCount}, Chunks: ${stats.chunkCount}`); ``` -------------------------------- ### About Resource Content Source: https://github.com/embabel/guide/blob/main/_autodocs/api-reference/McpResourceConfiguration.md This content describes the Embabel Guide MCP server, its purpose, available endpoints, tool naming conventions, and recommended usage for agents. It is served as a static resource. ```text Embabel Guide MCP server (SSE) Purpose: - Exposes Embabel documentation and API references to MCP clients. - Primary use is answering Embabel questions using MCP tools (docs_* and API lookup tools). Endpoints: - SSE: http://localhost:1337/sse - Tools list: http://localhost:1337/mcp/tools/list - Resources list: http://localhost:1337/mcp/resources/list Tool naming: - docs_* tools search Embabel documentation content. - embabel_agent_* tools resolve API signatures from Embabel packages. Recommended usage for agents: 1) Prefer docs_* tools to answer Embabel questions. 2) Use embabel_agent_* tools to confirm class/package signatures. 3) If unsure, query tools list to see exact available tools. Notes: - If running on a different port, update the SSE URL accordingly. - This server currently exposes MCP tools and resources (no MCP prompts). ``` -------------------------------- ### Action Using Domain Objects Source: https://github.com/embabel/guide/blob/main/data/docs/index.md An example of an action method that takes a Customer object and uses its exposed tools (getLoyaltyDiscount, isPremiumEligible) via the LLM context to generate a recommendation. ```java @Action public Recommendation generateRecommendation ( Customer customer, OperationContext context) { // LLM has access to customer.getLoyaltyDiscount() and customer.isPremiumEligible() // as tools, plus the customer object structure String prompt = String .format( "Generate a personalized recommendation for %s based on their profile", customer.getName() ); return context.ai() .withDefaultLlm() .createObject(prompt, Recommendation .class); } ``` -------------------------------- ### Example Usage of Neo4j PersistenceManager Source: https://github.com/embabel/guide/blob/main/_autodocs/api-reference/GuideApplication.md Demonstrates how to inject and use the 'neo' PersistenceManager bean in other beans for Neo4j data access. ```java @Bean public DataManager dataManager( @Qualifier("neo") PersistenceManager persistenceManager ) { // Use persistenceManager to access Neo4j } ``` -------------------------------- ### guideResources() Bean Definition Source: https://github.com/embabel/guide/blob/main/_autodocs/api-reference/McpResourceConfiguration.md Defines a Bean that publishes static resource information about the Guide service. This bean implements the McpResourcePublisher interface. ```java @Bean public McpResourcePublisher guideResources() ``` -------------------------------- ### Production Configuration (FalkorDB) Source: https://github.com/embabel/guide/blob/main/_autodocs/configuration.md Example configuration for a production environment using FalkorDB. The active Spring profile is set via environment variables. ```yaml # Set via environment spring.profiles.active=falkordb ``` -------------------------------- ### Trigger Reference Loading (cURL) Source: https://github.com/embabel/guide/blob/main/_autodocs/api-reference/DataManagerController.md Example of how to trigger reference loading using cURL. The request body is empty. ```bash curl -X POST http://localhost:1337/api/v1/data/load-references \ -H "Content-Type: application/json" \ -d "{}" ``` -------------------------------- ### Tool Naming with Custom Prefix Source: https://github.com/embabel/guide/blob/main/_autodocs/api-reference/McpResourceConfiguration.md Example of configuring a custom prefix for tool names using YAML. This changes how tools are exposed to MCP clients. ```yaml guide: tool-prefix: "embabel__" ``` -------------------------------- ### Vector Similarity Search Example Source: https://github.com/embabel/guide/blob/main/_autodocs/api-reference/RagConfiguration.md Shows how to perform a vector similarity search using the DrivineStore to find semantically related chunks based on a query. ```java // Search by semantic similarity List results = drivineStore.vectorSearch( query = "How do I use Embabel?", limit = 10 ); ``` -------------------------------- ### Implement Custom Shell Commands Source: https://github.com/embabel/guide/blob/main/data/docs/index.md Example of implementing a custom Spring Shell command to interact with the AgentPlatform. This command retrieves bank support information for a customer query. ```java @ShellComponent public record SupportAgentShellCommands ( AgentPlatform agentPlatform ) { @ShellMethod("Get bank support for a customer query") public String bankSupport ( @ShellOption(value = "id", help = "customer id", defaultValue = "123") Long id, @ShellOption(value = "query", help = "customer query", defaultValue = "What's my balance, including pending amounts?") String query ) { var supportInput = new SupportInput (id, query); System .out.println("Support input: " + supportInput); var invocation = AgentInvocation .builder(agentPlatform) .options( ProcessOptions .builder().verbosity(v -> v.showPrompts( true )).build()) .build( SupportOutput .class); var result = invocation.invoke(supportInput); return result.toString(); } } ``` -------------------------------- ### Self-Unsticking Agent with StuckHandler Source: https://github.com/embabel/guide/blob/main/data/docs/index.md An example of an agent implementing the StuckHandler interface to handle situations where an action gets stuck. It demonstrates how to add data to the blackboard and return a StuckHandlerResult to unstick the agent. ```kotlin @Agent( description = "self unsticking agent", ) class SelfUnstickingAgent : StuckHandler { // The agent will get stuck as there's no dog to convert to a frog @Action @AchievesGoal(description = "the big goal in the sky") fun toFrog (dog: Dog ): Frog { return Frog (dog.name) } // This method will be called when the agent is stuck override fun handleStuck (agentProcess: AgentProcess ): StuckHandlerResult { called = true agentProcess. addObject ( Dog ("Duke")) return StuckHandlerResult ( message = "Unsticking myself", handler = this , code = StuckHandlingResultCode . REPLAN , agentProcess = agentProcess, ) } } ``` -------------------------------- ### Override Docker Compose Port Source: https://github.com/embabel/guide/blob/main/README.md This command starts the Docker Compose services while overriding the default host port for the guide application to 1338, useful if port 1337 is already in use. ```bash GUIDE_PORT=1338 docker compose --profile java up --build -d ``` -------------------------------- ### Get Repository Statistics Source: https://github.com/embabel/guide/blob/main/_autodocs/api-reference/DataManager.md Retrieves statistics about the ingested content from the repository. Use this to get counts of documents, chunks, and elements. ```java ContentElementRepositoryInfo stats = dataManager.getStats(); System.out.println("Documents: " + stats.getDocumentCount()); System.out.println("Chunks: " + stats.getChunkCount()); ``` -------------------------------- ### Creating a Simple Agent with DSL Source: https://github.com/embabel/guide/blob/main/data/docs/index.md Build a basic agent using SimpleAgentBuilder. Specify the return type, the action to run, and the agent's name and description. ```java var agent = SimpleAgentBuilder .returning( Joke .class) ① .running(tac -> tac.ai() ② .withDefaultLlm() .createObject("Tell me a joke", Joke .class)) .buildAgent("joker", "This is guaranteed to return a dreadful joke"); ③ ``` -------------------------------- ### GET /api/v1/data/stats Endpoint Source: https://github.com/embabel/guide/blob/main/_autodocs/api-reference/DataManagerController.md Retrieves repository statistics about ingested content. Use this endpoint to get counts of documents, chunks, and content elements. ```java @GetMapping("/stats") public ContentElementRepositoryInfo getStats() ``` -------------------------------- ### Send Message JavaScript Fetch Example Source: https://github.com/embabel/guide/blob/main/_autodocs/api-reference/ChatApiController.md Example of sending a message using the Fetch API in JavaScript to the /api/messages/send endpoint. Handles the response status. ```javascript const response = await fetch('http://localhost:1337/api/messages/send', { method: 'POST', headers: {'Content-Type': 'application/json'}, body: JSON.stringify({ sessionId: 'my-session-123', fromWebUserId: 'user-456', body: 'What is Embabel?' }) }); console.log('Message sent, status:', response.status); ``` -------------------------------- ### Send Message cURL Example Source: https://github.com/embabel/guide/blob/main/_autodocs/api-reference/ChatApiController.md Example of sending a message using cURL to the /api/messages/send endpoint. Ensure Content-Type and JSON body are correctly formatted. ```bash curl -X POST http://localhost:1337/api/messages/send \ -H "Content-Type: application/json" \ -d '{ "sessionId": "my-session-123", "fromWebUserId": "user-456", "body": "What is Embabel?" }' ``` -------------------------------- ### Embabel Equivalent: Configuration and Agent Definition Source: https://github.com/embabel/guide/blob/main/data/docs/index.md This Embabel equivalent demonstrates defining configuration properties and an agent with multiple actions for book writing, leveraging Spring Boot annotations and Embabel's core concepts. ```java @ConfigurationProperties("examples.book-writer") record BookWriterConfig ( LlmOptions researcherLlm, LlmOptions writerLlm, RoleGoalBackstory researcher, RoleGoalBackstory writer ) {} @Agent(description = "Write a book by researching, outlining, and writing chapters") public record BookWriter (BookWriterConfig config) { @Action ResearchReport researchTopic (@Bind Request request, OperationContext context) { return context.ai() .withLlm(config.researcherLlm()) .withPromptElements(config.researcher(), request) .withToolGroup(CoreToolGroups.WEB) .createObject("Research the topic thoroughly...", ResearchReport.class); } @Action BookOutline createOutline (@Bind Request request, ResearchReport research, OperationContext context) { return context.ai() .withLlm(config.writerLlm()) .withPromptElements(config.writer(), request, research) .createObject("Create a book outline...", BookOutline.class); } @AchievesGoal(export = @Export(remote = true)) @Action Book writeBook (@Bind Request request, BookOutline outline, OperationContext context) { // Parallel chapter writing with crew-like coordination var chapters = context.parallelMap(outline.chapterOutlines(), config.maxConcurrency(), chapterOutline -> writeChapter(request, outline, chapterOutline, context)); return new Book(request, outline.title(), chapters); } } ``` -------------------------------- ### Send Message Python Requests Example Source: https://github.com/embabel/guide/blob/main/_autodocs/api-reference/ChatApiController.md Example of sending a message using the Python requests library to the /api/messages/send endpoint. Prints the status code of the response. ```python import requests import json response = requests.post( 'http://localhost:1337/api/messages/send', headers={'Content-Type': 'application/json'}, json={ 'sessionId': 'my-session-123', 'fromWebUserId': 'user-456', 'body': 'What is Embabel?' } ) print(f'Status: {response.status_code}') ``` -------------------------------- ### Run Docker Compose with Custom Environment Variables Source: https://github.com/embabel/guide/blob/main/README.md This command starts the Embel services using Docker Compose, allowing customization of Neo4j password, OpenAI API key, and the application port. ```bash NEO4J_PASSWORD=mysecretpassword OPENAI_API_KEY=sk-... GUIDE_PORT=1338 docker compose --profile java up --build -d ``` -------------------------------- ### JWT Authentication for WebSocket Source: https://github.com/embabel/guide/blob/main/_autodocs/endpoints.md Example of a WebSocket URL with JWT token for authentication. ```url ws://localhost:1337/ws?token=eyJhbG... ``` -------------------------------- ### Acknowledge Message (JavaScript) Source: https://github.com/embabel/guide/blob/main/_autodocs/api-reference/ChatController.md Example of publishing a message acknowledgment to the '/app/message.ack' destination. ```javascript client.publish({ destination: '/app/message.ack', body: JSON.stringify({ messageId: '550e8400-e29b-41d4-a716-446655440000' }) }); ``` -------------------------------- ### Simple Horoscope Agent Command Source: https://github.com/embabel/guide/blob/main/data/docs/index.md Example command to interact with a simple horoscope agent. ```shell execute "My name is Sarah and I'm a Leo" ``` -------------------------------- ### Run Spring Boot with Debug Logging for Ingestion Source: https://github.com/embabel/guide/blob/main/_autodocs/errors.md Execute the Maven wrapper with specific arguments to enable DEBUG logging for the com.embabel.guide package. This helps in viewing detailed information during data ingestion processes. ```bash # Run with DEBUG logging ./mvnw spring-boot:run -Dspring-boot.run.arguments="--logging.level.com.embabel.guide=DEBUG" ``` -------------------------------- ### provisionDatabase() Source: https://github.com/embabel/guide/blob/main/_autodocs/api-reference/DataManager.md Provisions the database, ensuring tables and schema are created if they don't exist. ```APIDOC ## provisionDatabase() ### Description Provisions the database, ensuring tables and schema are created if they don't exist. ### Method ```java public void provisionDatabase() ``` ### Example ```java dataManager.provisionDatabase(); ``` ``` -------------------------------- ### Provision Database Source: https://github.com/embabel/guide/blob/main/_autodocs/api-reference/DataManager.md Ensures the database is provisioned by creating necessary tables and schema if they do not already exist. ```java dataManager.provisionDatabase(); ``` -------------------------------- ### Implement a Tool Method to Bind Customer Data Source: https://github.com/embabel/guide/blob/main/data/docs/index.md This tool method finds a customer by ID and binds it to the AgentProcess blackboard if an agent process is available. It demonstrates how tools can interact with the AgentProcess. ```java @Tool(description="My Tool") String bindCustomer ( Long id) { var customer = customerRepository.findById(id); var agentProcess = AgentProcess .get(); if (agentProcess != null ) { agentProcess.addObject(customer); return "Customer bound to blackboard"; } return "No agent process: Unable to bind customer"; } ``` -------------------------------- ### Get Document Count Source: https://github.com/embabel/guide/blob/main/_autodocs/api-reference/DataManager.md A convenience method to retrieve the total number of documents stored in the repository. ```java int docCount = dataManager.getDocumentCount(); ``` -------------------------------- ### JWT Authentication for REST Endpoints Source: https://github.com/embabel/guide/blob/main/_autodocs/endpoints.md Example of an Authorization header for REST endpoints using a Bearer token. ```http Authorization: Bearer eyJhbG... ``` -------------------------------- ### Send Chat Message (Python) Source: https://github.com/embabel/guide/blob/main/_autodocs/api-reference/ChatController.md Example of publishing a chat message to the '/app/chat.send' destination using stomp.py. ```python conn.send( body=json.dumps({ 'sessionId': 'my-session-id', 'body': 'Hello, how can you help?' }), destination='/app/chat.send' ) ``` -------------------------------- ### Send Chat Message (JavaScript) Source: https://github.com/embabel/guide/blob/main/_autodocs/api-reference/ChatController.md Example of publishing a chat message to the '/app/chat.send' destination using @stomp/stompjs. ```javascript client.publish({ destination: '/app/chat.send', body: JSON.stringify({ sessionId: 'my-session-id', body: 'Hello, how can you help?' }) }); ``` -------------------------------- ### REST API List Personas Endpoint Source: https://github.com/embabel/guide/blob/main/README.md Use this GET request to retrieve a list of available personas. ```http GET /api/hub/personas ``` -------------------------------- ### Project Creator Command Source: https://github.com/embabel/guide/blob/main/data/docs/index.md Use this command to create a custom Embabel project using the project creator template. ```bash uvx --from git+https://github.com/embabel/project-creator.git project-creator ``` -------------------------------- ### Development Configuration (Local Neo4j) Source: https://github.com/embabel/guide/blob/main/_autodocs/configuration.md Example application.yml configuration for a development environment using local Neo4j. Sets content reload, default persona, projects path, and content configuration. ```yaml # application.yml guide: reload-content-on-startup: false default-persona: adaptive projects-path: ./embabel-projects content: versioned: base-url: https://docs.embabel.com/embabel-agent/guide/ versions: [0.4.0-SNAPSHOT] supplementary: [] spring: profiles: active: neo4j server: port: 1337 ``` -------------------------------- ### GET /actuator/health Source: https://github.com/embabel/guide/blob/main/_autodocs/endpoints.md Spring Boot health check endpoint to determine the application's operational status. ```APIDOC ## GET /actuator/health ### Description Spring Boot health check endpoint. ### Method GET ### Endpoint /actuator/health ### Parameters ### Request Example ### Response #### Success Response (200) - **status** (string) - The overall health status (e.g., "UP"). - **components** (object) - Details about individual health components. - **db** (object) - Database health status. - **status** (string) - Status of the database component. - **diskSpace** (object) - Disk space health status. - **status** (string) - Status of the disk space component. #### Response Example ```json { "status": "UP", "components": { "db": {"status": "UP"}, "diskSpace": {"status": "UP"} } } ``` #### Error Response (503) Service Unavailable ``` -------------------------------- ### GET /mcp/resources/list Source: https://github.com/embabel/guide/blob/main/_autodocs/api-reference/McpResourceConfiguration.md Lists all available MCP resources, including their URIs, names, descriptions, and MIME types. ```APIDOC ## GET /mcp/resources/list ### Description List all available MCP resources. ### Method GET ### Endpoint http://localhost:1337/mcp/resources/list ### Response #### Success Response (200) - **Response Type**: application/json #### Response Example ```json { "resources": [ { "uri": "embabel://guide/about", "name": "about", "description": "About this MCP server and how to use it", "mimeType": "text/plain" } ] } ``` ``` -------------------------------- ### Interacting with an Agent in the Embabel Shell Source: https://github.com/embabel/guide/blob/main/data/docs/index.md Example command to trigger an agent's functionality within the Embabel interactive shell. This specific command asks the agent to generate and review a story about a robot learning to paint. ```shell x "Tell me a story about a robot learning to paint" ``` -------------------------------- ### Run Embabel with Memgraph Profile Source: https://github.com/embabel/guide/blob/main/README.md Execute the Embabel application with the Memgraph database profile using Maven. Ensure Memgraph is set up. ```bash ./mvnw spring-boot:run -Dspring-boot.run.profiles=memgraph ``` -------------------------------- ### Create Agent Process from Varargs Source: https://github.com/embabel/guide/blob/main/data/docs/index.md Conveniently create an agent process by passing agent and input objects directly as varargs. ```kotlin val agentProcess = agentPlatform. createAgentProcessFrom ( agent = travelAgent, processOptions = ProcessOptions (), travelRequest, userPreferences ) ``` -------------------------------- ### Get Chunk Count Source: https://github.com/embabel/guide/blob/main/_autodocs/api-reference/DataManager.md A convenience method to retrieve the total number of content chunks created from ingested documents. ```java int chunkCount = dataManager.getChunkCount(); ``` -------------------------------- ### Run Tests with Local Neo4j Source: https://github.com/embabel/guide/blob/main/README.md Execute tests using the Maven wrapper, enabling local Neo4j development by setting the USE_LOCAL_NEO4J environment variable and ensuring the LLM API key is exported. ```bash export OPENAI_API_KEY=sk-your-key-here USE_LOCAL_NEO4J=true ./mvnw test ``` -------------------------------- ### ChunkTransformer Version Metadata Example Source: https://github.com/embabel/guide/blob/main/_autodocs/api-reference/RagConfiguration.md Illustrates how the chunkTransformer adds version metadata, shown here for ingesting Embabel 0.4.0-SNAPSHOT docs. ```java // When ingesting Embabel 0.4.0-SNAPSHOT docs: // Each chunk receives: version = "0.4.0-SNAPSHOT" ``` -------------------------------- ### Example LlmKeyError JSON Source: https://github.com/embabel/guide/blob/main/_autodocs/errors.md Illustrates a JSON object representing an LLM key error when an API key is not configured for OpenAI. ```json { "type": "LLM_KEY_ERROR", "errorCode": "KEY_NOT_SET", "provider": "OPENAI", "message": "OpenAI API key not configured. Set OPENAI_API_KEY environment variable." } ``` -------------------------------- ### GET /actuator/health Response Schema Source: https://github.com/embabel/guide/blob/main/_autodocs/endpoints.md This JSON schema shows the structure of the response from the Spring Boot health check endpoint. ```json { "status": "UP", "components": { "db": {"status": "UP"}, "diskSpace": {"status": "UP"} } } ``` -------------------------------- ### Research with Web Tools Source: https://github.com/embabel/guide/blob/main/data/docs/index.md Command to research a topic using web tools. Requires Docker Desktop with MCP extension. ```shell execute "research the recent australian federal election. what is the position of the Greens party?" ``` -------------------------------- ### Configure Claude Desktop for Embabel MCP Source: https://github.com/embabel/guide/blob/main/README.md Add this configuration to your `claude_desktop_config.json` file to connect Claude Desktop to the Embabel development server. ```yaml { "mcpServers": { "embabel-dev": { "command": "npx", "args": [ "-y", "mcp-remote", "http://localhost:1337/sse", "--transport", "sse-only" ] }, ... } } ``` -------------------------------- ### GET /api/v1/data/stats Response Schema Source: https://github.com/embabel/guide/blob/main/_autodocs/endpoints.md This JSON schema outlines the structure of the response when retrieving statistics about ingested RAG content. ```json { "documentCount": 45, "chunkCount": 320, "contentElementCount": 450 } ``` -------------------------------- ### Run All Tests Source: https://github.com/embabel/guide/blob/main/scripts/INGESTION-TESTING.md Executes all unit and integration tests. Integration tests automatically set up Neo4j using Testcontainers. ```bash ./mvnw test ```