import com.volcengine.ark.runtime.models.chat.*;
import com.volcengine.ark.runtime.service.ArkService;
import okhttp3.ConnectionPool;
import okhttp3.Dispatcher;
import java.time.Duration;
import java.util.ArrayList;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
public class BatchChatCompletionsExample {
public static void main(String[] args) {
Duration timeout = Duration.ofHours(24);
String apikey = System.getenv("ARK_API_KEY");
ConnectionPool connectionPool = new ConnectionPool(workerNum, 10, TimeUnit.MINUTES);
Dispatcher dispatcher = new Dispatcher();
dispatcher.setMaxRequests(workerNum);
dispatcher.setMaxRequestsPerHost(workerNum);
ArkService service = ArkService.builder().dispatcher(dispatcher).timeout(timeout).connectionPool(connectionPool)
.baseUrl("https://ark.cn-beijing.volces.com/api/v3")
ExecutorService executorService = Executors.newFixedThreadPool(workerNum);
CountDownLatch latch = new CountDownLatch(workerNum);
Runnable batchChatTask = () -> {
System.out.println(Thread.currentThread().getName() + ":在此线程中执行任务");
for (int i = 0; i < taskNum; i++) {
final List<ChatCompletionRequestMessage> messages = new ArrayList<>();
final ChatCompletionRequestMessage userMessage = ChatCompletionRequestUserMessage.builder().role(ChatCompletionRequestMessageType.USER)
.content(ChatCompletionMessageContent.ofString("Hello")).build();
messages.add(userMessage);
ChatCompletionRequest batchChatCompletionRequest = ChatCompletionRequest.builder()
.model("<YOUR_ENDPOINT_ID>")
service.createBatchChatCompletion(batchChatCompletionRequest)
.forEach(choice -> System.out.println(Thread.currentThread().getName() + ":"
+ choice.getMessage().getContent()));
System.out.println(Thread.currentThread().getName() + ":请求" + i + "失败。");
System.out.println(" 报错信息:" + e.getMessage());
System.out.println(Thread.currentThread().getName() + ":此线程中任务完成。");
for (int i = 0; i < workerNum; i++) {
executorService.submit(batchChatTask);
} catch (InterruptedException ignored) {
System.out.println("所有线程已退出");
executorService.shutdown();
System.out.println("线程池已退出");
service.shutdownExecutor();