Gemini APIを触ってみる会
はじめに
Googleの生成AIであるGeminiのAPIを触ってみる会
とりあえず触る
とりあえず触るためにはAPIキーが必要になるので、まずはGoogle AI Studioを開く。
つぎに左上にある「Get API key」を押す。
「キー APIキーを作成」を押すことで作成できる。
作成したキーはどこかにメモしておいてください。
次に取得したAPI keyを使ってGeminiのAPIを使ってみます。
クイックスタートガイドにあるコードをそのままでGEMINI_API_KEYの部分を取得したキーに置き換えて実行してみてください。
curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-1.5-flash:generateContent?key=GEMINI_API_KEY" \
-H 'Content-Type: application/json' \
-X POST \
-d '{
"contents": [{
"parts":[{"text": "Explain how AI works"}]
}]
}'
次のような内容が返ってきたら成功です。
{
"candidates": [
{
"content": {
"parts": [
{
"text": "Artificial intelligence (AI) is a broad field encompassing various techniques that enable computers to mimic human intelligence. There's no single \"how it works\" answer, as different AI approaches use different methods. However, we can break down the core concepts:\n\n**1. Data is King:** AI systems learn from data. The more relevant and high-quality data you feed an AI, the better it will perform. This data can be anything from images and text to sensor readings and financial transactions.\n\n**2. Algorithms are the Recipe:** Algorithms are sets of instructions that tell the computer how to process the data. These algorithms are designed to extract patterns, make predictions, or solve problems. Different AI tasks use different algorithms.\n\n**3. Learning from Data:** A crucial aspect of many AI systems is their ability to learn from data without explicit programming. This is often achieved through several approaches:\n\n* **Machine Learning (ML):** This involves algorithms that allow the system to identify patterns and build models from data without being explicitly programmed for each specific task. Instead, they learn from examples. Common types of machine learning include:\n * **Supervised Learning:** The algorithm is trained on labeled data (data where the correct answer is already known). For example, showing an AI thousands of images of cats and dogs, each labeled accordingly, to teach it to distinguish between them.\n * **Unsupervised Learning:** The algorithm is trained on unlabeled data and tasked with finding structure or patterns within the data. For example, grouping similar customers together based on their purchasing history.\n * **Reinforcement Learning:** The algorithm learns through trial and error, receiving rewards for correct actions and penalties for incorrect ones. This is commonly used in robotics and game playing.\n\n* **Deep Learning (DL):** A subset of machine learning that uses artificial neural networks with multiple layers (hence \"deep\"). These networks are inspired by the structure and function of the human brain and are particularly effective at processing complex data like images, audio, and text. Deep learning powers many advanced AI applications like image recognition, natural language processing, and self-driving cars.\n\n**4. Representation and Reasoning:** AI systems need to represent knowledge and reason with it. This can involve:\n\n* **Knowledge Representation:** Storing and organizing information in a way that the computer can understand and use.\n* **Reasoning:** Using the stored knowledge to draw conclusions, solve problems, and make decisions. This can involve logical deduction, probabilistic reasoning, or other techniques.\n\n**5. Evaluation and Improvement:** AI systems are continuously evaluated to measure their performance. This allows developers to identify areas for improvement and refine the algorithms and data used.\n\n**In simpler terms:** Imagine teaching a dog a trick. You show the dog (the AI) examples (the data) of the trick, reward it when it gets it right (reinforcement learning), and correct it when it's wrong. Over time, the dog learns the trick without you explicitly explaining every step. AI works similarly, but instead of a dog, it's a computer program, and instead of tricks, it's complex tasks.\n\nIt's important to note that AI is constantly evolving, and new techniques and approaches are continuously being developed. This explanation provides a general overview, and the specifics can vary greatly depending on the particular AI system.\n"
}
],
"role": "model"
},
"finishReason": "STOP",
"avgLogprobs": -0.22412655432674963
}
],
"usageMetadata": {
"promptTokenCount": 4,
"candidatesTokenCount": 693,
"totalTokenCount": 697
},
"modelVersion": "gemini-1.5-flash"
}
PHPで触ってみる
Gemini APIのチュートリアルにはPHPはないですが、packagistで探して今回はこちらを使って触ってみます。
おそらく公式パッケージではないと思います。
まずはパッケージのインストール
composer require google-gemini-php/client
途中で次のようなメッセージがでますが、今回は無効でいきます。
Do you trust "php-http/discovery" to execute code and wish to enable it now?
そのあとでguzzlehttp/guzzleを入れておきます。
composer require guzzlehttp/guzzle
適当に作成したサンプルコード、実行する時は$apiKey
に作成したAPI keyを設定してください。
<?php
require_once './vendor/autoload.php';
$apiKey = 'your-api-key';
$client = Gemini::client($apiKey);
$result = $client->geminiFlash()->generateContent('なんかやる気が出る一言を言ってください');
echo $result->text() . PHP_EOL;
実行してみると、次のような内容が返ってきましたね。(日本語に対応していた。)
% php api.php
大丈夫、なんとかなる!
会話できるような感じを試してみる。
generateContentからstartChatに変えることで会話履歴を保持してくれる。
(無料枠で無限は厳しいから3回くらいのやり取りできるようにしてみた。)
<?php
require_once './vendor/autoload.php';
$apiKey = 'your-api-key';
$client = Gemini::client($apiKey);
$chat = $client->geminiFlash()->startChat([]);
for ($i = 0; $i < 3; $i++) {
$text = readline('You: ');
$result = $chat->sendMessage($text);
echo $result->text() . PHP_EOL;
}
実行してみると、なんか会話ができた感じになった。
% php chat.php
You: なんかやる気が出る一言を言ってください
大丈夫、できるよ。一歩ずつ進もう。
You: いや、二歩くらい下がりそうだよ、困ったな
二歩下がったっていいんです。そこからまた、自分のペースで一歩ずつ、前へ進めばいい。 大切なのは、止まらないこと。どんなに小さな一歩でも構いません。 あなたは、すでに十分頑張っていますよ。
You: ありがとう、いまので三歩くらい進んだよ
素晴らしい! その調子で、自分のペースで進んでいきましょう! 応援しています!
会話の履歴は$chat->history
配列に入っているから出力すれば全部出てくる。
ためしに上の会話を出してみるとこんな感じだった。(長いので閉じた、みたい人は開いてみてください。)
会話履歴
Array
(
[0] => Gemini\Data\Content Object
(
[parts] => Array
(
[0] => Gemini\Data\Part Object
(
[text] => なんかやる気が出る一言を言ってください
[inlineData] =>
)
)
[role] => Gemini\Enums\Role Enum:string
(
[name] => USER
[value] => user
)
)
[1] => Gemini\Data\Content Object
(
[parts] => Array
(
[0] => Gemini\Data\Part Object
(
[text] => 大丈夫、できるよ。一歩ずつ進もう。
[inlineData] =>
)
)
[role] => Gemini\Enums\Role Enum:string
(
[name] => MODEL
[value] => model
)
)
[2] => Gemini\Data\Content Object
(
[parts] => Array
(
[0] => Gemini\Data\Part Object
(
[text] => いや、二歩くらい下がりそうだよ、困ったな
[inlineData] =>
)
)
[role] => Gemini\Enums\Role Enum:string
(
[name] => USER
[value] => user
)
)
[3] => Gemini\Data\Content Object
(
[parts] => Array
(
[0] => Gemini\Data\Part Object
(
[text] => 二歩下がったっていいんです。そこからまた、自分のペースで一歩ずつ、前へ進めばいい。 大切なのは、止まらないこと。どんなに小さな一歩でも構いません。 あなたは、すでに十分頑張っていますよ。
[inlineData] =>
)
)
[role] => Gemini\Enums\Role Enum:string
(
[name] => MODEL
[value] => model
)
)
[4] => Gemini\Data\Content Object
(
[parts] => Array
(
[0] => Gemini\Data\Part Object
(
[text] => ありがとう、いまので三歩くらい進んだよ
[inlineData] =>
)
)
[role] => Gemini\Enums\Role Enum:string
(
[name] => USER
[value] => user
)
)
[5] => Gemini\Data\Content Object
(
[parts] => Array
(
[0] => Gemini\Data\Part Object
(
[text] => 素晴らしい! その調子で、自分のペースで進んでいきましょう! 応援しています!
[inlineData] =>
)
)
[role] => Gemini\Enums\Role Enum:string
(
[name] => MODEL
[value] => model
)
)
)
まとめ
Gemini APIをとりあえず触ってみました。
さらにPHPを使って簡単な会話を行う方法も実装もやってみました。
思ったより簡単に使えましたが、無料枠なのでご利用はほどほどにしておく必要がありますね。
Discussion