aboutsummaryrefslogtreecommitdiffstats
path: root/container-search/src/main/java/ai/vespa/llm/clients/ConfigurableLanguageModel.java
blob: 761fdf0af93200e361aa9b509c03e2117cf21b3b (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
// Copyright Vespa.ai. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package ai.vespa.llm.clients;

import ai.vespa.llm.InferenceParameters;
import ai.vespa.llm.LanguageModel;
import com.yahoo.api.annotations.Beta;
import com.yahoo.component.annotation.Inject;
import com.yahoo.container.jdisc.secretstore.SecretStore;

import java.util.logging.Logger;


/**
 * Base class for language models that can be configured with config definitions.
 *
 * @author lesters
 */
@Beta
public abstract class ConfigurableLanguageModel implements LanguageModel {

    private static Logger log = Logger.getLogger(ConfigurableLanguageModel.class.getName());

    private final String apiKey;
    private final String endpoint;

    public ConfigurableLanguageModel() {
        this.apiKey = null;
        this.endpoint = null;
    }

    @Inject
    public ConfigurableLanguageModel(LlmClientConfig config, SecretStore secretStore) {
        this.apiKey = findApiKeyInSecretStore(config.apiKeySecretName(), secretStore);
        this.endpoint = config.endpoint();
    }

    private static String findApiKeyInSecretStore(String property, SecretStore secretStore) {
        String apiKey = "";
        if (property != null && ! property.isEmpty()) {
            try {
                apiKey = secretStore.getSecret(property);
            } catch (UnsupportedOperationException e) {
                // Secret store is not available - silently ignore this
            } catch (Exception e) {
                log.warning("Secret store look up failed: " + e.getMessage() + "\n" +
                        "Will expect API key in request header");
            }
        }
        return apiKey;
    }

    protected String getApiKey(InferenceParameters params) {
        return params.getApiKey().orElse(null);
    }

    /**
     * Set the API key as retrieved from secret store if it is not already set
     */
    protected void setApiKey(InferenceParameters params) {
        if (params.getApiKey().isEmpty() && apiKey != null) {
            params.setApiKey(apiKey);
        }
    }

    protected String getEndpoint() {
        return endpoint;
    }

    protected void setEndpoint(InferenceParameters params) {
        if (endpoint != null && ! endpoint.isEmpty()) {
            params.setEndpoint(endpoint);
        }
    }

}