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

채팅, 오류, 멀티모달

~14 min · typescript, chat, errors, multimodal

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

TypeScript의 채팅 세션

구조는 Python과 같아. ai.chats.create({...})가 채팅 객체를 반환하고, sendMessage로 메시지를 보내. 대화 기록은 메모리에 유지돼.

오류는 ApiError로 와

TypeScript SDK는 API 오류를 ApiError로 감싸고 name: 'ApiError'를 붙여. instanceof는 모듈 경계에서 믿기 어려울 수 있으니 name으로 확인하고 e.statuse.message를 읽어.

멀티모달에는 createUserContent와 createPartFromUri를 써

한 사용자 차례에 이미지나 파일을 텍스트와 함께 보내려면 이 도우미 함수들을 써. 올바른 parts 구조를 만들어 줘.

Code

여러 차례 이어지는 채팅·typescript
const chat = ai.chats.create({
  model: 'gemini-2.5-flash',
  config: {
    systemInstruction: 'You are a precise but warm tutor.',
  },
});

const r1 = await chat.sendMessage({ message: 'Tell me a fact about octopuses.' });
console.log(r1.text);

const r2 = await chat.sendMessage({ message: 'Now relate that to neural networks.' });
console.log(r2.text);

// Streaming chat
const stream = await chat.sendMessageStream({ message: 'And a haiku?' });
for await (const chunk of stream) {
  if (chunk.text) process.stdout.write(chunk.text);
}
복원력 있는 오류 처리·typescript
import { ApiError } from '@google/genai';

async function robustGenerate(prompt: string, maxRetries = 4) {
  for (let attempt = 0; attempt < maxRetries; attempt++) {
    try {
      return await ai.models.generateContent({
        model: 'gemini-2.5-flash',
        contents: prompt,
      });
    } catch (e: any) {
      if (e?.name === 'ApiError') {
        if (e.status === 429 || (e.status >= 500 && e.status < 600)) {
          // Rate limit or server error — back off and retry
          await new Promise(r => setTimeout(r, Math.min(2 ** attempt, 30) * 1000));
          continue;
        }
        // 4xx other than 429 — your fault, don't retry
        throw e;
      }
      throw e;
    }
  }
  throw new Error(`Gave up after ${maxRetries} retries`);
}
멀티모달 — 이미지와 텍스트·typescript
import { createUserContent, createPartFromUri } from '@google/genai';

// 1. Upload via File API
const uploaded = await ai.files.upload({
  file: 'photo.jpg',
  config: { mimeType: 'image/jpeg' },
});

// 2. Wait for processing if needed
// (large videos go through PROCESSING state)

// 3. Reference in a generateContent call
const response = await ai.models.generateContent({
  model: 'gemini-2.5-flash',
  contents: [
    createUserContent([
      'Describe this image in two sentences:',
      createPartFromUri(uploaded.uri!, uploaded.mimeType!),
    ]),
  ],
});
console.log(response.text);

External links

Exercise

작은 TypeScript 채팅 CLI를 만들어. 한 줄씩 읽어 스트리밍 채팅으로 보내고 표준 출력에 그린 뒤, 대화 기록을 JSONL 파일에 저장해. API 호출에는 robustGenerate를 적용해 429가 반복을 죽이지 않게 하고, JSONL을 다시 읽어 프로그램을 재시작해도 채팅이 이어지는지 확인해.

Progress

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

댓글 0

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

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