Skip to content

Adding a Little AI to Your Application

Before we get into the magic of full-blown Embabel agents, let’s see how easy it is to add a little AI to your application using the Embabel framework. Sometimes this is all you need.

The simplest way to use Embabel is to inject an OperationContext and use its AI capabilities directly. This approach is consistent with standard Spring dependency injection patterns.

package com.embabel.example.injection;
import com.embabel.agent.api.common.OperationContext;
import com.embabel.common.ai.model.LlmOptions;
import org.springframework.stereotype.Component;
/**
* Demonstrate the simplest use of Embabel's AI capabilities,
* injecting an AI helper into a Spring component.
* The jokes will be terrible, but don't blame Embabel, blame the LLM.
*/
@Component
public record InjectedComponent(Ai ai) {
public record Joke(String leadup, String punchline) {
}
public String tellJokeAbout(String topic) {
return ai
.withDefaultLlm()
.generateText("Tell me a joke about " + topic);
}
public Joke createJokeObjectAbout(String topic1, String topic2, String voice) {
return ai
.withLlm(LlmOptions.withDefaultLlm().withTemperature(.8))
.createObject("""
Tell me a joke about %s and %s.
The voice of the joke should be %s.
The joke should have a leadup and a punchline.
""".formatted(topic1, topic2, voice),
Joke.class);
}
}

This example demonstrates several key aspects of Embabel’s design philosophy:

  • Standard Spring Integration: The Ai object is injected like any other Spring dependency using constructor injection
  • Simple API: Access AI capabilities through the Ai interface directly or OperationContext.ai(), which can also be injected in the same way
  • Flexible Configuration: Configure LLM options like temperature on a per-call basis
  • Type Safety: Generate structured objects directly with createObject() method
  • Consistent Patterns: Works exactly like you’d expect any Spring component to work

The Ai type provides access to all of Embabel’s AI capabilities without requiring a full agent setup, making it perfect for adding AI features to existing applications incrementally.