Closed11
Gemini API クイックスタートやってみる
パッケージをgo getする。
vscode ➜ /workspaces/geminiApiQuickStart/app $ go mod init geminiApiQuickStart
go: creating new go.mod: module geminiApiQuickStart
vscode ➜ /workspaces/geminiApiQuickStart/app $ go get github.com/google/generative-ai-go
go: downloading github.com/google/generative-ai-go v0.18.0
go: added github.com/google/generative-ai-go v0.18.0
Get API Keyを選択
APIキー取得画面にあったcurlを実行してみる
vscode ➜ /workspaces/geminiApiQuickStart/app $ curl \
-H 'Content-Type: application/json' \
-d '{"contents":[{"parts":[{"text":"Explain how AI works"}]}]}' \
-X POST 'https://generativelanguage.googleapis.com/v1beta/models/gemini-1.5-flash-latest:generateContent?key=YOUR_API_KEY'
{
"error": {
"code": 400,
"message": "API key not valid. Please pass a valid API key.",
"status": "INVALID_ARGUMENT",
"details": [
{
"@type": "type.googleapis.com/google.rpc.ErrorInfo",
"reason": "API_KEY_INVALID",
"domain": "googleapis.com",
"metadata": {
"service": "generativelanguage.googleapis.com"
}
}
]
}
}
- APIキー指定してないので400(あたりまえ)
「APIキーを作成」ボタンを押して新規プロジェクト(GCP?)でキー作成。
キーを指定して再度実行
{
"candidates": [
{
"content": {
"parts": [
{
"text": "## How AI Works: A Simplified Explanation\n\nArtificial Intelligence (AI) is a broad field that encompasses various techniques and technologies designed to mimic human intelligence. Here's a simplified explanation of how it works:\n\n**1. Learning from Data:** AI systems learn by analyzing vast amounts of data. This data can be anything from images and text to sensor readings and financial records. The more data an AI system has access to, the better it can learn and make predictions.\n\n**2. Algorithms and Models:** AI systems use algorithms to process and analyze this data. These algorithms are mathematical formulas that define how the AI system will learn and make decisions. Examples include:\n\n * **Machine Learning (ML):** AI systems learn patterns and relationships from data without explicit programming. This includes supervised learning (learning from labeled data), unsupervised learning (finding patterns in unlabeled data), and reinforcement learning (learning through trial and error).\n * **Deep Learning (DL):** A subset of ML that uses artificial neural networks with multiple layers to extract complex features from data. These networks are inspired by the human brain and can learn intricate patterns.\n\n**3. Training and Evaluation:** AI systems are \"trained\" on large datasets, adjusting their algorithms and models to improve their performance. This involves feeding the system with labeled data and evaluating its accuracy in predicting the correct outputs. \n\n**4. Making Predictions and Decisions:** Once trained, AI systems can use their learned models to make predictions or decisions based on new data. This can include tasks like classifying images, translating languages, generating text, and controlling robots.\n\n**5. Continuous Improvement:** AI systems are constantly evolving and improving. As they are exposed to more data and feedback, they can adapt and become more accurate and efficient.\n\n**Examples of AI in Action:**\n\n* **Self-driving cars:** Use computer vision and deep learning to perceive their surroundings, navigate roads, and make driving decisions.\n* **Virtual assistants:** Use natural language processing to understand human speech and respond to questions.\n* **Spam filters:** Identify and block unwanted emails using machine learning algorithms.\n* **Medical diagnosis:** Use AI to analyze medical images and identify potential health issues.\n\n**Important Note:** AI is a powerful tool, but it's not magic. It relies on data, algorithms, and computation. It's essential to be aware of its limitations and ethical considerations.\n\nThis explanation provides a basic overview of how AI works. There's much more to explore, such as different types of AI, specific algorithms, and ethical implications. But hopefully, this gives you a starting point to understand this fascinating and rapidly developing field.\n"
}
],
"role": "model"
},
"finishReason": "STOP",
"index": 0,
"safetyRatings": [
{
"category": "HARM_CATEGORY_SEXUALLY_EXPLICIT",
"probability": "NEGLIGIBLE"
},
{
"category": "HARM_CATEGORY_HATE_SPEECH",
"probability": "NEGLIGIBLE"
},
{
"category": "HARM_CATEGORY_HARASSMENT",
"probability": "NEGLIGIBLE"
},
{
"category": "HARM_CATEGORY_DANGEROUS_CONTENT",
"probability": "NEGLIGIBLE"
}
],
"citationMetadata": {
"citationSources": [
{
"startIndex": 833,
"endIndex": 989,
"uri": "https://www.patsnap.com/glossary/data-science-and-machine-learning/",
"license": ""
}
]
}
}
],
"usageMetadata": {
"promptTokenCount": 4,
"candidatesTokenCount": 552,
"totalTokenCount": 556
}
}
- 説明が帰ってきた
GCPにプロジェクトができている
APIキーはとりあえず指示通りに環境変数へ
vscode ➜ /workspaces/geminiApiQuickStart/app $ export API_KEY=....
サンプルコードをコピペしてmain関数に
main.go
package main
import (
"context"
"log"
"os"
"github.com/google/generative-ai-go/genai"
"google.golang.org/api/option"
)
func main() {
ctx := context.Background()
// Access your API key as an environment variable (see "Set up your API key" above)
client, err := genai.NewClient(ctx, option.WithAPIKey(os.Getenv("API_KEY")))
if err != nil {
log.Fatal(err)
}
defer client.Close()
}
パッケージが足りないようだったので追加でgo get
vscode ➜ /workspaces/geminiApiQuickStart/app $ go get github.com/google/generative-ai-go/genai
これだけでは何も起きないので、サンプルコードを追加で持ってきて挨拶。
main.go
func main() {
ctx := context.Background()
// Access your API key as an environment variable (see "Set up your API key" above)
client, err := genai.NewClient(ctx, option.WithAPIKey(os.Getenv("API_KEY")))
if err != nil {
log.Fatal(err)
}
defer client.Close()
model := client.GenerativeModel("gemini-1.5-flash")
resp, err := model.GenerateContent(ctx, genai.Text("こんにちは"))
if err != nil {
log.Fatal(err)
}
for _, cand := range resp.Candidates {
if cand.Content != nil {
for _, part := range cand.Content.Parts {
fmt.Println(part)
}
}
}
fmt.Println("---")
}
日本語での応答も確認
bash
vscode ➜ /workspaces/geminiApiQuickStart/app $ go run .
こんにちは! 何かお困りですか?
---
要素としてはシンプルに2つだけ
-
GenerativeModel
: Geminiモデルを指定してインスタンス生成 -
GenerateContent
: 一問一答形式で質問を渡して回答の生成
ストリームにしてみる
main.go
func main() {
ctx := context.Background()
// Access your API key as an environment variable (see "Set up your API key" above)
client, err := genai.NewClient(ctx, option.WithAPIKey(os.Getenv("API_KEY")))
if err != nil {
log.Fatal(err)
}
defer client.Close()
model := client.GenerativeModel("gemini-1.5-flash")
iter := model.GenerateContentStream(ctx, genai.Text("もし浦島太郎と金太郎が決闘したら...。3行で"))
for {
resp, err := iter.Next()
if err == iterator.Done {
break
}
if err != nil {
log.Fatal(err)
}
printResponse(resp)
}
}
func printResponse(resp *genai.GenerateContentResponse) {
for _, cand := range resp.Candidates {
if cand.Content != nil {
for _, part := range cand.Content.Parts {
fmt.Println(part)
}
}
}
fmt.Println("---")
}
生成を待たないのですぐに出力が始まる
vscode ➜ /workspaces/geminiApiQuickStart/app $ go run .
竜
---
宮城の技術と金太郎の怪力、どちらが勝つかは未知数
---
。しかし、金太郎の素朴さと浦島太郎の経験値の
---
差は、戦いを有利に進めるための大きなカギとなるだろう。果たして、どちらが勝利の栄光を手にするのか、その結果は誰も予想
---
できない。
---
このスクラップは5ヶ月前にクローズされました