跳到主要内容

Qianfan

百度インテリジェントクラウド千帆大規模モデル image

Maven依存関係​

LangChain4jでは、通常のJavaまたはSpring Bootアプリケーションで千帆を使用できます。

通常のJava​

备注

1.0.0-alpha1以降、langchain4j-qianfanはlangchain4j-communityに移行し、langchain4j-community-qianfanに名前が変更されました。

1.0.0-alpha1より前:

<dependency>
<groupId>dev.langchain4j</groupId>
<artifactId>langchain4j-qianfan</artifactId>
<version>${previous version here}</version>
</dependency>

1.0.0-alpha1以降:

<dependency>
<groupId>dev.langchain4j</groupId>
<artifactId>langchain4j-community-qianfan</artifactId>
<version>${latest version here}</version>
</dependency>

Spring Boot​

备注

1.0.0-alpha1以降、langchain4j-qianfan-spring-boot-starterはlangchain4j-communityに移行し、 langchain4j-community-qianfan-spring-boot-starterに名前が変更されました。

1.0.0-alpha1より前:


<dependency>
<groupId>dev.langchain4j</groupId>
<artifactId>langchain4j-qianfan-spring-boot-starter</artifactId>
<version>${previous version here}</version>
</dependency>

1.0.0-alpha1以降:


<dependency>
<groupId>dev.langchain4j</groupId>
<artifactId>langchain4j-community-qianfan-spring-boot-starter</artifactId>
<version>${latest version here}</version>
</dependency>

または、BOMを使用して依存関係を一貫して管理することもできます:


<dependencyManagement>
<dependency>
<groupId>dev.langchain4j</groupId>
<artifactId>langchain4j-community-bom</artifactId>
<version>${latest version here}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencyManagement>

QianfanChatModel​

千帆のすべてのモデルと支払い状況

QianfanChatModel model = QianfanChatModel.builder()
.apiKey("apiKey")
.secretKey("secretKey")
.modelName("Yi-34B-Chat") // 一个免费的模型名称
.build();

String answer = model.chat("雷军");

System.out.println(answer);

カスタマイズ​

QianfanChatModel model = QianfanChatModel.builder()
.baseUrl(...)
.apiKey(...)
.secretKey(...)
.temperature(...)
.maxRetries(...)
.topP(...)
.modelName(...)
.endpoint(...)
.responseFormat(...)
.penaltyScore(...)
.logRequests(...)
.logResponses()
.build();

上記のパラメータの一部の説明はこちらで確認できます。

関数​

IAiService(重要)

public interface IAiService {
/**
* Ai Services 提供了一种更简单、更灵活的替代方案。 您可以定义自己的 API(具有一个或多个方法的 Java 接口), 并将为其提供实现。
* @param userMessage
* @return String
*/
String chat(String userMessage);
}

QianfanChatWithOnePersonMemory(1 人分のチャットメモリ付き)​


QianfanChatModel model = QianfanChatModel.builder()
.apiKey("apiKey")
.secretKey("secretKey")
.modelName("Yi-34B-Chat")
.build();
/* MessageWindowChatMemory
functions as a sliding window, retaining the N most recent messages and evicting older ones that no longer fit.
However, because each message can contain a varying number of tokens, MessageWindowChatMemory is mostly useful for fast prototyping.
保留最新的n条消息(包括回复)
*/
/* TokenWindowChatMemory
which also operates as a sliding window but focuses on keeping the N most recent tokens, evicting older messages as needed. Messages are indivisible.
If a message doesn't fit, it is evicted completely.
MessageWindowChatMemory requires a TokenCountEstimator to count the tokens in each ChatMessage.
*/
ChatMemory chatMemory = MessageWindowChatMemory.builder()
.maxMessages(10)
.build();

IAiService assistant = AiServices.builder(IAiService.class)
.chatModel(model) // the model
.chatMemory(chatMemory) // memory
.build();
String answer = assistant.chat("Hello,my name is xiaoyu");
System.out.println(answer); // Hello xiaoyu!******

String answerWithName = assistant.chat("What's my name?");
System.out.println(answerWithName); // Your name is xiaoyu.******

String answer1 = assistant.chat("I like playing football.");
System.out.println(answer1); // The answer

String answer2 = assistant.chat("I want to go eat delicious food.");
System.out.println(answer2); // The answer

String answerWithLike = assistant.chat("What I like to do?");
System.out.println(answerWithLike);//Playing football.******

QianfanChatWithMultiplePersonMemory(複数人のチャットメモリ付き)​

  QianfanChatModel model = QianfanChatModel.builder()
.apiKey("apiKey")
.secretKey("secretKey")
.modelName("Yi-34B-Chat")
.build();
IAiService assistant = AiServices.builder(IAiService.class)
.chatModel(model) // the model
.chatMemoryProvider(memoryId -> MessageWindowChatMemory.withMaxMessages(10)) // chatMemory
.build();

String answer = assistant.chat(1,"Hello, my name is xiaoyu");
System.out.println(answer); // Hello xiaoyu!******
String answer1 = assistant.chat(2,"Hello, my name is xiaomi");
System.out.println(answer1); // Hello xiaomi!******

String answerWithName1 = assistant.chat(1,"What's my name?");
System.out.println(answerWithName1); // Your name is xiaoyu.
String answerWithName2 = assistant.chat(2,"What's my name?");
System.out.println(answerWithName2); // Your name is xiaomi.

QianfanChatWithPersistentMemory(永続的なチャットメモリ付き)​

    <dependency>
<groupId>org.mapdb</groupId>
<artifactId>mapdb</artifactId>
<version>3.1.0</version>
</dependency>
class PersistentChatMemoryStore implements ChatMemoryStore {
private final DB db = DBMaker.fileDB("chat-memory.db").transactionEnable().make();
private final Map<String, String> map = db.hashMap("messages", STRING, STRING).createOrOpen();

@Override
public List<ChatMessage> getMessages(Object memoryId) {
String json = map.get((String) memoryId);
return messagesFromJson(json);
}

@Override
public void updateMessages(Object memoryId, List<ChatMessage> messages) {
String json = messagesToJson(messages);
map.put((String) memoryId, json);
db.commit();
}

@Override
public void deleteMessages(Object memoryId) {
map.remove((String) memoryId);
db.commit();
}
}

class PersistentChatMemoryTest{
public void test(){
QianfanChatModel chatModel = QianfanChatModel.builder()
.apiKey("apiKey")
.secretKey("secretKey")
.modelName("Yi-34B-Chat")
.build();

ChatMemory chatMemory = MessageWindowChatMemory.builder()
.maxMessages(10)
.chatMemoryStore(new PersistentChatMemoryStore())
.build();

IAiService assistant = AiServices.builder(IAiService.class)
.chatModel(chatModel)
.chatMemory(chatMemory)
.build();

String answer = assistant.chat("My name is xiaoyu");
System.out.println(answer);
// Run it once and then comment the top to run the bottom(运行一次后注释上面运行下面)
// String answerWithName = assistant.chat("What is my name?");
// System.out.println(answerWithName);
}
}

QianfanStreamingChatModel(ストリーミング応答)​

LLM はテキストを 1 トークンずつ生成するため、多くの LLM プロバイダーは、テキスト全体が生成されるのを待つ代わりに、レスポンスをトークンごとにストリーミングする方法を提供しています。これによりユーザーエクスペリエンスが大幅に向上します。ユーザーは不明な時間待つ必要がなく、ほぼ即座に応答の受け取りを開始できるためです。 以下はStreamingChatResponseHandlerを使用した実装例です:

  QianfanStreamingChatModel qianfanStreamingChatModel = QianfanStreamingChatModel.builder()
.apiKey("apiKey")
.secretKey("secretKey")
.modelName("Yi-34B-Chat")
.build();

qianfanStreamingChatModel.chat(userMessage, new StreamingChatResponseHandler() {

@Override
public void onPartialResponse(String partialResponse) {
System.out.print(partialResponse);
}
@Override
public void onCompleteResponse(ChatResponse completeResponse) {
System.out.println("onCompleteResponse: " + completeResponse);
}
@Override
public void onError(Throwable throwable) {
throwable.printStackTrace();
}
});

以下はTokenStreamを使用した別の実装例です:

  QianfanStreamingChatModel qianfanStreamingChatModel = QianfanStreamingChatModel.builder()
.apiKey("apiKey")
.secretKey("secretKey")
.modelName("Yi-34B-Chat")
.build();
IAiService assistant = AiServices.create(IAiService.class, qianfanStreamingChatModel);

TokenStream tokenStream = assistant.chatInTokenStream("Tell me a story.");
tokenStream.onPartialResponse(System.out::println)
.onError(Throwable::printStackTrace)
.start();

QianfanRAG​

プログラムが自動的に一致するコンテンツとユーザーの質問を組み合わせてプロンプトを作成し、大規模言語モデルに質問し、大規模言語モデルが回答を返します。

LangChain4jには「Easy RAG」機能があり、RAGを始めるのをできるだけ簡単にします。埋め込みについて学んだり、ベクトルストアを選んだり、適切な埋め込みモデルを見つけたり、ドキュメントの解析と分割方法を理解したりする必要はありません。ドキュメントを指定するだけで、LangChain4jが魔法をかけます。

  • 依存関係のインポート:langchain4j-easy-rag
<dependency>
<groupId>dev.langchain4j</groupId>
<artifactId>langchain4j-easy-rag</artifactId>
<version>1.23.0-beta33</version>
</dependency>
  • 使用方法

QianfanChatModel chatModel = QianfanChatModel.builder()
.apiKey(API_KEY)
.secretKey(SECRET_KEY)
.modelName("Yi-34B-Chat")
.build();
// All files in a directory, txt seems to be faster
List<Document> documents = FileSystemDocumentLoader.loadDocuments("/home/langchain4j/documentation");
// for simplicity, we will use an in-memory one:
InMemoryEmbeddingStore<TextSegment> embeddingStore = new InMemoryEmbeddingStore<>();
EmbeddingStoreIngestor.ingest(documents, embeddingStore);

IAiService assistant = AiServices.builder(IAiService.class)
.chatModel(chatModel)
.chatMemory(MessageWindowChatMemory.withMaxMessages(10))
.contentRetriever(EmbeddingStoreContentRetriever.from(embeddingStore))
.build();

String answer = assistant.chat("The Question");
System.out.println(answer);

例​