From the course: Foundations of AI and Machine Learning for Java Developers

Unlock this course with a free trial

Join today to access over 24,500 courses taught by industry experts.

Code examples of connecting to an LLM: Pure Java and LC4J

Code examples of connecting to an LLM: Pure Java and LC4J - Java Tutorial

From the course: Foundations of AI and Machine Learning for Java Developers

Code examples of connecting to an LLM: Pure Java and LC4J

- [Instructor] Let's look at some specific Java code to connect to a language model. I have two examples. One is in Pure Java and one is using LangChain4j. Here's the first one written in one page of Pure Java. Notice it's quite simple to connect to a language model using Pure Java. The first thing that we do is get the open AI API Key. This is the long encoded string that you get from OpenAI when you register as a developer with them. And from my example, I set it as an environment variable and here I retrieve it through using getenv. The next step is creating the REST payload, which includes the prompt. OpenAI requires you to send a formatted message with your prompt and other parameters, such as which model to use, how creative the response should be, and its maximum size. Here I use Java text block to clearly show my OpenAI message. As you can see, the prompt in my example is, "Tell me a funny joke about programming in Java." Other language model providers use a similar REST…

Contents