Repository navigation
Using Perplexity and OpenAI in the same application #3554
Replies: 2 comments
|
Hi @dolukhanov, I think you have to create a custom I hope the following example helps and answers your question. Example ProjectHere I am gonna make an example where I want to use the OpenAI API interface when running @Service
public class AiService {
private final ChatClient gemmaChatClient;
private final ChatClient openAiChatClient;
public AiService(ChatClient.Builder chatClientBuilder) {
var gemmaApi = OpenAiApi.builder()
.baseUrl("http://localhost:11434")
.apiKey("test") // Otherwise api key required exception is thrown
.build();
var gemmaChatModel = OpenAiChatModel.builder()
.openAiApi(gemmaApi)
.build();
var gemmaChatOptions = ChatOptions.builder()
.model("gemma:2b")
.build();
this.gemmaChatClient = ChatClient
.builder(gemmaChatModel)
.defaultOptions(gemmaChatOptions)
.build();
var openAiChatOptions = ChatOptions.builder()
.model("gpt-4.1-nano")
.build();
this.openAiChatClient = chatClientBuilder
.defaultOptions(openAiChatOptions)
.build();
}
public String askGemma(String message) {
return gemmaChatClient.prompt()
.user(message)
.call()
.content();
}
public String askOpenai(String message) {
return openAiChatClient.prompt()
.user(message)
.call()
.content();
}
}To test this I created a simple controller where I am injecting my AiService: @PostMapping(value = "/askai")
public String askai(@RequestParam("message") String message,
@RequestParam(value = "model", defaultValue = "openai") String model) {
return switch (model) {
case "openai" -> aiService.askOpenai(message);
case "gemma" -> aiService.askGemma(message);
default -> throw new IllegalStateException("Unexpected value: " + model);
};
}In my properties file, I will provide just the OpenAI API key. In my local environment, I have the Now, after running my application, I tested it using OpenAIGemma |
Uh oh!
There was an error while loading. Please reload this page.
In the documentation for Perplexity Chat the integration uses
spring.ai.openai.api-key=<your-perplexity-api-key>and similar openai based configuration.What is the recommended approach if an application needs to access both OpenAI and Perplexity chat models in the same application?
All reactions