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?

OpenAI APIで「記憶機能付き」簡単なAIエージェントを作ってみよう

Posted at

0. 入る前に

OpenAIのAPIを使って自分だけの会話型AIエージェントを作ることです。
この記事では、シンプルなPythonスクリプトを使って、過去の会話を記憶する(=メモリ機能付き)超簡単なAIエージェントを実装してみます。

1. 事前準備

OpenAI APIを利用するためには、まず APIキー が必要です。
プロジェクトのルートに .env ファイルを作成して以下のように記述します

.env
OPENAI_API_KEY={自分のapi_keyを記入}

2. コードの全体構造

main.ipynb
import openai

client = openai.OpenAI()
messages = []

def call_ai():
    response = client.chat.completions.create(
        model="gpt-4o-mini",messages=messages,
    )
    message = response.choices[0].message.content
    messages.append({"role": "assistant","content":message})
    print(f"AI: {message}")

while True:
    message = input("Send a message to the LLM...")
    if message == "quit" or message == "q":
        break
    else:
        messages.append({
            "role":"user",
            "content":message
        })
        print(f"User: {message}")
        call_ai()
        

今回作成するプログラムの流れは次のとおりです。
1. OpenAIクライアントを初期化
2. ユーザーとAIの会話を messages リストに保存
3. ユーザー入力を受け取り、AIに送信
4. AIの返答を受け取り、また messages に追加

つまり、この messages が会話の履歴を保持するため、これ自体が「メモリ機能 になります。

3. コードの全体構造

main.ipynb
import openai

# OpenAIクライアントの作成
client = openai.OpenAI()

# 会話履歴を保持するリスト
messages = []

client はOpenAIのAPIリクエストを処理するオブジェクトです。
messages にはユーザーとAIのやり取りを以下のように順番に記録します:

[
  {"role": "user", "content": "こんにちは!"},
  {"role": "assistant", "content": "こんにちは!お元気ですか?"},
  {"role": "user", "content": "今日の天気はどう?"},
  ...
]

4. AIを呼び出す関数を作成

main.ipynb
def call_ai():
    response = client.chat.completions.create(
        model="gpt-4o-mini",
        messages=messages,
    )
    message = response.choices[0].message.content
    messages.append({"role": "assistant", "content": message})
    print(f"AI: {message}")

ここでのポイントは client.chat.completions.create()
client.chat.completions.create() とは、OpenAIのチャットモデルを呼び出してAIの返答を生成するための中核的な関数です。

model="gpt-4o-mini"
ここでは、使用するAIモデルの種類を指定します。
messages=messages
この引数は、AIが会話の文脈(コンテキスト)を理解するための履歴情報を渡します。
保持情報例
messages = [
  {"role": "system", "content": "あなたは親切なAIアシスタントです。"},
  {"role": "user", "content": "こんにちは!"},
  {"role": "assistant", "content": "こんにちは!お元気ですか?"},
  {"role": "user", "content": "明日の天気は?"},
]

このメソッドは、これまでの会話履歴 (messages) をすべて考慮して次の回答を生成します。
そのため、AIは「前回の話を覚えている」ような自然な応答ができます。

5. ユーザー入力ループ

while True:
    message = input("Send a message to the LLM... ")
    if message == "quit" or message == "q":
        break
    else:
        messages.append({"role": "user", "content": message})
        print(f"User: {message}")
        call_ai()

この部分では、ユーザーがコンソール上でAIと自由に会話できます。
quit または q を入力すると終了します。

入力するたびに messages に新しい会話が追加され、
それをAIに渡して応答を得ることで、会話の文脈を維持することができます。

6. 実際会話してみよ

1回目
User: my name is jung!
AI: Nice to meet you, Jung! How can I assist you today?

2回目
User: what is my name?
AI: Your name is Jung! How can I help you further? -> 名前を覚えている

3回目
User: im from korea
AI: That's great, Jung! Korea has a rich culture and history. Are there any specific aspects of Korea you'd like to discuss or any questions you have?

4回目
User: what was the first question i asked you?
AI: The first question you asked me was, "what is my name?"

5回目
User: what is the closest island country to where i was born?
AI: Since you're from Korea, the closest island country would be Japan. The Sea of Japan (East Sea) separates the two countries, and they are relatively close, with some islands like Tsushima located just off the coast of Korea. If you have a specific region in Korea in mind, please let me know! 
↑ 覚えている情報を元に回答をしている
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?