|
| 1 | +///usr/bin/env jbang "$0" "$@" ; exit $? |
| 2 | +//JAVA 21+ |
| 3 | +//PREVIEW |
| 4 | +//DEPS dev.langchain4j:langchain4j:1.0.1 dev.langchain4j:langchain4j-mistral-ai:1.0.1-beta6 |
| 5 | + |
| 6 | +import com.fasterxml.jackson.databind.ObjectMapper; |
| 7 | +import dev.langchain4j.data.message.UserMessage; |
| 8 | +import dev.langchain4j.model.chat.request.ChatRequest; |
| 9 | +import dev.langchain4j.model.chat.request.ResponseFormat; |
| 10 | +import dev.langchain4j.model.chat.request.ResponseFormatType; |
| 11 | +import dev.langchain4j.model.chat.request.json.JsonObjectSchema; |
| 12 | +import dev.langchain4j.model.chat.request.json.JsonSchema; |
| 13 | +import dev.langchain4j.model.chat.response.ChatResponse; |
| 14 | +import dev.langchain4j.model.mistralai.MistralAiChatModel; |
| 15 | +import dev.langchain4j.model.chat.ChatModel; |
| 16 | + |
| 17 | +Person(String name, int age, double height, boolean married) { |
| 18 | +} |
| 19 | + |
| 20 | +void main() throws Exception { |
| 21 | + ResponseFormat responseFormat = ResponseFormat.builder() |
| 22 | + .type(ResponseFormatType.JSON) |
| 23 | + .jsonSchema(JsonSchema.builder() |
| 24 | + .name("Person") |
| 25 | + .rootElement(JsonObjectSchema.builder() |
| 26 | + .addStringProperty("name") |
| 27 | + .addIntegerProperty("age") |
| 28 | + .addNumberProperty("height") |
| 29 | + .addBooleanProperty("married") |
| 30 | + .required("name", "age", "height", "married") |
| 31 | + .build()) |
| 32 | + .build()) |
| 33 | + .build(); |
| 34 | + |
| 35 | + UserMessage userMessage = UserMessage.from(""" |
| 36 | + John is 42 years old. |
| 37 | + He stands 1.75 meters tall. |
| 38 | + Currently unmarried. |
| 39 | + """); |
| 40 | + |
| 41 | + ChatRequest chatRequest = ChatRequest.builder() |
| 42 | + .responseFormat(responseFormat) |
| 43 | + .messages(userMessage) |
| 44 | + .build(); |
| 45 | + |
| 46 | + ChatModel chatModel = MistralAiChatModel.builder() |
| 47 | + .apiKey(System.getenv("OVH_AI_ENDPOINTS_ACCESS_TOKEN")) |
| 48 | + .baseUrl(System.getenv("OVH_AI_ENDPOINTS_MODEL_URL")) |
| 49 | + .modelName(System.getenv("OVH_AI_ENDPOINTS_MODEL_NAME")) |
| 50 | + .logRequests(false) |
| 51 | + .logResponses(false) |
| 52 | + .build(); |
| 53 | + |
| 54 | + ChatResponse chatResponse = chatModel.chat(chatRequest); |
| 55 | + |
| 56 | + System.out.println("Prompt: \n" + userMessage.singleText()); |
| 57 | + String output = chatResponse.aiMessage().text(); |
| 58 | + System.out.println("Response: \n" + output); // {"name":"John","age":42,"height":1.75,"married":false} |
| 59 | + |
| 60 | + Person person = new ObjectMapper().readValue(output, Person.class); |
| 61 | + System.out.println(person); // Person[name=John, age=42, height=1.75, married=false] |
| 62 | +} |
0 commit comments