C.W.K.
Stream
Lesson 02 of 04 · published

generateContent() 와 Streaming

~12 min · typescript, generation, streaming

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

같은 API, TypeScript 모양

TS SDK 가 Python 의 surface 미러링하지만 TypeScript 친화 객체 인자. Python 이 model='...', contents='...' 를 kwarg 로 받는 곳에서 TypeScript 는 객체 한 개: { model, contents, config }.

response.text 는 property

Legacy SDK 에서 port 할 때 가장 큰 함정: response.textproperty, method 아냐. response.text() 라고 쓰면 "string is not callable" 에러 받음.

Streaming 은 generateContentStream 사용

Streaming 함수 이름이 다르고 async iterable 직접 반환:

  • ai.models.generateContent(...) — single response, awaitable.
  • ai.models.generateContentStream(...) — chunk 의 async iterable.

for await 로 stream 소비. 각 chunk 의 chunk.text 가 partial text.

Code

Single-shot generate·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,
  },
});
Response 읽기·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);
Streaming·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] 로 prompt 받아 Flash 응답을 stdout 에 stream 하는 작은 Node 스크립트 stream.mjs 작성. 그 다음 stream 을 SSE 로 browser 에 proxy 하는 작은 Express endpoint 작성. proxy lesson 은 Track 4; 일단 Gemini → server → terminal pipe 동작만 확인.

Progress

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

댓글 0

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

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