Close

LangChain4j - OpenAI Example

[Last Updated: Jan 19, 2026]

This example shows how to use OpenAI model in LangChain4j.

Example

The following example uses the demo proxy endpoint http://langchain4j.dev/demo/openai/v1 and the demo key provided by LangChain4j. When using the demo key, all requests to the OpenAI API need to go through the proxy, which injects the real key before forwarding your request to the OpenAI API. The demo key has a quota. This access is restricted to the gpt-4o-mini model and is ideal for educational purposes.

package com.logicbig.example;

import dev.langchain4j.model.chat.ChatModel;
import dev.langchain4j.model.openai.OpenAiChatModel;

public class OpenAiDemoExample {

    public static void main (String[] args) {
        ChatModel model = OpenAiChatModel.builder()
                                         .baseUrl("http://langchain4j.dev/demo/openai/v1")
                                         .apiKey("demo")
                                         .modelName("gpt-4o-mini")
                                         .build();

        String response = model.chat("Hi there!");
        System.out.println(response);
    }
}

Output

Hello! How can I assist you today?

Example Project

Dependencies and Technologies Used:

  • langchain4j-open-ai 1.10.0 (LangChain4j :: Integration :: OpenAI)
  • JDK 17
  • Maven 3.9.11

AI LangChain4j - LangChain4j With OpenAI example Select All Download
  • lang-chaing-4j-open-ai-example
    • src
      • main
        • java
          • com
            • logicbig
              • example
                • OpenAiDemoExample.java

    See Also

    Join