본문으로 건너뛰기

Cohere

Cohere 어댑터는 RAG 파이프라인의 두 가지 검색 단계를 지원합니다.

  • 임베딩 (cohereEmbedding): embed()를 사용해 텍스트, 이미지, 텍스트와 이미지가 결합된 입력을 벡터로 변환합니다.
  • 재순위 지정 (cohereRerank): rerank()를 사용해 쿼리와의 관련성에 따라 후보 문서의 순서를 다시 지정합니다.

chat(), summarize() 또는 미디어 생성을 지원하지 않습니다. 이러한 기능에는 OpenAI, Anthropic 또는 Gemini를 사용합니다. 이 어댑터는 SDK 의존성 없이 fetch를 통해 Cohere의 HTTP API와 직접 통신합니다.

설치

npm install @tanstack/ai @tanstack/ai-cohere

임베딩

import { embed } from "@tanstack/ai";
import { cohereEmbedding } from "@tanstack/ai-cohere";

const result = await embed({
adapter: cohereEmbedding("embed-v4.0"),
input: ["a red guitar", "a blue drum kit"],
modelOptions: { inputType: "search_document" },
});

console.log(result.embeddings[0]?.vector);
console.log(result.usage?.promptTokens);

inputType은 Cohere API에서 필수입니다. 인덱스를 생성할 때는 search_document를, 쿼리할 때는 search_query를 사용합니다(해당 워크로드에는 classification 또는 clustering 사용). TanStack AI는 이를 타입 수준에서 강제하므로 Cohere 임베딩 호출에는 modelOptions가 필요합니다.

멀티모달 임베딩

embed-v4.0은 텍스트와 함께 이미지를 임베딩합니다. 이미지 파트는 이미지 벡터를 생성합니다. 파트의 중첩 배열([textPart, imagePart])은 텍스트와 이미지를 하나의 벡터로 결합하므로 제품 카탈로그와 스크린샷 검색에 적합합니다. 바깥쪽 배열은 항목 목록이므로 결합하려면 중첩해야 합니다.

import { embed } from "@tanstack/ai";
import { cohereEmbedding } from "@tanstack/ai-cohere";

const productPhoto = "iVBORw0KGgo..."; // base64 image data

const result = await embed({
adapter: cohereEmbedding("embed-v4.0"),
input: [
{
type: "image",
source: {
type: "data",
value: productPhoto,
mimeType: "image/png",
},
},
// A nested array fuses its parts into a single vector.
[
{ type: "text", content: "Fender Stratocaster, sunburst finish" },
{
type: "image",
source: {
type: "data",
value: productPhoto,
mimeType: "image/png",
},
},
],
],
modelOptions: { inputType: "search_document" },
});

console.log(result.embeddings.length); // 2

Cohere API는 원격 이미지 URL을 가져오지 않습니다. base64 데이터(또는 data: URI)를 전달하거나 어댑터 측 다운로드를 사용하도록 설정합니다.

import { embed } from "@tanstack/ai";
import { cohereEmbedding } from "@tanstack/ai-cohere";

const adapter = cohereEmbedding("embed-v4.0", { allowUrlFetch: true });

const result = await embed({
adapter,
input: {
type: "image",
source: { type: "url", value: "https://example.com/guitar.png" },
},
modelOptions: { inputType: "search_document" },
});

차원 요청

embed-v4.0은 최상위 dimensions 옵션을 통해 Matryoshka 출력 차원을 지원합니다.

import { embed } from "@tanstack/ai";
import { cohereEmbedding } from "@tanstack/ai-cohere";

const result = await embed({
adapter: cohereEmbedding("embed-v4.0"),
input: "a red guitar",
dimensions: 1024, // 256 | 512 | 1024 | 1536
modelOptions: { inputType: "search_document" },
});

재순위 지정

import { rerank } from "@tanstack/ai";
import { cohereRerank } from "@tanstack/ai-cohere";

const { rerankedDocuments } = await rerank({
adapter: cohereRerank("rerank-v3.5"),
query: "talk about rain",
documents: ["sunny day at the beach", "rainy afternoon in the city"],
});

console.log(rerankedDocuments[0]); // 'rainy afternoon in the city'

객체 문서, RAG 파이프라인, 옵션 및 결과 형태를 포함한 전체 재순위 지정 가이드는 재순위 지정을 참조합니다.

요청별 재순위 지정 옵션은 modelOptions에 지정합니다.

import { rerank } from "@tanstack/ai";
import { cohereRerank } from "@tanstack/ai-cohere";

const { ranking } = await rerank({
adapter: cohereRerank("rerank-v3.5"),
query: "refund policy",
documents: ["Returns accepted within 30 days.", "Free shipping over $50."],
modelOptions: {
maxTokensPerDoc: 512, // Cap tokens kept per document (Cohere default: 4096)
},
});

console.log(ranking);

모델

모델기능설명
embed-v4.0임베딩멀티모달(텍스트 + 이미지), Matryoshka dimensions 지원
rerank-v3.5재순위 지정최신 다국어 재순위 지정 모델(권장)
rerank-english-v3.0재순위 지정영어에 최적화된 재순위 지정 모델
rerank-multilingual-v3.0재순위 지정다국어 재순위 지정 모델

환경 변수

두 어댑터 모두 환경 변수에서 API 키를 읽습니다.

COHERE_API_KEY=your-cohere-api-key
변수필수설명
COHERE_API_KEYCohere API 키

Cohere 대시보드에서 키를 가져옵니다.

명시적 API 키

환경 변수에서 읽는 대신 키를 직접 전달하려면 create* 팩토리를 사용합니다.

import {
createCohereEmbedding,
createCohereRerank,
} from "@tanstack/ai-cohere";

const embedAdapter = createCohereEmbedding(
"embed-v4.0",
process.env.MY_COHERE_KEY!,
);
const rerankAdapter = createCohereRerank("rerank-v3.5", "your-cohere-api-key");

API 참조

cohereEmbedding(model, config?)

환경 변수의 COHERE_API_KEY를 사용해 임베딩 어댑터를 생성합니다.

  • model: "embed-v4.0"
  • config.baseUrl: API 기본 URL을 재정의합니다(기본값 https://api.cohere.com)
  • config.headers: 추가 요청 헤더
  • config.allowUrlFetch: http(s) 이미지 URL을 다운로드하고 base64로 인라인 처리합니다(기본값 false)

createCohereEmbedding(model, apiKey, config?)

명시적 API 키를 사용하는 cohereEmbedding과 동일합니다.

cohereRerank(model, config?)

환경 변수의 COHERE_API_KEY를 사용해 재순위 지정 어댑터를 생성합니다.

  • model: 위의 재순위 지정 모델 중 하나
  • config.baseUrl: API 기본 URL을 재정의합니다(기본값 https://api.cohere.com)
  • config.headers: 추가 요청 헤더

createCohereRerank(model, apiKey, config?)

명시적 API 키를 사용하는 cohereRerank와 동일합니다.

다음 단계