Skip to content

Commit

Permalink
Merge pull request #504 from jmartisk/jbang-sample
Browse files Browse the repository at this point in the history
JBang sample
  • Loading branch information
jmartisk committed Apr 25, 2024
2 parents 7df718e + d639f79 commit 9e6f759
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 0 deletions.
30 changes: 30 additions & 0 deletions samples/jbang-joke-bot/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
# JBang sample aka getting an AI-powered bot in 13 lines of Java

To run the sample, you need JBang installed. If you don't have it, choose
one of the installation options from the [JBang
website](https://www.jbang.dev/download/).

You also have to set your OpenAI API key:

```
export QUARKUS_LANGCHAIN4J_OPENAI_API_KEY=<your-openai-api-key>
```

Then, run the example with:

```
jbang jokes.java
```

To have it tell you a joke, call `http://localhost:8080/joke` with a GET
request.

Explanation: The code contains a single method which injects a
`io.vertx.ext.web.Router`, which is a class from the `quarkus-vertx-http`
extension responsible for routing requests to appropriate handlers. The
method is called during application boot thanks to the `@Observes`
annotation, and it uses the injected `Router` to define a single route on
the `/joke` path. The route's handler (the lambda expression that accepts a `rc` -
`RoutingContext` parameter) invokes the model and sets the HTTP response.
See [Quarkus documentation](https://quarkus.io/guides/reactive-routes#using-the-vert-x-web-router)
for more information.
13 changes: 13 additions & 0 deletions samples/jbang-joke-bot/jokes.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
//DEPS io.quarkus.platform:quarkus-bom:3.9.4@pom
//DEPS io.quarkus:quarkus-vertx-http:3.9.4
//DEPS io.quarkiverse.langchain4j:quarkus-langchain4j-openai:0.12.0

import dev.langchain4j.model.chat.ChatLanguageModel;
import io.vertx.ext.web.Router;
import jakarta.enterprise.event.Observes;

public class jokes {
void route(@Observes Router router, ChatLanguageModel ai) {
router.get("/joke").blockingHandler(rc -> rc.end(ai.generate("tell me a joke")));
}
}

0 comments on commit 9e6f759

Please sign in to comment.