0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Gemini API ― チャット

Last updated at Posted at 2024-09-23

概要

(日記)前回

の続き。Node.jsで試す。

環境

  • Ubuntu 24.04
  • Node.js v22.4.1

Project準備

generateContent() ―― 一問一答

src/generateContent.ts
import { GoogleGenerativeAI } from "@google/generative-ai"

async function main() {
    const key = process.env.GOOGLE_API_KEY ?? ""
    const genAI = new GoogleGenerativeAI(key)
    const model = genAI.getGenerativeModel({ model: "gemini-1.5-flash" })
    
    async function qa(q: string) {
        const a = await model.generateContent(q)
        console.log(`Q: ${q}`)
        console.log(`A: ${a.response.text()}`)
    }

    await qa("三角、四角、五角形、の次は? 簡潔に")
    await qa("その次は? 簡潔に")
}

main()
Run
export GOOGLE_API_KEY=<your-api-key>
npx -y ts-node src/generateContent.ts 
結果
Q: 三角、四角、五角形、の次は? 簡潔に
A: 六角形。

Q: その次は? 簡潔に
A: 「その次は」は何の続きについてですか?もう少し詳しく教えてください。

startChat()/sendMessage() ―― 文脈を覚えてほしい

src/sendMessage.ts
import { GoogleGenerativeAI } from "@google/generative-ai"

async function main() {
    const key = process.env.GOOGLE_API_KEY ?? ""
    const genAI = new GoogleGenerativeAI(key)
    const model = genAI.getGenerativeModel({ model: "gemini-1.5-flash" })
    const chat = model.startChat()

    async function qa(q: string) {
        const a = await chat.sendMessage(q)
        console.log(`Q: ${q}`)
        console.log(`A: ${a.response.text()}`)
        console.log(a.response.usageMetadata)
    }

    await qa("三角、四角、五角形、の次は? 簡潔に")
    await qa("その次は? 簡潔に")
    await qa("その前は? 簡潔に")
}

main()
Run
export GOOGLE_API_KEY=<your-api-key>
npx -y ts-node src/sendMessage.ts 
結果
Q: 三角、四角、五角形、の次は? 簡潔に
A: 六角形です。
{ promptTokenCount: 16, candidatesTokenCount: 5, totalTokenCount: 21 }
Q: その次は? 簡潔に
A: 七角形です。
{ promptTokenCount: 31, candidatesTokenCount: 5, totalTokenCount: 36 }
Q: その前は? 簡潔に
A: 三角形です。
{ promptTokenCount: 46, candidatesTokenCount: 4, totalTokenCount: 50 }

この例のToken合計(平均)
gemini-1.5-flash: 50,48,50 (49.3)
gemini-1.0-pro: 41,41,41 (41)
gemini-1.5-pro: statusText: 'Too Many Requests' (2回/分制限)

今回のソースコード

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?