使用的openai-java版本:0.12.0
import com.fasterxml.jackson.databind.ObjectMapper;
import com.theokanning.openai.OpenAiApi;
import com.theokanning.openai.service.OpenAiService;
import okhttp3.*;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import retrofit2.Retrofit;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.time.Duration;
import static com.theokanning.openai.service.OpenAiService.defaultRetrofit;
@Configuration
public class OpenAiServiceConfig {
final static String proxyUsername = "xxxuser";
final static String proxyPassword = "xxxpwd";
@Bean
public OpenAiService getOpenAiService() {
ObjectMapper mapper = OpenAiService.defaultObjectMapper();
Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("127.0.0.1", 7890));
//这个是认证的重点
Authenticator authenticator = new Authenticator() {
public Request authenticate(Route route, Response response) throws IOException {
String credential = Credentials.basic(proxyUsername, proxyPassword);
return response.request().newBuilder()
.header("Proxy-Authorization", credential)
.build();
}
};
OkHttpClient client = OpenAiService.defaultClient("your-token", Duration.ofSeconds(60L))
.newBuilder()
//设置代理
.proxy(proxy)
//设置用户名和密码
.proxyAuthenticator(authenticator)
.build();
Retrofit retrofit = defaultRetrofit(client, mapper);
OpenAiApi api = retrofit.create(OpenAiApi.class);
OpenAiService service = new OpenAiService(api);
return service;
}
}