1. 簡介
上次更新時間:2023 年 11 月 27 日
什麼是生成式 AI
生成式 AI 又稱為「生成式人工智慧」,是指使用 AI 技術生成新的文字、圖片、音樂、音訊和影片等內容。
生成式 AI 是由基礎模型 (大型 AI 模型) 驅動,可同時處理多項工作,並立即執行各種任務,包括提供摘要、問與答和分類等。此外,只需最少訓練,基礎模型可用極少的範例資料,就能針對目標用途進行調整。
生成式 AI 的運作方式為何?
生成式 AI 運用機器學習 (機器學習) 模型,瞭解人類建立內容資料集內的模式和關係,然後再運用所學的模式生成新內容。
訓練生成式 AI 模型最常見的方式是使用監督式學習,由模型提供一組人類建立的內容和對應的標籤。讓模型學習生成與人類創作內容相似的內容,並加上相同的標籤。
什麼是常見的生成式 AI 應用程式?
生成式 AI 可以處理大量內容,透過文字、圖片和容易使用的格式,產生相關洞察資訊和答案。生成式 AI 有助於:
- 透過進階即時通訊和搜尋體驗改善客戶互動
- 透過對話式介面和摘要功能探索大量非結構化資料
- 協助處理重複性工作,例如回覆提案請求 (RFP)、將行銷內容翻譯成五種語言,以及確認客戶合約是否遵循規定等
Google Cloud 提供哪些生成式 AI 產品與服務?
有了 Vertex AI,您不必具備機器學習專業知識,就能與基礎模型互動,並將模型嵌入應用程式中。您可以在 Model Garden 中存取基礎模型、透過 Generative AI Studio 的簡易使用者介面調整模型,或是運用數據資料學筆記本中的模型。
Vertex AI Search and Conversation 可讓開發人員以最快的速度,建構採用生成式 AI 的搜尋引擎和聊天機器人。
此外,Duet AI 是採用 AI 技術的協作工具,適用於 Google Cloud 和 IDE,讓您更快完成更多工作。
這個程式碼研究室的重點是什麼?
本程式碼研究室著重於託管於 Google Cloud Vertex AI 的 PaLM 2 大型語言模型 (LLM),涵蓋所有機器學習產品和服務。
您將使用 Java 與 PaLM API 互動,並搭配 LangChain4J LLM 架構自動化調度管理器。我們將逐一說明幾個具體範例,說明如何利用大型語言模型回答問題、構思想法、擷取實體與結構化內容,以及提供摘要。
進一步說明 LangChain4J 架構!
LangChain4J 架構是一個開放原始碼程式庫,可透過自動化調度管理各種元件 (例如 LLM 本身) 與向量資料庫 (用於語意搜尋)、文件載入器和分割器 (用於分析文件及從中學習)、輸出剖析器等,在 Java 應用程式中整合大型語言模型。
課程內容
- 如何設定 Java 專案以使用 PaLM 和 LangChain4J
- 如何首次呼叫 PaLM 文字模型以生成內容及回答問題
- 如何從非結構化內容 (實體或關鍵字擷取、JSON 輸出內容) 中擷取實用資訊
- 如何利用少量畫面提示進行內容分類或情緒分析
軟硬體需求
- Java 程式設計語言知識
- Google Cloud 專案
- 瀏覽器,例如 Chrome 或 Firefox
2. 設定和需求
自修環境設定
- 登入 Google Cloud 控制台,建立新專案或重複使用現有專案。如果您還沒有 Gmail 或 Google Workspace 帳戶,請先建立帳戶。
- 「專案名稱」是這項專案參與者的顯示名稱。這是 Google API 未使用的字元字串。您可以隨時更新付款方式。
- 所有 Google Cloud 專案的專案 ID 均不得重複,而且設定後即無法變更。Cloud 控制台會自動產生一個不重複的字串。但通常是在乎它何在在大部分的程式碼研究室中,您必須參照專案 ID (通常為
PROJECT_ID
)。如果您對產生的 ID 不滿意,可以隨機產生一個 ID。或者,您也可以自行嘗試,看看是否支援。在這個步驟後,這個名稱即無法變更,而且在專案期間內仍會保持有效。 - 資訊中的第三個值是專案編號,部分 API 會使用這個編號。如要進一步瞭解這三個值,請參閱說明文件。
- 接下來,您需要在 Cloud 控制台中啟用計費功能,才能使用 Cloud 資源/API。執行本程式碼研究室不會產生任何費用 (如果有的話)。如要關閉資源,以免產生本教學課程結束後產生的費用,您可以刪除自己建立的資源或刪除專案。新使用者符合 $300 美元免費試用計畫的資格。
啟動 Cloud Shell
雖然 Google Cloud 可以從筆記型電腦遠端操作,但在本程式碼研究室中,您將使用 Cloud Shell,這是一種在 Cloud 中執行的指令列環境。
啟用 Cloud Shell
- 在 Cloud 控制台中,按一下「啟用 Cloud Shell」圖示
。
如果您是第一次啟動 Cloud Shell,系統會顯示中繼畫面,說明這項服務的內容。如果系統顯示中繼畫面,請按一下「繼續」。
佈建並連線至 Cloud Shell 只需幾分鐘的時間。
這個虛擬機器已載入所有必要的開發工具。提供永久的 5 GB 主目錄,而且在 Google Cloud 中運作,大幅提高網路效能和驗證能力。在本程式碼研究室中,您的大部分作業都可透過瀏覽器完成。
連線至 Cloud Shell 後,您應會發現自己通過驗證,且專案已設為您的專案 ID。
- 在 Cloud Shell 中執行下列指令,確認您已通過驗證:
gcloud auth list
指令輸出
Credentialed Accounts ACTIVE ACCOUNT * <my_account>@<my_domain.com> To set the active account, run: $ gcloud config set account `ACCOUNT`
- 在 Cloud Shell 中執行下列指令,確認 gcloud 指令知道您的專案:
gcloud config list project
指令輸出
[core] project = <PROJECT_ID>
如果尚未設定,請使用下列指令進行設定:
gcloud config set project <PROJECT_ID>
指令輸出
Updated property [core/project].
3. 準備開發環境
在本程式碼研究室中,您將使用 Cloud Shell 終端機和程式碼編輯器來開發 Java 程式。
啟用 Vertex AI API
- 請前往 Google Cloud 控制台,確認 Google Cloud 控制台頂端會顯示你的專案名稱。如果沒有,請按一下「Select a project」開啟「Project Selector」,然後選取所需的專案。
- 如果您尚未位於 Google Cloud 控制台的「Vertex AI」部分,請按照下列步驟操作:
- 在搜尋中輸入 Vertex AI,然後傳回
- 在搜尋結果中按一下「Vertex AI Vertex AI 資訊主頁」。
- 在 Vertex AI 資訊主頁中,按一下「Enable All Recommended APIs」。
這項操作會啟用多個 API,但本程式碼研究室中最重要的 API 是 aiplatform.googleapis.com
。您也可以在 Cloud Shell 終端機中透過指令列啟用這個 API,並執行下列指令:
$ gcloud services enable aiplatform.googleapis.com
使用 Gradle 建立專案結構
如要建構 Java 程式碼範例,請使用 Gradle 建構工具和 Java 第 17 版。如要透過 Gradle 設定專案,請在 Cloud Shell 終端機中建立目錄 (此處為 palm-workshop
),然後在該目錄中執行 gradle init
指令:
$ mkdir palm-workshop $ cd palm-workshop $ gradle init Select type of project to generate: 1: basic 2: application 3: library 4: Gradle plugin Enter selection (default: basic) [1..4] 2 Select implementation language: 1: C++ 2: Groovy 3: Java 4: Kotlin 5: Scala 6: Swift Enter selection (default: Java) [1..6] 3 Split functionality across multiple subprojects?: 1: no - only one application project 2: yes - application and library projects Enter selection (default: no - only one application project) [1..2] 1 Select build script DSL: 1: Groovy 2: Kotlin Enter selection (default: Groovy) [1..2] 1 Generate build using new APIs and behavior (some features may change in the next minor release)? (default: no) [yes, no] Select test framework: 1: JUnit 4 2: TestNG 3: Spock 4: JUnit Jupiter Enter selection (default: JUnit Jupiter) [1..4] 4 Project name (default: palm-workshop): Source package (default: palm.workshop): > Task :init Get more help with your project: https://docs.gradle.org/7.4/samples/sample_building_java_applications.html BUILD SUCCESSFUL in 51s 2 actionable tasks: 2 executed
您將使用「Java 語言」(選項 2)、「不使用子專案」(選項 3)、「不使用子專案」(選項 1)、使用「建構檔案的 Groovy 語法」(選項 4)、「不要使用新的建構功能」(選項 4) 建構「application」 (選項 2)、使用 JUnit Jupiter (選項 4) 產生測試;您也可以用 palm-workshop 為原始碼產生測試。
專案結構如下所示:
├── gradle │ └── ... ├── gradlew ├── gradlew.bat ├── settings.gradle └── app ├── build.gradle └── src ├── main │ └── java │ └── palm │ └── workshop │ └── App.java └── test └── ...
讓我們更新 app/build.gradle
檔案,新增一些必要的依附元件。您可以移除 guava
依附元件 (如果有的話),並替換為 LangChain4J 專案的依附元件和記錄程式庫,以免遺漏記錄器訊息:
dependencies {
// Use JUnit Jupiter for testing.
testImplementation 'org.junit.jupiter:junit-jupiter:5.8.1'
// Logging library
implementation 'org.slf4j:slf4j-jdk14:2.0.9'
// This dependency is used by the application.
implementation 'dev.langchain4j:langchain4j-vertex-ai:0.24.0'
implementation 'dev.langchain4j:langchain4j:0.24.0'
}
LangChain4J 有 2 個依附元件:
- 對核心專案來說
- 另一個則用於專屬的 Vertex AI 模組
如要使用 Java 17 編譯及執行程式,請在 plugins {}
區塊下方新增下列區塊:
java {
toolchain {
languageVersion = JavaLanguageVersion.of(17)
}
}
需進行一項額外變更:更新 app/build.gradle
的 application
區塊,讓使用者能夠在叫用建構工具時覆寫主要類別,以便透過指令列執行:
application {
mainClass = providers.systemProperty('javaMainClass')
.orElse('palm.workshop.App')
}
如要確認建構檔案已準備好執行應用程式,可以執行預設的主要類別,該類別會顯示簡單的 Hello World!
訊息:
$ ./gradlew run -DjavaMainClass=palm.workshop.App > Task :app:run Hello World! BUILD SUCCESSFUL in 3s 2 actionable tasks: 2 executed
您現在已可透過使用 LangChain4J 專案,以 PaLM 大型語言文字模型編寫程式!
以下是 app/build.gradle
建構檔案現在的完整外觀,供您參考:
plugins {
// Apply the application plugin to add support for building a CLI application in Java.
id 'application'
}
java {
toolchain {
// Ensure we compile and run on Java 17
languageVersion = JavaLanguageVersion.of(17)
}
}
repositories {
// Use Maven Central for resolving dependencies.
mavenCentral()
}
dependencies {
// Use JUnit Jupiter for testing.
testImplementation 'org.junit.jupiter:junit-jupiter:5.8.1'
// This dependency is used by the application.
implementation 'dev.langchain4j:langchain4j-vertex-ai:0.24.0'
implementation 'dev.langchain4j:langchain4j:0.24.0'
implementation 'org.slf4j:slf4j-jdk14:2.0.9'
}
application {
mainClass = providers.systemProperty('javaMainClass').orElse('palm.workshop.App')
}
tasks.named('test') {
// Use JUnit Platform for unit tests.
useJUnitPlatform()
}
4. 首次呼叫 PaLM 的文字模型
現在已正確設定專案,接著要呼叫 PaLM API。
在 app/src/main/java/palm/workshop
目錄中建立名為 TextPrompts.java
的新類別 (以及預設的 App.java
類別),然後輸入下列內容:
package palm.workshop;
import dev.langchain4j.model.output.Response;
import dev.langchain4j.model.vertexai.VertexAiLanguageModel;
public class TextPrompts {
public static void main(String[] args) {
VertexAiLanguageModel model = VertexAiLanguageModel.builder()
.endpoint("us-central1-aiplatform.googleapis.com:443")
.project("YOUR_PROJECT_ID")
.location("us-central1")
.publisher("google")
.modelName("text-bison@001")
.maxOutputTokens(500)
.build();
Response<String> response = model.generate("What are large language models?");
System.out.println(response.content());
}
}
在第一個範例中,您必須匯入 Response
類別,以及 PaLM 的 Vertex AI 語言模型。
接下來,您要在 main
方法中使用 VertexAiLanguageModel
的建構工具設定語言模型,以便指定:
- 這個端點
- 專案
- 區域
- 發布商
- 以及模型名稱 (
text-bison@001
)。
語言模型準備就緒後,您可以呼叫 generate()
方法並傳遞「提示」(例如要傳送至 LLM 的問題或操作說明)。接著要詢問一個關於 LLM 的簡單問題,你可以變更提示內容,嘗試不同的問題或任務。
如要執行這個類別,請在 Cloud Shell 終端機中執行下列指令:
./gradlew run -DjavaMainClass=palm.workshop.TextPrompts
畫面會顯示類似以下的輸出內容:
Large language models (LLMs) are artificial intelligence systems that can understand and generate human language. They are trained on massive datasets of text and code, and can learn to perform a wide variety of tasks, such as translating languages, writing different kinds of creative content, and answering your questions in an informative way. LLMs are still under development, but they have the potential to revolutionize many industries. For example, they could be used to create more accurate and personalized customer service experiences, to help doctors diagnose and treat diseases, and to develop new forms of creative expression. However, LLMs also raise a number of ethical concerns. For example, they could be used to create fake news and propaganda, to manipulate people's behavior, and to invade people's privacy. It is important to carefully consider the potential risks and benefits of LLMs before they are widely used. Here are some of the key features of LLMs: * They are trained on massive datasets of text and code. * They can learn to perform a wide variety of tasks, such as translating languages, writing different kinds of creative content, and answering your questions in an informative way. * They are still under development, but they have the potential to revolutionize many industries. * They raise a number of ethical concerns, such as the potential for fake news, propaganda, and invasion of privacy.
VertexAILanguageModel
建構工具可讓您定義已擁有某些預設值的選用參數,並具有可覆寫的預設值。例如:
.temperature(0.2)
:定義您希望回應的廣告素材 (0 表示廣告素材不足且通常與事實不符,1 則代表生成更多創意).maxOutputTokens(50)
:在本範例中,要求產生 500 個符記 (3 個符記大約相當於 4 個字詞),取決於您產生答案的間隔時長.topK(20)
:從完成文字可能字數上限最多的字詞中隨機選取一個字詞 (從 1 到 40 個字).topP(0.95)
:選取總機率加總等於該浮點數的可能字詞 (介於 0 至 1 之間).maxRetries(3)
:如果您的執行時間超過每次要求配額,可以讓模型重試呼叫 3 次,例如
大型語言模型的功能非常強大,不僅可以提供複雜問題的答案,還能處理各種有趣的工作。下一節將介紹實用的工作:從文字擷取結構化資料。
5. 從非結構化文字中擷取資訊
在上一節中,您產生了一些文字輸出內容。您也可以直接向使用者顯示這個輸出內容。不過,如果您要擷取這個輸出內容中提及的資料,要如何從非結構化文字中擷取這項資訊?
假設您想要擷取某個人的簡介或描述,因而擷取其姓名和年齡。您可以依照下列方式調整提示,指示大型語言模型產生 JSON 資料結構 (這通常稱為「提示工程」):
Extract the name and age of the person described below. Return a JSON document with a "name" and an "age" property, following this structure: {"name": "John Doe", "age": 34} Return only JSON, without any markdown markup surrounding it. Here is the document describing the person: --- Anna is a 23 year old artist based in Brooklyn, New York. She was born and raised in the suburbs of Chicago, where she developed a love for art at a young age. She attended the School of the Art Institute of Chicago, where she studied painting and drawing. After graduating, she moved to New York City to pursue her art career. Anna's work is inspired by her personal experiences and observations of the world around her. She often uses bright colors and bold lines to create vibrant and energetic paintings. Her work has been exhibited in galleries and museums in New York City and Chicago. --- JSON:
修改 TextPrompts
類別中的 model.generate()
呼叫,將上方的整個文字提示傳遞給這個函式:
Response<String> response = model.generate("""
Extract the name and age of the person described below.
Return a JSON document with a "name" and an "age" property, \
following this structure: {"name": "John Doe", "age": 34}
Return only JSON, without any markdown markup surrounding it.
Here is the document describing the person:
---
Anna is a 23 year old artist based in Brooklyn, New York. She was born and
raised in the suburbs of Chicago, where she developed a love for art at a
young age. She attended the School of the Art Institute of Chicago, where
she studied painting and drawing. After graduating, she moved to New York
City to pursue her art career. Anna's work is inspired by her personal
experiences and observations of the world around her. She often uses bright
colors and bold lines to create vibrant and energetic paintings. Her work
has been exhibited in galleries and museums in New York City and Chicago.
---
JSON:
"""
);
如果您在 TextPrompts
類別中執行這項提示,則回應會傳回下列 JSON 字串,您可以使用 GSON 程式庫等 JSON 剖析器進行剖析:
$ ./gradlew run -DjavaMainClass=palm.workshop.TextPrompts > Task :app:run {"name": "Anna", "age": 23} BUILD SUCCESSFUL in 24s 2 actionable tasks: 1 executed, 1 up-to-date
當然可以!小安 23 歲了!
6. 提示範本和結構化提示
回答問題以外的問題
PaLM 這類大型語言模型可以解答問題,但也可以用於更多工作!舉例來說,請嘗試下列 Generative AI Studio 的提示 (或修改 TextPrompts
類別)。用自己的想法改變大寫字母,並檢視輸出結果:
- 翻譯 -「將下列句子翻譯成法文:YOUR_SENTENCE_HERE」
- 摘要 -「提供下列文件的摘要:PASTE_YOUR_DOC」
- 廣告素材產生:「撰寫有關TOPIC_OF_THE_POEM」的詩
- 程式設計 -「How to write a Fibonacci function in PROGRAMMING_LANGUAGE?」
提示範本
如果您試過上述的翻譯、摘要、廣告素材產生或程式設計工作提示,您就已經將預留位置值替換成自己的構想。不過,您不用執行字串簡化,不如利用「提示範本」來定義這些預留位置值,並在完成後填入資料。
我們來看看將 main()
方法的完整內容替換為下列程式碼,看看這個構圖和創意提示的例子:
VertexAiLanguageModel model = VertexAiLanguageModel.builder()
.endpoint("us-central1-aiplatform.googleapis.com:443")
.project("YOUR_PROJECT_ID")
.location("us-central1")
.publisher("google")
.modelName("text-bison@001")
.maxOutputTokens(300)
.build();
PromptTemplate promptTemplate = PromptTemplate.from("""
Create a recipe for a {{dish}} with the following ingredients: \
{{ingredients}}, and give it a name.
"""
);
Map<String, Object> variables = new HashMap<>();
variables.put("dish", "dessert");
variables.put("ingredients", "strawberries, chocolate, whipped cream");
Prompt prompt = promptTemplate.apply(variables);
Response<String> response = model.generate(prompt);
System.out.println(response.content());
然後新增下列匯入項目:
import dev.langchain4j.model.input.Prompt;
import dev.langchain4j.model.input.PromptTemplate;
import java.util.HashMap;
import java.util.Map;
然後再次執行應用程式。輸出內容應如下所示:
$ ./gradlew run -DjavaMainClass=palm.workshop.TextPrompts > Task :app:run **Strawberry Shortcake** Ingredients: * 1 pint strawberries, hulled and sliced * 1/2 cup sugar * 1/4 cup cornstarch * 1/4 cup water * 1 tablespoon lemon juice * 1/2 cup heavy cream, whipped * 1/4 cup confectioners' sugar * 1/4 teaspoon vanilla extract * 6 graham cracker squares, crushed Instructions: 1. In a medium saucepan, combine the strawberries, sugar, cornstarch, water, and lemon juice. Bring to a boil over medium heat, stirring constantly. Reduce heat and simmer for 5 minutes, or until the sauce has thickened. 2. Remove from heat and let cool slightly. 3. In a large bowl, combine the whipped cream, confectioners' sugar, and vanilla extract. Beat until soft peaks form. 4. To assemble the shortcakes, place a graham cracker square on each of 6 dessert plates. Top with a scoop of whipped cream, then a spoonful of strawberry sauce. Repeat layers, ending with a graham cracker square. 5. Serve immediately. **Tips:** * For a more elegant presentation, you can use fresh strawberries instead of sliced strawberries. * If you don't have time to make your own whipped cream, you can use store-bought whipped cream.
超美味!
透過提示範本,您可以在呼叫文字產生方法前提供必要參數。這個方法很適合用來傳遞資料,並自訂使用者提示的不同值。
做為類別名稱的建議,PromptTemplate
類別會建立範本提示,而您可以套用預留位置名稱和值的對應,將值指派給預留位置元素。
結構化提示 (選用)
如果想使用更豐富的物件導向方法,使用 @StructuredPrompt
註解建構提示的另一種方法。您會使用這項註解為類別加上註解,其欄位對應於提示中定義的預留位置。一起來看看實際的運作方式吧
首先,我們需要新的匯入作業:
import java.util.Arrays;
import java.util.List;
import dev.langchain4j.model.input.structured.StructuredPrompt;
import dev.langchain4j.model.input.structured.StructuredPromptProcessor;
接著,我們可以在 TextPrompts
類別中建立內部靜態類別,收集 @StructuredPrompt
註解所述的預留位置中傳入所需的資料:
@StructuredPrompt("Create a recipe of a {{dish}} that can be prepared using only {{ingredients}}")
static class RecipeCreationPrompt {
String dish;
List<String> ingredients;
}
接著,將該新類別例項化,並動態饋給食譜的餐點和食材,建立提示並傳遞至 generate()
方法,如下所示:
RecipeCreationPrompt createRecipePrompt = new RecipeCreationPrompt();
createRecipePrompt.dish = "salad";
createRecipePrompt.ingredients = Arrays.asList("cucumber", "tomato", "feta", "onion", "olives");
Prompt prompt = StructuredPromptProcessor.toPrompt(createRecipePrompt);
Response<String> response = model.generate(prompt);
您可以使用 Java 物件,以更加安全的方式使用 Java 物件,其中欄位可由 IDE 自動完成。
如果想輕鬆將這些變更貼到 TextPrompts
類別中,以下是完整的程式碼:
package palm.workshop;
import java.util.Arrays;
import java.util.List;
import dev.langchain4j.model.input.Prompt;
import dev.langchain4j.model.output.Response;
import dev.langchain4j.model.vertexai.VertexAiLanguageModel;
import dev.langchain4j.model.input.structured.StructuredPrompt;
import dev.langchain4j.model.input.structured.StructuredPromptProcessor;
public class TextPrompts {
@StructuredPrompt("Create a recipe of a {{dish}} that can be prepared using only {{ingredients}}")
static class RecipeCreationPrompt {
String dish;
List<String> ingredients;
}
public static void main(String[] args) {
VertexAiLanguageModel model = VertexAiLanguageModel.builder()
.endpoint("us-central1-aiplatform.googleapis.com:443")
.project("YOUR_PROJECT_ID")
.location("us-central1")
.publisher("google")
.modelName("text-bison@001")
.maxOutputTokens(300)
.build();
RecipeCreationPrompt createRecipePrompt = new RecipeCreationPrompt();
createRecipePrompt.dish = "salad";
createRecipePrompt.ingredients = Arrays.asList("cucumber", "tomato", "feta", "onion", "olives");
Prompt prompt = StructuredPromptProcessor.toPrompt(createRecipePrompt);
Response<String> response = model.generate(prompt);
System.out.println(response.content());
}
}
7. 分類文字及分析情緒
與上一節學習到的內容類似,您將瞭解另一種「提示工程」技術,讓 PaLM 模型分類文字或分析情緒。讓我們來談談「少量樣本提示」。這種方法可透過幾個範例強化提示,幫助語言模型找到您想要的方向,進而進一步瞭解意圖。
讓我們重新調整 TextPrompts
類別,以充分運用提示範本:
package palm.workshop;
import java.util.Map;
import dev.langchain4j.model.output.Response;
import dev.langchain4j.model.vertexai.VertexAiLanguageModel;
import dev.langchain4j.model.input.Prompt;
import dev.langchain4j.model.input.PromptTemplate;
public class TextPrompts {
public static void main(String[] args) {
VertexAiLanguageModel model = VertexAiLanguageModel.builder()
.endpoint("us-central1-aiplatform.googleapis.com:443")
.project("YOUR_PROJECT_ID")
.location("us-central1")
.publisher("google")
.modelName("text-bison@001")
.maxOutputTokens(10)
.build();
PromptTemplate promptTemplate = PromptTemplate.from("""
Analyze the sentiment of the text below. Respond only with one word to describe the sentiment.
INPUT: This is fantastic news!
OUTPUT: POSITIVE
INPUT: Pi is roughly equal to 3.14
OUTPUT: NEUTRAL
INPUT: I really disliked the pizza. Who would use pineapples as a pizza topping?
OUTPUT: NEGATIVE
INPUT: {{text}}
OUTPUT:
""");
Prompt prompt = promptTemplate.apply(
Map.of("text", "I love strawberries!"));
Response<String> response = model.generate(prompt);
System.out.println(response.content());
}
}
請注意,如何在提示中提供幾項輸入和輸出內容範例。這些是「少數鏡頭」讓 LLM 遵循相同的結構模型收到輸入內容後,會需要傳回符合輸入/輸出模式的輸出內容。
執行程式應該只傳回 POSITIVE
這個字詞,因為草莓也好笑!
$ ./gradlew run -DjavaMainClass=palm.workshop.TextPrompts
> Task :app:run
POSITIVE
情緒分析也是內容分類情境您可以採行相同的「少量樣本提示」方法,將不同文件分類至不同類別值區。
8. 恭喜
恭喜,您已成功使用 LangChain4J 和 PaLM API 透過 Java 建構第一個生成式 AI 應用程式!一路走來,您發現大型語言模型的功能非常強大,能夠處理各種工作,例如問題/回答、資料擷取、摘要、文字分類、情緒分析等。
後續步驟
請參閱下列程式碼研究室,進一步在 Java 中使用 PaLM: