langchain4j/README.md

304 lines
14 KiB
Markdown
Raw Normal View History

2023-07-07 15:19:39 +08:00
# LangChain for Java: Supercharge your Java application with the power of LLMs
2023-06-20 23:57:52 +08:00
2023-07-07 15:19:39 +08:00
## Project goals
The goal of this project is to simplify the integration of AI/LLM capabilities into your Java application.
2023-06-20 23:57:52 +08:00
2023-07-07 15:19:39 +08:00
This can be achieved thanks to:
2023-06-20 23:57:52 +08:00
2023-07-07 15:19:39 +08:00
- **A simple and coherent layer of abstractions**, designed to ensure that your code does not depend on concrete implementations such as LLM providers, embedding store providers, etc. This allows for easy swapping of components.
- **Numerous implementations of the above-mentioned abstractions**, providing you with a variety of LLMs and embedding stores to choose from.
- **Range of in-demand features on top of LLMs, such as:**
- The capability to **ingest your own data** (documentation, codebase, etc.), allowing the LLM to act and respond based on your data.
- **Autonomous agents** for delegating tasks (defined on the fly) to the LLM, which will strive to complete them.
- **Prompt templates** to help you achieve the highest possible quality of LLM responses.
- **Memory** to provide context to the LLM for your current and past conversations.
- **Structured outputs** for receiving responses from the LLM with a desired structure as Java POJOs.
- **"AI Services"** for declaratively defining complex AI behavior behind a simple API.
- **Chains** to reduce the need for extensive boilerplate code in common use-cases.
- **Auto-moderation** to ensure that all inputs and outputs to/from the LLM are not harmful.
2023-06-20 23:57:52 +08:00
2023-07-03 05:29:35 +08:00
## News
2023-07-12 02:50:43 +08:00
11 July:
2023-07-07 15:19:39 +08:00
2023-07-12 02:50:43 +08:00
- Added ["Dynamic Tools"](https://github.com/langchain4j/langchain4j-examples/blob/main/other-examples/src/main/java/ServiceWithDynamicToolsExample.java):
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](https://rapidapi.com/judge0-official/api/judge0-ce/pricing), for code execution. You can subscribe and receive 50 free executions per day.
2023-07-07 15:19:39 +08:00
2023-07-12 02:50:43 +08:00
5 July:
- Now you can [add your custom knowledge base to "AI Services"](https://github.com/langchain4j/langchain4j-examples/blob/main/spring-boot-example/src/test/java/dev/example/CustomerSupportApplicationTest.java).
2023-07-07 15:19:39 +08:00
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.
2023-07-06 00:55:06 +08:00
2023-07-12 02:50:43 +08:00
3 July:
2023-07-07 15:19:39 +08:00
2023-07-03 21:12:43 +08:00
- Added support for Spring Boot 3
2023-07-12 02:50:43 +08:00
2 July:
2023-07-07 15:19:39 +08:00
2023-07-03 05:29:35 +08:00
- [Added Spring Boot Starter](https://github.com/langchain4j/langchain4j-examples/blob/main/spring-boot-example/src/test/java/dev/example/CustomerSupportApplicationTest.java)
- Added support for HuggingFace models
2023-07-12 02:50:43 +08:00
1 July:
2023-07-07 15:19:39 +08:00
2023-07-12 02:50:43 +08:00
- [Added "Tools"](https://github.com/langchain4j/langchain4j-examples/blob/main/other-examples/src/main/java/ServiceWithToolsExample.java) (support for OpenAI functions)
2023-07-03 05:29:35 +08:00
2023-06-20 23:57:52 +08:00
## Highlights
2023-07-07 15:19:39 +08:00
2023-06-20 23:57:52 +08:00
You can declaratively define concise "AI Services" that are powered by LLMs:
2023-07-07 15:19:39 +08:00
2023-07-02 01:18:49 +08:00
```java
2023-06-30 04:15:38 +08:00
interface Assistant {
2023-06-20 23:57:52 +08:00
2023-06-30 04:15:38 +08:00
String chat(String userMessage);
2023-06-20 23:57:52 +08:00
}
2023-07-07 15:19:39 +08:00
Assistant assistant = AiServices.create(Assistant.class, model);
2023-06-30 04:15:38 +08:00
2023-07-07 15:19:39 +08:00
String answer = assistant.chat("Hello");
System.out.println(answer); // Hello! How can I assist you today?
2023-06-30 04:15:38 +08:00
```
You can use LLM as a classifier:
2023-07-07 15:19:39 +08:00
2023-07-02 01:18:49 +08:00
```java
2023-06-30 04:15:38 +08:00
enum Sentiment {
POSITIVE, NEUTRAL, NEGATIVE;
2023-06-20 23:57:52 +08:00
}
2023-07-07 15:19:39 +08:00
2023-06-30 04:15:38 +08:00
interface SentimentAnalyzer {
2023-06-20 23:57:52 +08:00
2023-06-30 04:15:38 +08:00
@UserMessage("Analyze sentiment of {{it}}")
Sentiment analyzeSentimentOf(String text);
2023-06-20 23:57:52 +08:00
2023-06-30 04:15:38 +08:00
@UserMessage("Does {{it}} have a positive sentiment?")
boolean isPositive(String text);
}
2023-06-20 23:57:52 +08:00
2023-07-07 15:19:39 +08:00
SentimentAnalyzer sentimentAnalyzer = AiServices.create(SentimentAnalyzer.class, model);
2023-06-20 23:57:52 +08:00
2023-07-07 15:19:39 +08:00
Sentiment sentiment = sentimentAnalyzer.analyzeSentimentOf("It is good!");
// POSITIVE
2023-06-20 23:57:52 +08:00
2023-07-07 15:19:39 +08:00
boolean positive = sentimentAnalyzer.isPositive("It is bad!");
// false
2023-06-20 23:57:52 +08:00
```
You can easily extract structured information from unstructured data:
2023-07-07 15:19:39 +08:00
2023-07-02 01:18:49 +08:00
```java
2023-06-20 23:57:52 +08:00
class Person {
private String firstName;
private String lastName;
private LocalDate birthDate;
2023-06-30 04:15:38 +08:00
public String toString() {...}
2023-06-20 23:57:52 +08:00
}
interface PersonExtractor {
2023-06-30 04:15:38 +08:00
@UserMessage("Extract information about a person from {{it}}")
2023-06-20 23:57:52 +08:00
Person extractPersonFrom(String text);
}
2023-07-07 15:19:39 +08:00
PersonExtractor extractor = AiServices.create(PersonExtractor.class, model);
2023-06-20 23:57:52 +08:00
2023-07-07 15:19:39 +08:00
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 }
2023-06-20 23:57:52 +08:00
```
2023-07-06 01:16:04 +08:00
You can define more sophisticated prompt templates using mustache syntax:
2023-07-07 15:19:39 +08:00
2023-07-02 01:18:49 +08:00
```java
2023-06-20 23:57:52 +08:00
interface Translator {
@SystemMessage("You are a professional translator into {{language}}")
@UserMessage("Translate the following text: {{text}}")
String translate(@V("text") String text, @V("language") String language);
}
2023-07-07 15:19:39 +08:00
Translator translator = AiServices.create(Translator.class, model);
2023-06-20 23:57:52 +08:00
2023-07-07 15:19:39 +08:00
String translation = translator.translate("Hello, how are you?", "Italian");
// Ciao, come stai?
2023-06-20 23:57:52 +08:00
```
2023-07-02 00:55:48 +08:00
You can provide tools that LLMs can use! Can be anything: retrieve information from DB, call APIs, etc.
2023-07-03 05:29:35 +08:00
See example [here](https://github.com/langchain4j/langchain4j-examples/blob/main/other-examples/src/main/java/ServiceWithToolsExample.java).
2023-07-02 00:55:48 +08:00
2023-07-03 21:12:43 +08:00
## Compatibility
2023-07-07 15:19:39 +08:00
2023-07-03 21:12:43 +08:00
- Java: 8 or higher
2023-07-06 01:22:40 +08:00
- Spring Boot: 2 or 3
2023-07-03 21:12:43 +08:00
2023-07-07 15:19:39 +08:00
## Getting started
1. Add langchain4j dependency to your project:
- Maven:
```
<dependency>
<groupId>dev.langchain4j</groupId>
<artifactId>langchain4j</artifactId>
<version>0.12.0</version>
2023-07-07 15:19:39 +08:00
</dependency>
```
- Gradle:
```
implementation 'dev.langchain4j:langchain4j:0.12.0'
2023-07-07 15:19:39 +08:00
```
2. Import your OpenAI/HuggingFace API key:
```java
String apiKey = System.getenv("OPENAI_API_KEY");
```
[How to gen an API key?](https://github.com/langchain4j/langchain4j#how-to-get-an-api-key)
3. Create an instance of a model and start interacting:
```java
OpenAiChatModel model = OpenAiChatModel.withApiKey(apiKey);
AiMessage answer = model.sendUserMessage("Hello world!").get();
System.out.println(answer.text()); // Hello! How can I assist you today?
```
2023-06-20 23:57:52 +08:00
2023-07-07 15:19:39 +08:00
## Code examples
2023-06-20 23:57:52 +08:00
2023-07-07 15:19:39 +08:00
Please see more examples of how LangChain4j can be used:
- [Examples in plain Java](https://github.com/langchain4j/langchain4j-examples/tree/main/other-examples/src/main/java)
- [Example with Spring Boot](https://github.com/langchain4j/langchain4j-examples/blob/main/spring-boot-example/src/test/java/dev/example/CustomerSupportApplicationTest.java)
2023-06-20 23:57:52 +08:00
## Disclaimer
2023-07-07 15:19:39 +08:00
2023-06-20 23:57:52 +08:00
Please note that the library is in active development and:
2023-07-07 15:19:39 +08:00
2023-06-20 23:57:52 +08:00
- Many features are still missing. We are working hard on implementing them ASAP.
2023-07-07 15:19:39 +08:00
- 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.
2023-06-21 03:05:42 +08:00
- We need your input! Please let us know what features you need and your concerns about the current implementation.
2023-06-20 23:57:52 +08:00
2023-06-21 00:15:18 +08:00
## Current capabilities:
2023-07-07 15:19:39 +08:00
2023-07-02 00:55:48 +08:00
- AI Services:
2023-07-03 05:29:35 +08:00
- [Simple](https://github.com/langchain4j/langchain4j-examples/blob/main/other-examples/src/main/java/SimpleServiceExample.java)
- [With Memory](https://github.com/langchain4j/langchain4j-examples/blob/main/other-examples/src/main/java/ServiceWithMemoryExample.java)
- [With Tools](https://github.com/langchain4j/langchain4j-examples/blob/main/other-examples/src/main/java/ServiceWithToolsExample.java)
- [With Auto-Moderation](https://github.com/langchain4j/langchain4j-examples/blob/main/other-examples/src/main/java/ServiceWithAutoModerationExample.java)
- [With Structured Outputs, Structured Prompts, etc](https://github.com/langchain4j/langchain4j-examples/blob/main/other-examples/src/main/java/OtherServiceExamples.java)
2023-06-20 23:57:52 +08:00
- Integration with [OpenAI (ChatGPT)](https://platform.openai.com/docs/introduction) for:
2023-07-03 05:29:35 +08:00
- [Chats](https://platform.openai.com/docs/guides/chat) (sync + streaming + functions)
2023-06-20 23:57:52 +08:00
- [Completions](https://platform.openai.com/docs/guides/completion) (sync + streaming)
- [Embeddings](https://platform.openai.com/docs/guides/embeddings)
2023-06-27 02:24:15 +08:00
- Integration with [HuggingFace Inference API](https://huggingface.co/docs/api-inference/index) for:
2023-07-07 15:19:39 +08:00
- [Chats](https://huggingface.co/docs/api-inference/detailed_parameters#text-generation-task)
- [Completions](https://huggingface.co/docs/api-inference/detailed_parameters#text-generation-task)
- [Embeddings](https://huggingface.co/docs/api-inference/detailed_parameters#feature-extraction-task)
2023-07-03 05:29:35 +08:00
- [Memory for Chats](https://github.com/langchain4j/langchain4j-examples/blob/main/other-examples/src/main/java/ChatMemoryExamples.java)
- [Chat with Documents](https://github.com/langchain4j/langchain4j-examples/blob/main/other-examples/src/main/java/ChatWithDocumentsExamples.java)
2023-06-20 23:57:52 +08:00
- Integration with [Pinecone](https://docs.pinecone.io/docs/overview) embedding store
- In-memory embedding store (for prototyping and testing)
2023-07-03 05:29:35 +08:00
- [Structured outputs](https://github.com/langchain4j/langchain4j-examples/blob/main/other-examples/src/main/java/OtherServiceExamples.java)
- [Prompt templates](https://github.com/langchain4j/langchain4j-examples/blob/main/other-examples/src/main/java/PromptTemplateExamples.java)
- [Structured prompt templates](https://github.com/langchain4j/langchain4j-examples/blob/main/other-examples/src/main/java/StructuredPromptTemplateExamples.java)
- [Streaming of LLM responses](https://github.com/langchain4j/langchain4j-examples/blob/main/other-examples/src/main/java/StreamingExamples.java)
- [Loading text and PDF documents from the file system and via URL](https://github.com/langchain4j/langchain4j-examples/blob/main/other-examples/src/main/java/ChatWithDocumentsExamples.java)
- [Splitting documents into segments](https://github.com/langchain4j/langchain4j-examples/blob/main/other-examples/src/main/java/ChatWithDocumentsExamples.java):
2023-07-07 15:19:39 +08:00
- by paragraph
- by sentence
- by character count
2023-06-21 00:15:18 +08:00
- Token count estimation (so that you can predict how much you will pay)
2023-06-20 23:57:52 +08:00
## Coming soon:
2023-07-07 15:19:39 +08:00
2023-06-20 23:57:52 +08:00
- Extending "AI Service" features
- Integration with more LLM providers (commercial and open)
- Integrations with more embedding stores (commercial and open)
- Support for more document types
- Long-term memory for chatbots and agents
2023-07-02 00:55:48 +08:00
- Chain-of-Thought and Tree-of-Thought
2023-06-20 23:57:52 +08:00
2023-06-21 00:15:18 +08:00
**Please [let us know what features you need](https://github.com/langchain4j/langchain4j/issues/new)!**
2023-06-20 23:57:52 +08:00
## Request features
Please [let us know what features you need](https://github.com/ai-for-java/ai4j/issues/new).
## Contribute
Please help us make this open-source library better by contributing.
2023-07-07 15:19:39 +08:00
## 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
2023-06-20 23:57:52 +08:00
## Best practices
We highly recommend
2023-06-21 03:05:42 +08:00
watching [this amazing 90-minute tutorial](https://www.deeplearning.ai/short-courses/chatgpt-prompt-engineering-for-developers/)
2023-06-20 23:57:52 +08:00
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 [magical "Lets think step by step" instruction](https://arxiv.org/pdf/2205.11916.pdf) 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.
2023-06-21 03:05:42 +08:00
- Use unusual delimiters, such as \```triple backticks``` to help the LLM distinguish
2023-06-20 23:57:52 +08:00
data or input from instructions.
2023-07-07 15:19:39 +08:00
## 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](https://www.howtogeek.com/885918/how-to-get-an-openai-api-key/).
For embeddings, we recommend using one of the models from the [HuggingFace MTEB leaderboard](https://huggingface.co/spaces/mteb/leaderboard).
You'll have to find the best one for your specific use case.
Here's how to get a HuggingFace API key:
- Create an account on https://huggingface.co
- Go to https://huggingface.co/settings/tokens
- Generate a new access token