Skip to content
View langchain4j's full-sized avatar
Block or Report

Block or report langchain4j

Block user

Prevent this user from interacting with your repositories and sending you notifications. Learn more about blocking users.

You must be logged in to block users.

Add an optional note:
Please don't include any personal information such as legal names or email addresses. Maximum 100 characters, markdown supported. This note will be visible to only you.
Report abuse

Contact GitHub support about this user’s behavior. Learn more about reporting abuse.

Report abuse
langchain4j/README.md

LangChain for Java: Supercharge your Java application with the power of LLMs

Introduction

Welcome!

The goal of LangChain4j is to simplify integrating AI/LLM capabilities into Java applications.

Here's how:

  1. Unified APIs: LLM providers (like OpenAI or Google Vertex AI) and embedding (vector) stores (such as Pinecone or Vespa) use proprietary APIs. LangChain4j offers a unified API to avoid the need for learning and implementing specific APIs for each of them. To experiment with a different LLM or embedding store, you can easily switch between them without the need to rewrite your code. LangChain4j currently supports over 10 popular LLM providers and more than 15 embedding stores. Think of it as a Hibernate, but for LLMs and embedding stores.
  2. Comprehensive Toolbox: During the past year, the community has been building numerous LLM-powered applications, identifying common patterns, abstractions, and techniques. LangChain4j has refined these into practical code. Our toolbox includes tools ranging from low-level prompt templating, memory management, and output parsing to high-level patterns like Agents and RAGs. For each pattern and abstraction, we provide an interface along with multiple ready-to-use implementations based on proven techniques. Whether you're building a chatbot or developing a RAG with a complete pipeline from data ingestion to retrieval, LangChain4j offers a wide variety of options.
  3. Numerous Examples: These examples showcase how to begin creating various LLM-powered applications, providing inspiration and enabling you to start building quickly.

LangChain4j began development in early 2023 amid the ChatGPT hype. We noticed a lack of Java counterparts to the numerous Python and JavaScript LLM libraries and frameworks, and we had to fix that! Although "LangChain" is in our name, the project is a fusion of ideas and concepts from LangChain, Haystack, LlamaIndex, and the broader community, spiced up with a touch of our own innovation.

We actively monitor community developments, aiming to quickly incorporate new techniques and integrations, ensuring you stay up-to-date. The library is under active development. While some features from the Python version of LangChain are still being worked on, the core functionality is in place, allowing you to start building LLM-powered apps now!

For easier integration, LangChain4j also includes integration with Quarkus (extension) and Spring Boot (starters).

Code Examples

Please see examples of how LangChain4j can be used in langchain4j-examples repo:

Documentation

Documentation can be found here.

Tutorials

Tutorials can be found here.

Useful Materials

Library Structure

LangChain4j features a modular design, comprising:

  • The langchain4j-core module, which defines core abstractions (such as ChatLanguageModel and EmbeddingStore) and their APIs.
  • The main langchain4j module, containing useful tools like ChatMemory, OutputParser as well as a high-level features like AiServices.
  • A wide array of langchain4j-xyz modules, each providing integration with various LLM providers and embedding stores into LangChain4j. You can use the langchain4j-xyz modules independently. For additional features, simply import the main langchain4j dependency.

News

30 January:

Previous News

22 December:

12 November:

29 September:

  • Updates to models API: return Response<T> instead of T. Response<T> contains token usage and finish reason.
  • All model and embedding store integrations now live in their own modules
  • Integration with Vespa by @Heezer
  • Integration with Elasticsearch by @Martin7-1
  • Integration with Redis by @Martin7-1
  • Integration with Milvus by @IuriiKoval
  • Integration with Astra DB and Cassandra by @clun
  • Added support for overlap in document splitters
  • Some bugfixes and smaller improvements

29 August:

19 August:

10 August:

26 July:

21 July:

17 July:

  • You can now try out OpenAI's gpt-3.5-turbo and text-embedding-ada-002 models with LangChain4j for free, without needing an OpenAI account and keys! Simply use the API key "demo".

15 July:

  • Added EmbeddingStoreIngestor
  • Redesigned document loaders (see FileSystemDocumentLoader)
  • Simplified ConversationalRetrievalChain
  • Renamed DocumentSegment into TextSegment
  • Added output parsers for numeric types
  • Added @UserName for AI Services
  • Fixed 23 and 24

11 July:

  • Added "Dynamic Tools": Now, the LLM can generate code for tasks that require precise calculations, such as math and string manipulation. This will be dynamically executed in a style akin to GPT-4's code interpreter! We use Judge0, hosted by Rapid API, for code execution. You can subscribe and receive 50 free executions per day.

5 July:

  • Now you can add your custom knowledge base to "AI Services". Relevant information will be automatically retrieved and injected into the prompt. This way, the LLM will have a context of your data and will answer based on it!
  • The current date and time can now be automatically injected into the prompt using special {{current_date}}, {{current_time}} and {{current_date_time}} placeholders.

3 July:

  • Added support for Spring Boot 3

2 July:

1 July:

Highlights

You can define declarative "AI Services" that are powered by LLMs:

interface Assistant {

    String chat(String userMessage);
}

Assistant assistant = AiServices.create(Assistant.class, model);

String answer = assistant.chat("Hello");
    
System.out.println(answer);
// Hello! How can I assist you today?

You can use LLM as a classifier:

enum Sentiment {
    POSITIVE, NEUTRAL, NEGATIVE
}

interface SentimentAnalyzer {

    @UserMessage("Analyze sentiment of {{it}}")
    Sentiment analyzeSentimentOf(String text);

    @UserMessage("Does {{it}} have a positive sentiment?")
    boolean isPositive(String text);
}

SentimentAnalyzer sentimentAnalyzer = AiServices.create(SentimentAnalyzer.class, model);

Sentiment sentiment = sentimentAnalyzer.analyzeSentimentOf("It is good!");
// POSITIVE

boolean positive = sentimentAnalyzer.isPositive("It is bad!");
// false

You can easily extract structured information from unstructured data:

class Person {

    private String firstName;
    private String lastName;
    private LocalDate birthDate;
}

interface PersonExtractor {

    @UserMessage("Extract information about a person from {{text}}")
    Person extractPersonFrom(@V("text") String text);
}

PersonExtractor extractor = AiServices.create(PersonExtractor.class, model);

String text = "In 1968, amidst the fading echoes of Independence Day, "
    + "a child named John arrived under the calm evening sky. "
    + "This newborn, bearing the surname Doe, marked the start of a new journey.";

Person person = extractor.extractPersonFrom(text);
// Person { firstName = "John", lastName = "Doe", birthDate = 1968-07-04 }

You can provide tools that LLMs can use! It can be anything: retrieve information from DB, call APIs, etc. See example here.

Compatibility

  • Java: 8 or higher
  • Spring Boot: 2 or 3

Getting started

  1. Add LangChain4j OpenAI dependency to your project:

    • Maven:
      <dependency>
          <groupId>dev.langchain4j</groupId>
          <artifactId>langchain4j-open-ai</artifactId>
          <version>0.27.1</version>
      </dependency>
    • Gradle:
      implementation 'dev.langchain4j:langchain4j-open-ai:0.27.1'
  2. Import your OpenAI API key:

    String apiKey = System.getenv("OPENAI_API_KEY");

    You can also use the API key demo to test OpenAI, which we provide for free. How to get an API key?

  3. Create an instance of a model and start interacting:

    OpenAiChatModel model = OpenAiChatModel.withApiKey(apiKey);
    
    String answer = model.generate("Hello world!");
    
    System.out.println(answer); // Hello! How can I assist you today?

Supported LLM Integrations (Docs)

Provider Native Image Completion Streaming Async Completion Async Streaming Embedding Image Generation ReRanking
OpenAI
Azure OpenAI
Hugging Face
Amazon Bedrock
Google Vertex AI Gemini
Google Vertex AI
Mistral AI
DashScope
LocalAI
Ollama
Cohere
Qianfan
ChatGLM
Nomic

Disclaimer

Please note that the library is in active development and:

  • Some features are still missing. We are working hard on implementing them ASAP.
  • API might change at any moment. At this point, we prioritize good design in the future over backward compatibility now. We hope for your understanding.
  • We need your input! Please let us know what features you need and your concerns about the current implementation.

Current features (this list is outdated, we have much more):

Coming soon:

  • Extending "AI Service" features
  • Integration with more LLM providers (commercial and free)
  • Integrations with more embedding stores (commercial and free)
  • Support for more document types
  • Long-term memory for chatbots and agents
  • Chain-of-Thought and Tree-of-Thought

Request features

Please let us know what features you need!

Contribute

Please help us make this open-source library better by contributing.

Some guidelines:

  1. Follow Google's Best Practices for Java Libraries.
  2. Keep the code compatible with Java 8.
  3. Avoid adding new dependencies as much as possible. If absolutely necessary, try to (re)use the same libraries which are already present.
  4. Follow existing code styles present in the project.
  5. Ensure to add Javadoc where necessary.
  6. Provide unit and/or integration tests for your code.
  7. Large features should be discussed with maintainers before implementation.

Use cases

You might ask why would I need all of this? Here are a couple of examples:

  • You want to implement a custom AI-powered chatbot that has access to your data and behaves the way you want it:
    • Customer support chatbot that can:
      • politely answer customer questions
      • take /change/cancel orders
    • Educational assistant that can:
      • Teach various subjects
      • Explain unclear parts
      • Assess user's understanding/knowledge
  • You want to process a lot of unstructured data (files, web pages, etc) and extract structured information from them. For example:
    • extract insights from customer reviews and support chat history
    • extract interesting information from the websites of your competitors
    • extract insights from CVs of job applicants
  • You want to generate information, for example:
    • Emails tailored for each of your customers
    • Content for your app/website:
      • Blog posts
      • Stories
  • You want to transform information, for example:
    • Summarize
    • Proofread and rewrite
    • Translate

Best practices

We highly recommend watching this amazing 90-minute tutorial on prompt engineering best practices, presented by Andrew Ng (DeepLearning.AI) and Isa Fulford (OpenAI). This course will teach you how to use LLMs efficiently and achieve the best possible results. Good investment of your time!

Here are some best practices for using LLMs:

  • Be responsible. Use AI for Good.
  • Be specific. The more specific your query, the best results you will get.
  • Add a "Let’s think step by step" instruction to your prompt.
  • Specify steps to achieve the desired goal yourself. This will make the LLM do what you want it to do.
  • Provide examples. Sometimes it is best to show LLM a few examples of what you want instead of trying to explain it.
  • Ask LLM to provide structured output (JSON, XML, etc). This way you can parse response more easily and distinguish different parts of it.
  • Use unusual delimiters, such as ```triple backticks``` to help the LLM distinguish data or input from instructions.

How to get an API key

You will need an API key from OpenAI (paid) or HuggingFace (free) to use LLMs hosted by them.

We recommend using OpenAI LLMs (gpt-3.5-turbo and gpt-4) as they are by far the most capable and are reasonably priced.

It will cost approximately $0.01 to generate 10 pages (A4 format) of text with gpt-3.5-turbo. With gpt-4, the cost will be $0.30 to generate the same amount of text. However, for some use cases, this higher cost may be justified.

How to get OpenAI API key.

For embeddings, we recommend using one of the models from the HuggingFace MTEB leaderboard. You'll have to find the best one for your specific use case.

Here's how to get a HuggingFace API key:

Popular repositories

  1. langchain4j langchain4j Public

    Java version of LangChain

    Java 1.8k 297

  2. langchain4j-examples langchain4j-examples Public

    Java 145 77

  3. langchain4j-embeddings langchain4j-embeddings Public

    Java 27 12

  4. awesome-langchain awesome-langchain Public

    Forked from kyrolabs/awesome-langchain

    😎 Awesome list of tools and projects with the awesome LangChain framework

    10

  5. langchain4j-spring langchain4j-spring Public

    LangChain4j integration with Spring

    Java 6 7

  6. langchain-java langchain-java Public

    Java implementation for LangChain

    4

709 contributions in the last year

No contributions on February 12th.No contributions on February 19th.No contributions on February 26th.No contributions on March 5th.No contributions on March 12th.No contributions on March 19th.No contributions on March 26th.No contributions on April 2nd.No contributions on April 9th.No contributions on April 16th.No contributions on April 23rd.No contributions on April 30th.No contributions on May 7th.No contributions on May 14th.No contributions on May 21st.No contributions on May 28th.No contributions on June 4th.No contributions on June 11th.No contributions on June 18th.No contributions on June 25th.1 contribution on July 2nd.No contributions on July 9th.4 contributions on July 16th.7 contributions on July 23rd.1 contribution on July 30th.13 contributions on August 6th.9 contributions on August 13th.4 contributions on August 20th.2 contributions on August 27th.2 contributions on September 3rd.No contributions on September 10th.2 contributions on September 17th.2 contributions on September 24th.No contributions on October 1st.1 contribution on October 8th.No contributions on October 15th.No contributions on October 22nd.No contributions on October 29th.No contributions on November 5th.2 contributions on November 12th.4 contributions on November 19th.No contributions on November 26th.No contributions on December 3rd.No contributions on December 10th.No contributions on December 17th.6 contributions on December 24th.No contributions on December 31st.3 contributions on January 7th.3 contributions on January 14th.No contributions on January 21st.No contributions on January 28th.No contributions on February 4th.No contributions on February 11th.No contributions on February 13th.No contributions on February 20th.No contributions on February 27th.No contributions on March 6th.No contributions on March 13th.No contributions on March 20th.No contributions on March 27th.No contributions on April 3rd.No contributions on April 10th.No contributions on April 17th.No contributions on April 24th.1 contribution on May 1st.No contributions on May 8th.No contributions on May 15th.No contributions on May 22nd.No contributions on May 29th.3 contributions on June 5th.No contributions on June 12th.No contributions on June 19th.No contributions on June 26th.4 contributions on July 3rd.No contributions on July 10th.4 contributions on July 17th.4 contributions on July 24th.2 contributions on July 31st.2 contributions on August 7th.No contributions on August 14th.3 contributions on August 21st.8 contributions on August 28th.1 contribution on September 4th.1 contribution on September 11th.2 contributions on September 18th.No contributions on September 25th.No contributions on October 2nd.5 contributions on October 9th.No contributions on October 16th.1 contribution on October 23rd.No contributions on October 30th.No contributions on November 6th.No contributions on November 13th.No contributions on November 20th.No contributions on November 27th.7 contributions on December 4th.1 contribution on December 11th.8 contributions on December 18th.No contributions on December 25th.No contributions on January 1st.12 contributions on January 8th.13 contributions on January 15th.2 contributions on January 22nd.17 contributions on January 29th.10 contributions on February 5th.No contributions on February 12th.No contributions on February 14th.No contributions on February 21st.No contributions on February 28th.No contributions on March 7th.No contributions on March 14th.No contributions on March 21st.No contributions on March 28th.No contributions on April 4th.No contributions on April 11th.No contributions on April 18th.No contributions on April 25th.No contributions on May 2nd.No contributions on May 9th.No contributions on May 16th.No contributions on May 23rd.No contributions on May 30th.No contributions on June 6th.No contributions on June 13th.7 contributions on June 20th.No contributions on June 27th.No contributions on July 4th.4 contributions on July 11th.2 contributions on July 18th.3 contributions on July 25th.1 contribution on August 1st.2 contributions on August 8th.1 contribution on August 15th.2 contributions on August 22nd.3 contributions on August 29th.No contributions on September 5th.No contributions on September 12th.3 contributions on September 19th.No contributions on September 26th.No contributions on October 3rd.No contributions on October 10th.3 contributions on October 17th.No contributions on October 24th.No contributions on October 31st.2 contributions on November 7th.No contributions on November 14th.No contributions on November 21st.No contributions on November 28th.3 contributions on December 5th.6 contributions on December 12th.10 contributions on December 19th.No contributions on December 26th.No contributions on January 2nd.22 contributions on January 9th.5 contributions on January 16th.5 contributions on January 23rd.35 contributions on January 30th.1 contribution on February 6th.No contributions on February 13th.No contributions on February 15th.No contributions on February 22nd.No contributions on March 1st.No contributions on March 8th.No contributions on March 15th.No contributions on March 22nd.No contributions on March 29th.No contributions on April 5th.No contributions on April 12th.No contributions on April 19th.No contributions on April 26th.No contributions on May 3rd.No contributions on May 10th.No contributions on May 17th.No contributions on May 24th.No contributions on May 31st.No contributions on June 7th.No contributions on June 14th.3 contributions on June 21st.No contributions on June 28th.3 contributions on July 5th.2 contributions on July 12th.No contributions on July 19th.2 contributions on July 26th.3 contributions on August 2nd.4 contributions on August 9th.1 contribution on August 16th.1 contribution on August 23rd.3 contributions on August 30th.No contributions on September 6th.No contributions on September 13th.No contributions on September 20th.1 contribution on September 27th.2 contributions on October 4th.No contributions on October 11th.No contributions on October 18th.No contributions on October 25th.No contributions on November 1st.No contributions on November 8th.No contributions on November 15th.No contributions on November 22nd.No contributions on November 29th.No contributions on December 6th.1 contribution on December 13th.6 contributions on December 20th.10 contributions on December 27th.14 contributions on January 3rd.10 contributions on January 10th.6 contributions on January 17th.5 contributions on January 24th.3 contributions on January 31st.3 contributions on February 7th.No contributions on February 14th.No contributions on February 16th.No contributions on February 23rd.No contributions on March 2nd.No contributions on March 9th.No contributions on March 16th.No contributions on March 23rd.No contributions on March 30th.No contributions on April 6th.No contributions on April 13th.No contributions on April 20th.No contributions on April 27th.No contributions on May 4th.No contributions on May 11th.No contributions on May 18th.No contributions on May 25th.No contributions on June 1st.No contributions on June 8th.No contributions on June 15th.No contributions on June 22nd.No contributions on June 29th.1 contribution on July 6th.1 contribution on July 13th.No contributions on July 20th.3 contributions on July 27th.3 contributions on August 3rd.4 contributions on August 10th.No contributions on August 17th.2 contributions on August 24th.No contributions on August 31st.2 contributions on September 7th.2 contributions on September 14th.7 contributions on September 21st.2 contributions on September 28th.3 contributions on October 5th.No contributions on October 12th.No contributions on October 19th.No contributions on October 26th.No contributions on November 2nd.No contributions on November 9th.No contributions on November 16th.No contributions on November 23rd.No contributions on November 30th.No contributions on December 7th.9 contributions on December 14th.27 contributions on December 21st.No contributions on December 28th.No contributions on January 4th.No contributions on January 11th.1 contribution on January 18th.16 contributions on January 25th.8 contributions on February 1st.33 contributions on February 8th.No contributions on February 15th.No contributions on February 17th.No contributions on February 24th.No contributions on March 3rd.No contributions on March 10th.No contributions on March 17th.No contributions on March 24th.No contributions on March 31st.No contributions on April 7th.No contributions on April 14th.No contributions on April 21st.No contributions on April 28th.No contributions on May 5th.No contributions on May 12th.No contributions on May 19th.No contributions on May 26th.No contributions on June 2nd.No contributions on June 9th.No contributions on June 16th.No contributions on June 23rd.No contributions on June 30th.2 contributions on July 7th.No contributions on July 14th.3 contributions on July 21st.No contributions on July 28th.1 contribution on August 4th.No contributions on August 11th.5 contributions on August 18th.1 contribution on August 25th.No contributions on September 1st.No contributions on September 8th.2 contributions on September 15th.2 contributions on September 22nd.1 contribution on September 29th.No contributions on October 6th.No contributions on October 13th.1 contribution on October 20th.4 contributions on October 27th.No contributions on November 3rd.7 contributions on November 10th.No contributions on November 17th.1 contribution on November 24th.No contributions on December 1st.6 contributions on December 8th.4 contributions on December 15th.36 contributions on December 22nd.1 contribution on December 29th.No contributions on January 5th.No contributions on January 12th.1 contribution on January 19th.23 contributions on January 26th.6 contributions on February 2nd.30 contributions on February 9th.No contributions on February 16th.No contributions on February 18th.No contributions on February 25th.No contributions on March 4th.No contributions on March 11th.No contributions on March 18th.No contributions on March 25th.No contributions on April 1st.No contributions on April 8th.No contributions on April 15th.No contributions on April 22nd.No contributions on April 29th.No contributions on May 6th.No contributions on May 13th.No contributions on May 20th.No contributions on May 27th.No contributions on June 3rd.No contributions on June 10th.No contributions on June 17th.No contributions on June 24th.3 contributions on July 1st.No contributions on July 8th.11 contributions on July 15th.No contributions on July 22nd.4 contributions on July 29th.1 contribution on August 5th.No contributions on August 12th.2 contributions on August 19th.2 contributions on August 26th.1 contribution on September 2nd.No contributions on September 9th.No contributions on September 16th.No contributions on September 23rd.No contributions on September 30th.No contributions on October 7th.No contributions on October 14th.No contributions on October 21st.No contributions on October 28th.No contributions on November 4th.No contributions on November 11th.4 contributions on November 18th.3 contributions on November 25th.No contributions on December 2nd.No contributions on December 9th.4 contributions on December 16th.20 contributions on December 23rd.5 contributions on December 30th.2 contributions on January 6th.3 contributions on January 13th.No contributions on January 20th.No contributions on January 27th.3 contributions on February 3rd.No contributions on February 10th.No contributions on February 17th.
Contribution Graph
Day of Week February March April May June July August September October November December January February
Sunday
Monday
Tuesday
Wednesday
Thursday
Friday
Saturday
Less
No contributions.
Low contributions.
Medium-low contributions.
Medium-high contributions.
High contributions.
More

Contribution activity

February 2024

Created a pull request in langchain4j/langchain4j that received 3 comments

Metadata Filtering

This is a draft. Comments and suggestions are welcome! Metadata Filtering API This PR introduces a metadata filtering feature, supported by many em…

+2,927 −98 lines changed 3 comments
Opened 10 other pull requests in 3 repositories
langchain4j/langchain4j 6 merged
langchain4j/langchain4j-embeddings 2 merged
langchain4j/langchain4j-spring 2 merged
Reviewed 21 pull requests in 2 repositories
langchain4j/langchain4j 17 pull requests
langchain4j/langchain4j-examples 4 pull requests

Created an issue in langchain4j/langchain4j that received 4 comments

[FEATURE] Add responseFormat to AzureOpenAiChatModel and AzureOpenAiStreamingChatModel

Currently there is no way to enable json mode in Azure OpenAI, as well as many other parameters are missing. AzureOpenAiChatModel and AzureOpenAiSt…

4 comments
Opened 2 other issues in 1 repository

Seeing something unexpected? Take a look at the GitHub profile guide.