Overview
Intent classification and entity extraction (check out this basic AI tutorial) are foundational building blocks for conversational and automation systems. An intent represents what the user wants to achieve, while entities represent structured data embedded in natural language, such as order IDs, item names, or reasons.
Example
The following example sends a user message to an Ollama-hosted phi3:mini-128k model and requests a strict JSON response containing the detected intent and entities. The Java program then prints the raw model output.
package com.logicbig.example;
import dev.langchain4j.data.message.AiMessage;
import dev.langchain4j.data.message.SystemMessage;
import dev.langchain4j.data.message.UserMessage;
import dev.langchain4j.model.chat.ChatModel;
import dev.langchain4j.model.chat.response.ChatResponse;
import dev.langchain4j.model.ollama.OllamaChatModel;
public class IntentClassifierExample {
public static void main(String[] args) {
ChatModel model = OllamaChatModel.builder()
.baseUrl("http://localhost:11434")
.modelName("phi3:mini-128k")
.numCtx(4096)
.temperature(0.5)
.build();
SystemMessage systemInstruction = SystemMessage.from(
"Identify the intent and extract entities from the user's request.\n"
+ "Intents: [CHECK_ORDER, CANCEL_ORDER, REFUND_REQUEST, UNKNOWN]\n"
+ "Entities to find: [order_id, item_name, reason]\n"
+ "Return the result ONLY as a JSON object.");
UserMessage userMessage = UserMessage.from(
"I need a refund for the fries in my order #9921 because they are soggy");
ChatResponse response = model.chat(systemInstruction, userMessage);
AiMessage aiMessage = response.aiMessage();
System.out.println(aiMessage.text());
}
}
Output```json
{
"Intent": "REFUND_REQUEST",
"Entities": {
"order_id": "9921",
"item_name": "fries",
"reason": "soggy"
}
}
```
Conclusion
The output produced by the example confirms that the model can correctly infer a user’s intent (e.g. refund request) and extract relevant entities such as order ID, item name, and reason. This validates that a single, well-scoped prompt is sufficient for intent classification and entity extraction.
Example ProjectDependencies and Technologies Used: - langchain4j 1.10.0 (Build LLM-powered applications in Java: chatbots, agents, RAG, and much more)
- langchain4j-ollama 1.10.0 (LangChain4j :: Integration :: Ollama)
- JDK 21
- Maven 3.9.11
|
|