Skip to content

Commit

Permalink
feature 1.1.2 新的api开发:tts
Browse files Browse the repository at this point in the history
  • Loading branch information
guorutao committed Nov 12, 2023
1 parent 25e2dbf commit 640ad2d
Show file tree
Hide file tree
Showing 14 changed files with 469 additions and 100 deletions.
10 changes: 10 additions & 0 deletions fine_tune_test_file.json1
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
{"messages": [{"role": "system", "content": "OnBot是一个聊天机器人。"}, {"role": "user", "content": "chagpt-java好用么?"}, {"role": "assistant", "content": "还行吧。"}]}
{"messages": [{"role": "system", "content": "OnBot是一个聊天机器人。"}, {"role": "user", "content": "chagpt-java最新版本是什么?"}, {"role": "assistant", "content": "1.1.2版本"}]}
{"messages": [{"role": "system", "content": "OnBot是一个聊天机器人。"}, {"role": "user", "content": "chagpt-java支持流式输出么?"}, {"role": "assistant", "content": "最新版支持流式输出"}]}
{"messages": [{"role": "system", "content": "OnBot是一个聊天机器人。"}, {"role": "user", "content": "chagpt-java的作者是谁?"}, {"role": "assistant", "content": "作者是Unfbx,个人网站:https://www.unfbx.com"}]}
{"messages": [{"role": "system", "content": "OnBot是一个聊天机器人。"}, {"role": "user", "content": "Unfbx是chagpt-java的作者,微信公众号是什么?"}, {"role": "assistant", "content": "程序员的黑洞。"}]}
{"messages": [{"role": "system", "content": "OnBot是一个聊天机器人。"}, {"role": "user", "content": "Unfbx是chagpt-java的作者,个人博客地址是什么?"}, {"role": "assistant", "content": "https://www.unfbx.com"}]}
{"messages": [{"role": "system", "content": "OnBot是一个聊天机器人。"}, {"role": "user", "content": "Unfbx是chagpt-java的作者,chagpt-java官方地址是什么?"}, {"role": "assistant", "content": "https://chatgpt-java.unfbx.com"}]}
{"messages": [{"role": "system", "content": "OnBot是一个聊天机器人。"}, {"role": "user", "content": "Unfbx是chagpt-java的作者,chagpt-java的github地址是什么?"}, {"role": "assistant", "content": "https://github.com/Grt1228/chatgpt-java"}]}
{"messages": [{"role": "system", "content": "OnBot是一个聊天机器人。"}, {"role": "user", "content": "Unfbx是chagpt-java的作者,chagpt-java的简单介绍。"}, {"role": "assistant", "content": "OpenAI官方Api的Java SDK,可以快速接入项目使用。目前支持OpenAI官方全部接口,**同时支持Tokens计算。参考文档:[Tokens_README.md](https://github.com/Grt1228/chatgpt-java/blob/main/Tokens_README.md)**"}]}
{"messages": [{"role": "system", "content": "OnBot是一个聊天机器人。"}, {"role": "user", "content": "OpenAi的官方Java Sdk 是什么?"}, {"role": "assistant", "content": "chagpt-java,github地址:https://github.com/Grt1228/chatgpt-java"}]}
19 changes: 12 additions & 7 deletions src/main/java/com/unfbx/chatgpt/OpenAiApi.java
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@
import com.unfbx.chatgpt.entity.billing.BillingUsage;
import com.unfbx.chatgpt.entity.billing.CreditGrantsResponse;
import com.unfbx.chatgpt.entity.billing.Subscription;
import com.unfbx.chatgpt.entity.chat.BaseChatCompletion;
import com.unfbx.chatgpt.entity.chat.ChatCompletion;
import com.unfbx.chatgpt.entity.chat.ChatCompletionResponse;
import com.unfbx.chatgpt.entity.chat.ChatCompletionWithPicture;
Expand Down Expand Up @@ -217,7 +216,7 @@ Single<UploadFileResponse> uploadFile(@Part MultipartBody.Part file,
* 微调作业集合
*
* @return Single OpenAiResponse FineTuneResponse
* @see #fineTuneJobs()
* @see #fineTuneJobs(String, Integer)
*/
@Deprecated
@GET("v1/fine-tunes")
Expand Down Expand Up @@ -248,7 +247,7 @@ Single<UploadFileResponse> uploadFile(@Part MultipartBody.Part file,
* 微调作业事件列表
*
* @return Single OpenAiResponse Event
* @see #fineTuneJobEvents(String fineTuneJobId)
* @see #fineTuneJobEvents(String, String, Integer)
*/
@Deprecated
@GET("v1/fine-tunes/{fine_tune_id}/events")
Expand Down Expand Up @@ -362,8 +361,10 @@ Single<WhisperResponse> speechToTextTranslations(@Part MultipartBody.Part file,
*
* @param textToSpeech
* @return
* @since 1.1.2
*/
@POST("v1/audio/speech")
@Streaming
Call<ResponseBody> textToSpeech(@Body TextToSpeech textToSpeech);


Expand All @@ -380,11 +381,13 @@ Single<WhisperResponse> speechToTextTranslations(@Part MultipartBody.Part file,
/**
* 微调job集合
*
* @param after 上一个分页请求中最后一个job id
* @param limit 每次查询数量
* @return FineTuneJobListResponse #FineTuneResponse
* @since 1.1.2
*/
@GET("v1/fine_tuning/jobs")
Single<FineTuneJobListResponse<FineTuneJobResponse>> fineTuneJobs();
Single<FineTuneJobListResponse<FineTuneJobResponse>> fineTuneJobs(@Query("after") String after, @Query("limit") Integer limit);


/**
Expand All @@ -400,7 +403,7 @@ Single<WhisperResponse> speechToTextTranslations(@Part MultipartBody.Part file,
/**
* 取消微调job
*
* @param fineTuneJobId
* @param fineTuneJobId JobId
* @return FineTuneJobResponse
* @since 1.1.2
*/
Expand All @@ -410,11 +413,13 @@ Single<WhisperResponse> speechToTextTranslations(@Part MultipartBody.Part file,
/**
* 微调job事件列表
*
* @param fineTuneJobId
* @param fineTuneJobId JobId
* @param after 上一个分页请求中最后一个id,默认值:null
* @param limit 每次查询数量 默认值:20
* @return FineTuneJobListResponse #FineTuneResponse
* @since 1.1.2
*/
@GET("v1/fine_tuning/jobs/{fine_tuning_job_id}/events")
Single<FineTuneJobListResponse<FineTuneJobEvent>> fineTuneJobEvents(@Path("fine_tuning_job_id") String fineTuneJobId);
Single<FineTuneJobListResponse<FineTuneJobEvent>> fineTuneJobEvents(@Path("fine_tuning_job_id") String fineTuneJobId, @Query("after") String after, @Query("limit") Integer limit);

}
41 changes: 19 additions & 22 deletions src/main/java/com/unfbx/chatgpt/OpenAiClient.java
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,7 @@
import retrofit2.converter.jackson.JacksonConverterFactory;

import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.util.*;
import java.util.concurrent.TimeUnit;
Expand Down Expand Up @@ -586,7 +587,7 @@ public FineTuneResponse fineTune(String trainingFileId) {
* 微调模型列表
*
* @return FineTuneResponse list
* @see #fineTuneJobs()
* @see #fineTuneJobs(String, Integer)
*/
@Deprecated
public List<FineTuneResponse> fineTunes() {
Expand Down Expand Up @@ -625,7 +626,7 @@ public FineTuneResponse cancelFineTune(String fineTuneId) {
*
* @param fineTuneId 微调作业id
* @return Event List
* @see #fineTuneJobEvents(String fineTuneJobId)
* @see #fineTuneJobEvents(String, String, Integer)
*/
@Deprecated
public List<Event> fineTuneEvents(String fineTuneId) {
Expand Down Expand Up @@ -933,18 +934,23 @@ public FineTuneJobResponse fineTuneJob(FineTuneJob fineTuneJob) {
* @since 1.1.2
*/
public FineTuneJobResponse fineTuneJob(String trainingFileId) {
FineTuneJob fineTuneJob = FineTuneJob.builder().trainingFile(trainingFileId).build();
FineTuneJob fineTuneJob = FineTuneJob.builder()
.model(FineTuneJob.Model.GPT_3_5_TURBO_1106.getName())
.trainingFile(trainingFileId)
.build();
return this.fineTuneJob(fineTuneJob);
}

/**
* 微调job列表
* 微调job集合
*
* @return FineTuneJobListResponse #FineTuneJobResponse
* @param after 上一个分页请求中最后一个job id,默认值:null
* @param limit 每次查询数量 默认值:20
* @return FineTuneJobListResponse #FineTuneResponse
* @since 1.1.2
*/
public FineTuneJobListResponse<FineTuneJobResponse> fineTuneJobs() {
Single<FineTuneJobListResponse<FineTuneJobResponse>> fineTuneJobs = this.openAiApi.fineTuneJobs();
public FineTuneJobListResponse<FineTuneJobResponse> fineTuneJobs(String after, Integer limit) {
Single<FineTuneJobListResponse<FineTuneJobResponse>> fineTuneJobs = this.openAiApi.fineTuneJobs(after, limit);
return fineTuneJobs.blockingGet();
}

Expand Down Expand Up @@ -976,29 +982,20 @@ public FineTuneJobResponse cancelFineTuneJob(String fineTuneJobId) {
* 微调作业事件列表
*
* @param fineTuneJobId 微调job id
* @param after 上一个分页请求中最后一个id,默认值:null
* @param limit 每次查询数量 默认值:20
* @return Event List
* @since 1.1.2
*/
public FineTuneJobListResponse<FineTuneJobEvent> fineTuneJobEvents(String fineTuneJobId) {
Single<FineTuneJobListResponse<FineTuneJobEvent>> events = this.openAiApi.fineTuneJobEvents(fineTuneJobId);
public FineTuneJobListResponse<FineTuneJobEvent> fineTuneJobEvents(String fineTuneJobId, String after, Integer limit) {
Single<FineTuneJobListResponse<FineTuneJobEvent>> events = this.openAiApi.fineTuneJobEvents(fineTuneJobId, after, limit);
return events.blockingGet();
}


public void textToSpeech(TextToSpeech textToSpeech) {
public void textToSpeech(TextToSpeech textToSpeech, Callback callback) {
Call<ResponseBody> responseBody = this.openAiApi.textToSpeech(textToSpeech);
responseBody.enqueue(new Callback<ResponseBody>() {
@SneakyThrows
@Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
System.out.println("--------------------->" + response.body());
}

@Override
public void onFailure(Call<ResponseBody> call, Throwable t) {

}
});
responseBody.enqueue(callback);
}

public static final class Builder {
Expand Down
21 changes: 0 additions & 21 deletions src/main/java/com/unfbx/chatgpt/OpenAiStreamClient.java
Original file line number Diff line number Diff line change
Expand Up @@ -156,27 +156,6 @@ private OkHttpClient okHttpClient() {
.build();
}


public void textToSpeed(TextToSpeech textToSpeech, EventSourceListener eventSourceListener) {
try {
EventSource.Factory factory = EventSources.createFactory(this.okHttpClient);
ObjectMapper mapper = new ObjectMapper();
String requestBody = mapper.writeValueAsString(textToSpeech);
Request request = new Request.Builder()
.url(this.apiHost + "v1/audio/speech")
.post(RequestBody.create(MediaType.parse(ContentType.JSON.getValue()), requestBody))
.build();
//创建事件
EventSource eventSource = factory.newEventSource(request, eventSourceListener);
} catch (JsonProcessingException e) {
log.error("请求参数解析异常:{}", e);
e.printStackTrace();
} catch (Exception e) {
log.error("请求参数解析异常:{}", e);
e.printStackTrace();
}
}

/**
* 问答接口 stream 形式
*
Expand Down
12 changes: 6 additions & 6 deletions src/main/java/com/unfbx/chatgpt/entity/Tts/TtsVoice.java
Original file line number Diff line number Diff line change
Expand Up @@ -11,12 +11,12 @@
@AllArgsConstructor
public enum TtsVoice {

ALLOY("mp3"),
ECHO("opus"),
FABLE("aac"),
ONYX("flac"),
NOVA("flac"),
SHIMMER("flac"),
ALLOY("alloy"),
ECHO("echo"),
FABLE("fable"),
ONYX("onyx"),
NOVA("nova"),
SHIMMER("shimmer"),
;

private final String name;
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
package com.unfbx.chatgpt.entity.fineTune.job;

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import lombok.Data;

/**
* 描述:
*
* @author https://www.unfbx.com
* @since 1.1.2
* 2023-11-12
*/
@Data
@JsonIgnoreProperties(ignoreUnknown = true)
public class FineTuneError {
private String message;
private String param;
private String code;
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,18 @@

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.unfbx.chatgpt.entity.common.OpenAiResponse;
import lombok.*;

import java.io.Serializable;
import java.util.List;

/**
* 描述:
*
* @author https://www.unfbx.com
* @since 1.1.2
* 2023-11-12
*/
@Data
@JsonIgnoreProperties(ignoreUnknown = true)
public class FineTuneJobResponse implements Serializable {
Expand All @@ -18,7 +24,7 @@ public class FineTuneJobResponse implements Serializable {
private Long createdAt;

@JsonProperty("error")
private OpenAiResponse.Error error;
private FineTuneError error;

@JsonProperty("fine_tuned_model")
private String fineTunedModel;
Expand All @@ -42,7 +48,7 @@ public class FineTuneJobResponse implements Serializable {
private List<String> resultFiles;

@JsonProperty("status")
private Long status;
private String status;

@JsonProperty("trained_tokens")
private Integer trainedTokens;
Expand All @@ -52,4 +58,7 @@ public class FineTuneJobResponse implements Serializable {

@JsonProperty("validation_file")
private String validationFile;

@JsonProperty("data")
private String data;
}
3 changes: 2 additions & 1 deletion src/main/java/com/unfbx/chatgpt/entity/images/Image.java
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,8 @@ public class Image implements Serializable {
*
* @see Model
*/
private String model;
@Builder.Default
private String model = Model.DALL_E_3.getName();

/**
* 此参数仅仅dall-e-3,默认值:standard
Expand Down
4 changes: 2 additions & 2 deletions src/test/java/com/unfbx/chatgpt/OpenAiClientFunctionTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ public void before() {
.authInterceptor(new DynamicKeyOpenAiAuthInterceptor())
.okHttpClient(okHttpClient)
//自己做了代理就传代理地址,没有可不不传,(关注公众号回复:openai ,获取免费的测试代理地址)
.apiHost("https://dgr.life/")
.apiHost("https://*************/")
.build();

openAiStreamClient = OpenAiStreamClient.builder()
Expand All @@ -69,7 +69,7 @@ public void before() {
.authInterceptor(new DynamicKeyOpenAiAuthInterceptor())
.okHttpClient(okHttpClient)
//自己做了代理就传代理地址,没有可不不传,(关注公众号回复:openai ,获取免费的测试代理地址)
.apiHost("https://dgr.life/")
.apiHost("https://*************/")
.build();
}

Expand Down
28 changes: 2 additions & 26 deletions src/test/java/com/unfbx/chatgpt/OpenAiClientTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -80,40 +80,16 @@ public void before() {
.build();
v2 = OpenAiClient.builder()
//支持多key传入,请求时候随机选择
.apiKey(Arrays.asList("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"))
.apiKey(Arrays.asList("************************"))
//自定义key的获取策略:默认KeyRandomStrategy
//.keyStrategy(new KeyRandomStrategy())
.keyStrategy(new FirstKeyStrategy())
.okHttpClient(okHttpClient)
//自己做了代理就传代理地址,没有可不不传,(关注公众号回复:openai ,获取免费的测试代理地址)
.apiHost("https://dgr.life/")
.apiHost("https://*********/")
.build();
}

@Test
public void textToSpeed() throws IOException {
TextToSpeech textToSpeech = TextToSpeech.builder()
.model("tts-1")
.input("In the vast, white expanse of the winter landscape, a drama unfolds that is as timeless as it is raw. Here, in the cradle of nature's harshest trials, a pack of grey wolves has singled out a bison from the herd—a desperate struggle for life and sustenance is about to begin.\n" +
"\n" +
"In a carefully orchestrated assault, the pack encircles their quarry, each wolf keenly aware of its role. Muscles tense and breaths visible in the frigid air, they inch closer, probing for a weakness. The bison, a formidable giant, stands its ground, backed by the survival instincts honed over millennia. Its hulking form casts a solitary shadow against the snow's blinding canvas.\n" +
"\n" +
"The dance of predator and prey plays out as a symphony of survival—each movement, each feint, holds the weight of life itself. The wolves take turns attacking, conserving strength while wearing down their target. The herd, once the bison's allies, scatter into the distance, a stark reminder that in these wild territories, the law of survival supersedes the bonds of kinship.\n" +
"\n" +
"A burst of activity—the wolves close in. The bison, though mighty, is tiring, its breaths labored, its movements sluggish. The wolves sense the turning tide. With relentless determination, they press their advantage, a testament to the brutal beauty of the natural order.\n" +
"\n" +
"As the struggle reaches its inevitable conclusion, we are reminded of the delicate balance that governs these wild spaces. Life, death, struggle, and survival—the cycle continues, each chapter written in the snow, for as long as the wolf roams and the bison roves these frozen plains.")
.voice("alloy")
.responseFormat("mp3")
.build();
v2.textToSpeech(textToSpeech);
CountDownLatch countDownLatch = new CountDownLatch(1);
try {
countDownLatch.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
@Test
public void subscription() {
Subscription subscription = v2.subscription();
Expand Down
4 changes: 2 additions & 2 deletions src/test/java/com/unfbx/chatgpt/OpenAiStreamClientTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -50,13 +50,13 @@ public void before() {
.readTimeout(30, TimeUnit.SECONDS)
.build();
client = OpenAiStreamClient.builder()
.apiKey(Arrays.asList("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"))
.apiKey(Arrays.asList("*************"))
//自定义key的获取策略:默认KeyRandomStrategy
// .keyStrategy(new KeyRandomStrategy())
.keyStrategy(new FirstKeyStrategy())
.okHttpClient(okHttpClient)
//自己做了代理就传代理地址,没有可不不传((关注公众号回复:openai ,获取免费的测试代理地址))
.apiHost("https://dgr.life/")
.apiHost("https://**********/")
.build();
}

Expand Down
4 changes: 2 additions & 2 deletions src/test/java/com/unfbx/chatgpt/PluginTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -48,12 +48,12 @@ public void before() {
openAiClient = OpenAiClient.builder()
.okHttpClient(okHttpClient)
.apiKey(Arrays.asList("sk-********************************"))
.apiHost("https://dgr.life/")
.apiHost("https://*************/")
.build();
openAiStreamClient = OpenAiStreamClient.builder()
//支持多key传入,请求时候随机选择
.apiKey(Arrays.asList("sk-********************************"))
.apiHost("https://dgr.life/")
.apiHost("https://*************/")
.build();
}

Expand Down
Loading

0 comments on commit 640ad2d

Please sign in to comment.