Google VertexAI 텍스트 임베딩
Google VertexAI 텍스트 임베딩 (Text Embeddings)
Vertex AI는 텍스트와 멀티모달 두 가지 유형의 임베딩 모델을 지원해요. 이 문서는 Vertex AI Text embeddings API를 사용해 텍스트 임베딩을 만드는 방법을 설명해요. Vertex AI 텍스트 임베딩 API는 밀집 벡터 표현을 사용해서, 직접적인 단어나 구문 일치 대신 쿼리의 의미와 일치하는 구절을 더 잘 검색할 수 있게 해줘요.
출처: 문서
본문
Vertex AI는 텍스트와 멀티모달 두 가지 유형의 임베딩 모델을 지원해요. 이 문서는 Vertex AI Text embeddings API를 사용해 텍스트 임베딩을 만드는 방법을 설명해요.
Vertex AI 텍스트 임베딩 API는 밀집 벡터 표현(dense vector representation)을 사용해요. 단어를 숫자로 직접 매핑하는 경향이 있는 희소 벡터(sparse vector)와 달리, 밀집 벡터는 텍스트 조각의 의미를 더 잘 표현하도록 설계됐어요. 생성형 AI에서 밀집 벡터 임베딩을 사용하는 이점은, 직접적인 단어나 구문 일치를 검색하는 대신 쿼리의 의미와 일치하는 구절을 더 잘 검색할 수 있다는 점이에요. 구절이 같은 언어를 사용하지 않아도 말이죠.
Prerequisites
-
운영체제에 맞는 gcloud CLI를 설치하세요.
-
다음 명령을 실행해 인증하세요.
PROJECT_ID를 Google Cloud 프로젝트 ID로,ACCOUNT를 Google Cloud 사용자 이름으로 바꾸세요.gcloud config set project <PROJECT_ID> && gcloud auth application-default login
Add Repositories and BOM
Spring AI 아티팩트는 Maven Central과 Spring Snapshot 저장소에 게시돼요. 빌드 시스템에 이러한 저장소를 추가하려면 Artifact Repositories 섹션을 참고하세요.
의존성 관리를 돕기 위해 Spring AI는 프로젝트 전체에서 일관된 Spring AI 버전을 사용하도록 보장하는 BOM(bill of materials)을 제공해요. 빌드 시스템에 Spring AI BOM을 추가하려면 Dependency Management 섹션을 참고하세요.
Auto-configuration
| __ | Spring AI 자동 설정과 스타터 모듈 아티팩트 이름에 큰 변경이 있었어요. 자세한 내용은 upgrade notes를 참고해주세요. |
|---|
Spring AI는 VertexAI Embedding Model에 대한 Spring Boot 자동 설정을 제공해요. 활성화하려면 프로젝트의 Maven pom.xml 파일에 다음 의존성을 추가하세요:
<dependency>
<groupId>org.springframework.ai</groupId>
<artifactId>spring-ai-starter-model-vertex-ai-embedding</artifactId>
</dependency>
또는 Gradle build.gradle 빌드 파일에 추가할 수도 있어요:
dependencies {
implementation 'org.springframework.ai:spring-ai-starter-model-vertex-ai-embedding'
}
| __ | 빌드 파일에 Spring AI BOM을 추가하려면 Dependency Management 섹션을 참고해주세요. |
|---|
Embedding Properties
프리픽스 spring.ai.vertex.ai.embedding은 VertexAI Embedding API에 연결할 수 있게 해주는 프로퍼티 프리픽스예요.
| Property | Description | Default |
|---|---|---|
| spring.ai.vertex.ai.embedding.project-id | Google Cloud Platform 프로젝트 ID | - |
| spring.ai.vertex.ai.embedding.location | 리전 | - |
| spring.ai.vertex.ai.embedding.api-endpoint | Vertex AI Embedding API 엔드포인트. | - |
| __ | 임베딩 자동 설정의 활성화/비활성화는 이제 프리픽스 spring.ai.model.embedding이 붙은 최상위 프로퍼티로 설정해요. 활성화하려면 spring.ai.model.embedding.text=vertexai (기본값으로 활성화됨). 비활성화하려면 spring.ai.model.embedding.text=none (또는 vertexai와 일치하지 않는 어떤 값). 이 변경은 여러 모델의 설정을 허용하기 위한 것이에요. |
|---|
프리픽스 spring.ai.vertex.ai.embedding.text는 VertexAI 텍스트 임베딩의 임베딩 모델 구현을 구성할 수 있게 해주는 프로퍼티 프리픽스예요.
| Property | Description | Default |
|---|---|---|
| spring.ai.vertex.ai.embedding.text.enabled (제거됨, 더 이상 유효하지 않음) | Vertex AI Embedding API 모델 활성화. | true |
| spring.ai.model.embedding.text | Vertex AI Embedding API 모델 활성화. | vertexai |
| spring.ai.vertex.ai.embedding.text.model | 사용할 Vertex Text Embedding 모델 | text-embedding-004 |
| spring.ai.vertex.ai.embedding.text.task-type | 더 나은 품질의 임베딩을 생성하도록 모델을 돕기 위한 의도된 다운스트림 애플리케이션. 사용 가능한 task-types | RETRIEVAL_DOCUMENT |
| spring.ai.vertex.ai.embedding.text.title | 선택적 제목, task_type=RETRIEVAL_DOCUMENT에서만 유효. | - |
| spring.ai.vertex.ai.embedding.text.dimensions | 결과 출력 임베딩이 가져야 하는 차원 수. 모델 버전 004 이상에서 지원돼요. 예를 들어 저장 최적화를 위해 임베딩 크기를 줄이는 데 이 매개변수를 사용할 수 있어요. | - |
| spring.ai.vertex.ai.embedding.text.auto-truncate | true로 설정하면 입력 텍스트가 잘려요(truncate). false로 설정하면 입력 텍스트가 모델이 지원하는 최대 길이보다 길 때 오류가 반환돼요. | true |
Sample Controller
새 Spring Boot 프로젝트를 만들고, pom(또는 gradle) 의존성에 spring-ai-starter-model-vertex-ai-embedding을 추가하세요.
src/main/resources 디렉터리 아래에 application.properties 파일을 추가해 VertexAi 채팅 모델을 활성화하고 구성해요:
spring.ai.vertex.ai.embedding.project-id=<YOUR_PROJECT_ID>
spring.ai.vertex.ai.embedding.location=<YOUR_PROJECT_LOCATION>
spring.ai.vertex.ai.embedding.text.model=text-embedding-004
이렇게 하면 클래스에 주입할 수 있는 VertexAiTextEmbeddingModel 구현이 생성돼요. 임베딩 생성을 위해 임베딩 모델을 사용하는 간단한 @Controller 클래스 예시예요:
@RestController
public class EmbeddingController {
private final EmbeddingModel embeddingModel;
@Autowired
public EmbeddingController(EmbeddingModel embeddingModel) {
this.embeddingModel = embeddingModel;
}
@GetMapping("/ai/embedding")
public Map embed(@RequestParam(value = "message", defaultValue = "Tell me a joke") String message) {
EmbeddingResponse embeddingResponse = this.embeddingModel.embedForResponse(List.of(message));
return Map.of("embedding", embeddingResponse);
}
}
Manual Configuration
VertexAiTextEmbeddingModel은 EmbeddingModel을 구현해요.
프로젝트의 Maven pom.xml 파일에 spring-ai-vertex-ai-embedding 의존성을 추가하세요:
<dependency>
<groupId>org.springframework.ai</groupId>
<artifactId>spring-ai-vertex-ai-embedding</artifactId>
</dependency>
또는 Gradle build.gradle 빌드 파일에 추가할 수도 있어요:
dependencies {
implementation 'org.springframework.ai:spring-ai-vertex-ai-embedding'
}
| __ | 빌드 파일에 Spring AI BOM을 추가하려면 Dependency Management 섹션을 참고해주세요. |
|---|
다음으로 VertexAiTextEmbeddingModel을 만들고 텍스트 생성에 사용해요:
VertexAiEmbeddingConnectionDetails connectionDetails =
VertexAiEmbeddingConnectionDetails.builder()
.projectId(System.getenv(<VERTEX_AI_GEMINI_PROJECT_ID>))
.location(System.getenv(<VERTEX_AI_GEMINI_LOCATION>))
.build();
VertexAiTextEmbeddingOptions options = VertexAiTextEmbeddingOptions.builder()
.model(VertexAiTextEmbeddingOptions.DEFAULT_MODEL_NAME)
.build();
var embeddingModel = new VertexAiTextEmbeddingModel(this.connectionDetails, this.options);
EmbeddingResponse embeddingResponse = this.embeddingModel
.embedForResponse(List.of("Hello World", "World is big and salvation is near"));
Load credentials from a Google Service Account
Service Account json 파일에서 프로그래밍 방식으로 GoogleCredentials를 로드하려면 다음을 사용할 수 있어요:
GoogleCredentials credentials = GoogleCredentials.fromStream(<INPUT_STREAM_TO_CREDENTIALS_JSON>)
.createScoped("https://www.googleapis.com/auth/cloud-platform");
credentials.refreshIfExpired();
VertexAiEmbeddingConnectionDetails connectionDetails =
VertexAiEmbeddingConnectionDetails.builder()
.projectId(System.getenv(<VERTEX_AI_GEMINI_PROJECT_ID>))
.location(System.getenv(<VERTEX_AI_GEMINI_LOCATION>))
.apiEndpoint(endpoint)
.predictionServiceSettings(
PredictionServiceSettings.newBuilder()
.setEndpoint(endpoint)
.setCredentialsProvider(FixedCredentialsProvider.create(credentials))
.build());