LangChain4j Examples

repository·main·Indexed 23 days ago

https://github.com/langchain4j/langchain4j-examples

A collection of practical, runnable examples for the LangChain4j library. Includes an Agentic Tutorial covering basic agents, sequential workflows, loops, parallelism, and human-in-the-loop validation. Features specialized projects such as a DBpedia semantic data extraction tool using Apache Jena and Azure OpenAI, GPULlama3.java for local LLM execution via TornadoVM, and Coffee Shop Assistant demos integrating LangChain4j with Helidon MP and Helidon SE.

Tokens
9.5K
Snippets
32
Records
51
Agent score
83%

What's inside langchain4j-examples

  1. Overview of the JavaFX Chat UI implementation

    main

    This project demonstrates how to build a JavaFX-based user interface for LangChain4j that visualizes streaming responses from an LLM (such as OpenAI).

    Key features demonstrated include:

    • Streaming Visualization: Real-time visualization of answers being streamed into a text box and a table as they are received.
    • Conversation History: A table that lists all previous application and search actions.
    • Memory Management: The model maintains memory of previous chat messages to track the context of the conversation.
    • JavaFX Bindings: Illustrates how to use JavaFX bindings to handle incoming streamed data from LangChain4j.
  2. Overview of DBpedia Example Project components

    main

    This project demonstrates semantic data extraction by combining DBpedia SPARQL queries with Azure OpenAI.

    Core Logic Flow:

    1. Subject Extraction: Uses Azure OpenAI to extract a subject from a natural language question (e.g., extracting "Napoleon" from "How many years did Napoleon live?").
    2. SPARQL Querying: Uses Apache Jena to query the DBpedia endpoint for data related to the extracted subject.
    3. Answer Generation: Uses the retrieved data and Azure OpenAI to generate a professional natural language response.

    Key Classes:

    • DbPediaSparqlExample: The main entry point handling SPARQL execution and OpenAI integration.
    • AzureOpenAIConfig: A Singleton class that reads credentials from ~/.azureopenapi/key.json.
  3. Explore LangChain4j examples and tutorials

    main

    This repository contains a collection of practical examples for the LangChain4j library. To learn how to use the library, you can explore different categories of examples:

    • Tutorials: Step-by-step guides for learning the core concepts.
    • Advanced RAG: Examples demonstrating advanced Retrieval-Augmented Generation (RAG) techniques.
    • Complex Agents: Implementations of agents that combine memory, tools, and RAG capabilities.
    • General Examples: A variety of other use cases and patterns.

    For community-contributed examples, visit the langchain4j-community-examples repository.

  4. Features of the Helidon SE LangChain4j Integration

    main

    The Coffee Shop Assistant demo highlights several key capabilities of the Helidon SE and LangChain4J integration:

    • OpenAI Chat Models: Integration with OpenAI for conversational capabilities.
    • RAG Components: Utilization of embedding models, embedding stores, ingestors, and content retrievers to provide context-aware answers.
    • Dependency Injection: Uses Helidon Inject to manage components.
    • Data Initialization: Demonstrates initializing an embedding store from a JSON file.
    • Callback Support: Support for callback functions to enhance AI-driven interactions.
    WARNING

    LangChain4J integration is currently a preview feature. The APIs are subject to change and will be finalized in a future release of Helidon.

  5. Explore LangChain4j Agentic Tutorial examples

    main

    The LangChain4j Agentic Tutorial provides a series of progressive examples demonstrating how to build complex agentic workflows. These range from basic single-agent setups to advanced orchestration patterns like supervisors, parallel execution, and human-in-the-loop validation.

    Available Patterns:

    • Basic Agents: String-based and structured output (POJO) agents.
    • Sequential Workflows: Untyped and typed sequential execution.
    • Loops: Basic loops with exit conditions and advanced loops with state tracking.
    • Parallelism: Concurrent agent execution and output aggregation.
    • Conditional Logic: Score-based branching and async conditional workflows.
    • Composition: Nested workflow composition.
    • Orchestration: Basic and advanced supervisor patterns.
    • Hybrid Systems: Combining deterministic (non-AI) operations with AI agents.
    • Human-in-the-loop: Simple validation and interactive chatbots with memory.
  6. Summary of Google AI Gemini Examples

    main

    The following examples are available in the module to demonstrate various capabilities:

    • Basic Chat: Example01_SimpleChat (Basic interaction with GoogleAiGeminiChatModel), Example02_StreamingChat (Real-time streaming).
    • Embeddings: Example03_SimpleEmbedding (Text to vectors via GoogleAiEmbeddingModel), Example07_EmbeddingWithTaskTypes (Configuring for retrieval, similarity, etc.).
    • Token Counting: Example04_TokenCounting (Estimating tokens via GoogleAiGeminiTokenCountEstimator).
    • Structured Output: Example05_ChatWithJsonResponse (JSON schema constraints).
    • Tools & Function Calling: Example06_ChatWithTools (Using @Tool annotation).
    • Multimodal: Example08_FileUpload (Using GeminiFiles API), Example09_MultimodalChat (Images + text).
    • Advanced Features: Example10_ChatWithThinking (Reasoning mode), Example11_ChatWithSafetySettings (Safety thresholds).
    • Batch Processing: Example12_BatchChatInline, Example13_BatchEmbeddingInline, Example14_BatchChatFromFile, Example15_BatchEmbedFromFile.
  7. How batch processing works in Google AI Gemini

    main

    Batch processing provides a 50% cost reduction compared to interactive requests with a 24-hour turnaround SLO. It is ideal for large-scale, non-urgent tasks.

    Batching Approaches

    • Inline: Best for small to medium batches. Supports up to 20MB of requests.
    • File-based: Best for large batches. Limited by the Files API (up to 2GB per file).

    Batch Workflow

    1. Submit: Use submit(...) to start a job (either inline via GeminiBatchRequest or from an uploaded file).
    2. Poll: Use retrieve(batchId) to check status until response.state().isTerminal() returns true.
    3. Process: Once the state is SUCCEEDED, access results via response.responses() or correlate outcomes with requests using response.results().
    4. Clean up: Use deleteBatchJob(batchId) and delete any uploaded files (though batches are automatically removed after a retention period).
  8. Define tools for Function Calling using @Tool

    main

    In LangChain4j, you can expose Java methods to a language model by annotating them with @Tool. This allows the model to invoke these methods to retrieve information it doesn't natively possess. Use @P to provide a description for the parameter, which helps the model understand how to pass arguments.

    @Tool("Get the status of a payment transaction")
    public Status paymentStatus(@P("The id of the payment transaction") String transaction) {
        System.out.println();
        return DATASET.get(new Transaction(transaction));
    }
  9. Build and run the Coffee Shop Assistant (Helidon MP Version)

    main

    This demo application showcases the integration between Helidon MP and LangChain4J. It uses Helidon Inject for dependency injection, OpenAI chat models, and embedding storage (initialized from a JSON file) to power an AI assistant.

    Note: The LangChain4J integration in Helidon is currently a preview feature and APIs are subject to change.

  10. Build and run the WildFly LangChain4j example

    main

    Follow these steps to build the application and start the WildFly server:

    1. Build the application using Maven:
    mvn clean install
    1. Start the server:
    ./target/server/bin/standalone.sh
    1. Interact with the application: You can access the minimal AIService ChatBot via a REST endpoint at http://localhost:8080/.
    mvn clean install
    ./target/server/bin/standalone.sh