1. 소개
최종 업데이트: 2023년 11월 27일
생성형 AI란 무엇인가요
생성형 AI 또는 생성형 인공지능은 AI를 사용하여 텍스트, 이미지, 음악, 오디오, 동영상과 같은 새로운 콘텐츠를 만드는 것을 의미합니다.
생성형 AI는 요약, 질의응답, 분류 등 다양한 작업을 즉시 수행할 수 있는 대규모 AI 모델인 파운데이션 모델을 기반으로 합니다. 또한 파운데이션 모델은 예시 데이터가 매우 적어도 최소한의 학습만으로 특정 사용 사례에 맞게 조정할 수 있습니다.
생성형 AI는 어떻게 작동하나요?
생성형 AI는 ML (머신러닝) 모델을 사용하여 사람이 만든 콘텐츠의 데이터 세트에서 패턴과 관계를 학습하는 방식으로 작동합니다. 그런 다음 학습된 패턴을 사용하여 새 콘텐츠를 생성합니다.
생성형 AI 모델을 학습시키는 가장 일반적인 방법은 지도 학습을 사용하는 것입니다. 지도 학습에는 사람이 만든 콘텐츠와 해당 라벨의 집합이 부여됩니다. 그런 다음 사람이 만든 콘텐츠와 유사하고 동일한 라벨이 지정된 콘텐츠를 생성하는 방법을 학습합니다.
일반적인 생성형 AI 애플리케이션은 무엇인가요?
생성형 AI는 방대한 콘텐츠를 처리하여 텍스트, 이미지, 사용자 친화적인 형식을 통해 유용한 정보와 답변을 제공합니다. 생성형 AI는 다음과 같은 용도로 사용할 수 있습니다.
- 향상된 채팅 및 검색 환경을 통해 고객 상호작용 개선
- 대화형 인터페이스 및 요약을 통해 방대한 양의 구조화되지 않은 데이터 탐색
- 제안 요청서 (RFP)에 대한 답장을 작성하고, 동일한 마케팅 콘텐츠를 5가지 언어로 작성하고, 고객 계약이 규정을 준수하는지 확인하는 등의 반복적인 작업 지원
Google Cloud에는 어떤 생성형 AI 제품이 있나요?
Vertex AI를 사용하면 ML 전문 지식이 거의 없어도 애플리케이션에 기반 모델을 사용, 맞춤설정, 삽입할 수 있습니다. Model Garden에서 기반 모델에 액세스하고, Generative AI Studio에서 간단한 UI를 통해 모델을 조정하거나, 데이터 과학 노트북에서 모델을 사용할 수 있습니다.
Vertex AI Search and Conversation은 개발자가 생성형 AI 기반 검색엔진과 챗봇을 빌드할 수 있는 가장 빠른 방법을 제공합니다.
Duet AI는 Google Cloud 및 IDE 전반에서 사용할 수 있는 AI 기반 공동작업 도구로, 더 많은 작업을 더 빠르게 수행할 수 있도록 지원합니다.
이 Codelab에서는 무엇에 중점을 두나요?
이 Codelab에서는 모든 머신러닝 제품과 서비스를 포함하는 Google Cloud Vertex AI에서 호스팅되는 PaLM 2 대규모 언어 모델 (LLM)에 중점을 둡니다.
Java를 사용하여 PaLM API와 상호작용하고 LangChain4J LLM 프레임워크 오케스트레이터를 사용합니다. 다양한 구체적인 예를 통해 LLM을 활용하여 질문에 답변하고, 아이디어를 생성하고, 엔티티와 구조화된 콘텐츠를 추출하고, 요약하는 방법을 알아봅니다.
LangChain4J 프레임워크에 대해 자세히 알려 줘.
LangChain4J 프레임워크는 LLM 자체뿐만 아니라 벡터 데이터베이스 (시맨틱 검색용), 문서 로더 및 스플리터 (문서 분석 및 학습용), 출력 파서 등 다양한 구성요소를 오케스트레이션하여 Java 애플리케이션에 대규모 언어 모델을 통합하기 위한 오픈소스 라이브러리입니다.

학습할 내용
- PaLM 및 LangChain4J를 사용하도록 Java 프로젝트를 설정하는 방법
- PaLM 텍스트 모델을 처음 호출하여 콘텐츠를 생성하고 질문에 답변하는 방법
- 비구조화 콘텐츠에서 유용한 정보를 추출하는 방법 (항목 또는 키워드 추출, JSON으로 출력)
- 소수의 예시 프롬프트를 사용하여 콘텐츠 분류 또는 감정 분석을 수행하는 방법
필요한 항목
- Java 프로그래밍 언어에 대한 지식
- Google Cloud 프로젝트
- 브라우저(예: Chrome, Firefox)
2. 설정 및 요건
자습형 환경 설정
- Google Cloud Console에 로그인하여 새 프로젝트를 만들거나 기존 프로젝트를 재사용합니다. 아직 Gmail이나 Google Workspace 계정이 없는 경우 계정을 만들어야 합니다.



- 프로젝트 이름은 이 프로젝트 참가자의 표시 이름입니다. 이는 Google API에서 사용하지 않는 문자열이며 언제든지 업데이트할 수 있습니다.
- 프로젝트 ID는 모든 Google Cloud 프로젝트에서 고유하며, 변경할 수 없습니다(설정된 후에는 변경할 수 없음). Cloud 콘솔은 고유한 문자열을 자동으로 생성합니다. 일반적으로는 신경 쓰지 않아도 됩니다. 대부분의 Codelab에서는 프로젝트 ID (일반적으로
PROJECT_ID로 식별됨)를 참조해야 합니다. 생성된 ID가 마음에 들지 않으면 다른 임의 ID를 생성할 수 있습니다. 또는 직접 시도해 보고 사용 가능한지 확인할 수도 있습니다. 이 단계 이후에는 변경할 수 없으며 프로젝트 기간 동안 유지됩니다. - 참고로 세 번째 값은 일부 API에서 사용하는 프로젝트 번호입니다. 이 세 가지 값에 대한 자세한 내용은 문서를 참고하세요.
- 다음으로 Cloud 리소스/API를 사용하려면 Cloud 콘솔에서 결제를 사용 설정해야 합니다. 이 Codelab 실행에는 많은 비용이 들지 않습니다. 이 튜토리얼이 끝난 후에 요금이 청구되지 않도록 리소스를 종료하려면 만든 리소스 또는 프로젝트를 삭제하면 됩니다. Google Cloud 신규 사용자는 300달러(USD) 상당의 무료 체험판 프로그램에 참여할 수 있습니다.
Cloud Shell 시작
Google Cloud를 노트북에서 원격으로 실행할 수 있지만, 이 Codelab에서는 Cloud에서 실행되는 명령줄 환경인 Cloud Shell을 사용합니다.
Cloud Shell 활성화
- Cloud Console에서 Cloud Shell 활성화
를 클릭합니다.

Cloud Shell을 처음 시작하는 경우 설명이 포함된 중간 화면이 제공됩니다. 중간 화면이 표시되면 계속을 클릭합니다.

Cloud Shell을 프로비저닝하고 연결하는 작업은 몇 분이면 끝납니다.

이 가상 머신에는 필요한 개발 도구가 모두 로드되어 있습니다. 영구적인 5GB 홈 디렉터리를 제공하고 Google Cloud에서 실행되므로 네트워크 성능과 인증이 크게 개선됩니다. 이 Codelab에서 대부분의 작업은 브라우저로 수행할 수 있습니다.
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. 개발 환경 준비
이 Codelab에서는 Cloud Shell 터미널과 코드 편집기를 사용하여 Java 프로그램을 개발합니다.
Vertex AI API 사용 설정
- Google Cloud 콘솔에서 프로젝트 이름이 Google Cloud 콘솔 상단에 표시되는지 확인합니다. 선택되어 있지 않다면 프로젝트 선택을 클릭하여 프로젝트 선택기를 열고 원하는 프로젝트를 선택합니다.
- Google Cloud 콘솔의 Vertex AI 부분에 있지 않은 경우 다음을 수행합니다.
- 검색에 Vertex AI를 입력하고 Enter 키를 누릅니다.
- 검색 결과에서 Vertex AI를 클릭합니다. Vertex AI 대시보드가 표시됩니다.
- Vertex AI 대시보드에서 모든 권장 API 사용 설정을 클릭합니다.
이렇게 하면 여러 API가 사용 설정되지만 Codelab에서 가장 중요한 API는 aiplatform.googleapis.com입니다. 다음 명령어를 실행하여 Cloud Shell 터미널의 명령줄에서도 사용 설정할 수 있습니다.
$ 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
하위 프로젝트를 사용하지 않고 (옵션 1) 빌드 파일에 Groovy 구문을 사용 (옵션 1)하여 새 빌드 기능을 사용하지 않고 (옵션 없음) JUnit Jupiter (옵션 4)로 테스트를 생성하여 Java 언어 (옵션 3)를 사용하여 애플리케이션 (옵션 2)을 빌드합니다. 프로젝트 이름은 palm-workshop을 사용하고 소스 패키지는 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에는 두 가지 종속 항목이 있습니다.
- 핵심 프로젝트에 하나,
- 전용 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 디렉터리 (기본 App.java 클래스와 함께)에 TextPrompts.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에 대한 시를 써 줘'
- 프로그래밍 - '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;
그런 다음 @StructuredPrompt 주석에 설명된 프롬프트의 자리표시자에 전달하는 데 필요한 데이터를 수집하는 내부 정적 클래스를 TextPrompts 클래스 내에 만들 수 있습니다.
@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);
지도를 통해 간격을 채우는 대신 IDE에서 자동 완성할 수 있는 필드가 있는 Java 객체를 더 유형 안전한 방식으로 사용할 수 있습니다.
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());
}
}
프롬프트에서 입력과 출력의 몇 가지 예시를 제공하는 접근 방식을 확인하세요. 이러한 'few shots'은 LLM이 동일한 구조를 따르도록 지원합니다. 그런 다음 모델이 입력을 받으면 입력/출력 패턴과 일치하는 출력을 반환하려고 합니다.
프로그램을 실행하면 딸기도 맛있기 때문에 POSITIVE라는 단어만 반환됩니다.
$ ./gradlew run -DjavaMainClass=palm.workshop.TextPrompts
> Task :app:run
POSITIVE
감정 분석도 콘텐츠 분류 시나리오입니다. 동일한 '퓨샷 프롬프팅' 접근 방식을 적용하여 여러 문서를 여러 카테고리 버킷으로 분류할 수 있습니다.
8. 축하합니다
축하합니다. LangChain4J 및 PaLM API를 사용하여 Java로 첫 번째 생성형 AI 애플리케이션을 빌드했습니다. 그 과정에서 대규모 언어 모델이 매우 강력하며 질문/답변, 데이터 추출, 요약, 텍스트 분류, 감정 분석 등 다양한 작업을 처리할 수 있다는 것을 알게 되었습니다.
다음 단계
다음 Codelab을 확인하여 Java에서 PaLM을 자세히 알아보세요.