본문 바로가기
C.W.K.
Stream
Lesson 02 of 04 · published

generateContent()와 스트리밍

~12 min · typescript, generation, streaming

Level 0불씨
0 XP0/35 lessons0/10 achievements
0/140 XP to next level140 XP to go0% complete

같은 API를 TypeScript답게 쓰기

TypeScript SDK는 Python API와 대응하지만 인자는 TypeScript에 어울리는 객체로 받아. Python에서 model='...', contents='...' 같은 키워드 인자를 넘기는 자리에 TypeScript는 { model, contents, config } 객체 하나를 넘겨.

response.text는 속성이야

예전 SDK에서 옮길 때 가장 큰 함정이야. response.text속성이지 메서드가 아니야. response.text()라고 쓰면 "string is not callable" 오류가 나.

스트리밍에는 generateContentStream을 써

스트리밍 함수는 이름이 다르고 비동기 이터러블을 바로 반환해:

  • ai.models.generateContent(...) — await할 수 있는 응답 하나를 반환해.
  • ai.models.generateContentStream(...) — 청크의 비동기 이터러블을 반환해.

for await로 스트림을 순회하면 돼. 각 청크의 chunk.text에 부분 텍스트가 들어 있어.

Code

한 번에 생성하기·typescript
const response = await ai.models.generateContent({
  model: 'gemini-2.5-flash',
  contents: 'Why is the sky blue?',
});
console.log(response.text);

// With config
const response2 = await ai.models.generateContent({
  model: 'gemini-2.5-flash',
  contents: 'Explain quantum entanglement.',
  config: {
    systemInstruction: 'You are a precise but warm tutor.',
    maxOutputTokens: 500,
    temperature: 0.3,
    topP: 0.9,
    topK: 40,
  },
});
응답 읽기·typescript
// 90% case: just the text
console.log(response.text);  // string

// Function calls (Track 5)
console.log(response.functionCalls);  // FunctionCall[] | undefined

// Finish reason — always check before trusting text
const finishReason = response.candidates?.[0]?.finishReason;
if (finishReason !== 'STOP') {
  throw new Error(`Generation did not finish cleanly: ${finishReason}`);
}

// Token counts
console.log(response.usageMetadata?.totalTokenCount);
스트리밍·typescript
const stream = await ai.models.generateContentStream({
  model: 'gemini-2.5-flash',
  contents: 'Write a 200-word story.',
});

let finalUsage;
for await (const chunk of stream) {
  if (chunk.text) {
    process.stdout.write(chunk.text);
  }
  if (chunk.usageMetadata) {
    finalUsage = chunk.usageMetadata;
  }
}
console.log(`\n[total tokens: ${finalUsage?.totalTokenCount}]`);

External links

Exercise

process.argv[2]로 프롬프트를 받아 Flash 응답을 표준 출력으로 흘려보내는 작은 Node 스크립트 stream.mjs를 작성해. 그다음 스트림을 SSE로 브라우저에 중계하는 작은 Express 엔드포인트를 만들어. 프록시는 트랙 4에서 자세히 다룰 테니, 여기서는 Gemini → 서버 → 터미널 흐름만 확인해.

Progress

Progress is local-only — sign in to sync across devices.
이 페이지에서 버그를 발견하셨거나 피드백이 있으세요?문제 신고

댓글 0

🔔 답글 알림 (로그인 필요)
로그인댓글을 남기려면 로그인해 주세요.

아직 댓글이 없어요. 첫 댓글을 남겨보세요.