ChatGPT API ハック – EC営業AIの構築 – 本番運用のための実装

AI

リアルタイム応答でUXを改善

通常の ChatGPT API は「生成が全部終わってから」まとめて返します。でも stream: true を使うと、
ChatGPTが文を考えながら順次出力することができます。

from openai import OpenAI

openai_api_key = "xxx"
client = OpenAI(api_key=openai_api_key)

stream = client.chat.completions.create(
    model="gpt-4o",
    messages=[
        {"role": "system", "content": "あなたは薬局ECの営業アシスタントです。"},
        {"role": "user", "content": "こんにちは!この店のおすすめ商品を教えてください。"}
    ],
    stream=True  # ストリーミングモードをON
)

for chunk in stream:
    delta = chunk.choices[0].delta
    if delta and delta.content:
        print(delta.content, end="", flush=True)

print("\n--- 完了 ---")
こんにちは!当店のおすすめ商品をご紹介します。

1. **ビタミン剤サプリメント** - 身体の免疫力を高めるのに役立ちます。特にビタミンCやマルチビタミンは人気があります。

2. **プロバイオティクス** - 腸内環境を整えるためのサプリメントです。消化を助け、全体的な健康をサポートします。

3. **鎮痛剤** - 頭痛や筋肉痛に効果的なイブプロフェンやアセトアミノフェンなどの一般的な鎮痛剤も人気です。

4. **スキンケア商品** - 肌の保湿や美白をサポートするクリームやセラム。特に敏感肌用のものも用意しています。

5. **アレルギー対策商品** - アレルギーシーズンに向けた抗ヒスタミン剤などもおすすめです。

お客様のニーズに合わせた商品のご提案も可能ですので、お気軽にお問い合わせください!
--- 完了 ---

Function Callingの利用

ここからが 「答えるAI → 動くAI」 への進化です。OpenAIの Function Calling(関数呼び出し) を使えば、ChatGPTが「在庫確認」「CRM登録」「注文作成」などの処理を 自動でトリガー できます。

from openai import OpenAI
import json

openai_api_key = "xxx"
client = OpenAI(api_key=openai_api_key)

# AIが呼び出せる関数の定義
functions = [
    {
        "name": "check_inventory",
        "description": "指定された商品IDの在庫を確認します。",
        "parameters": {
            "type": "object",
            "properties": {
                "product_id": {"type": "string", "description": "在庫を確認したい商品のID"}
            },
            "required": ["product_id"]
        }
    },
    {
        "name": "add_customer_to_crm",
        "description": "顧客情報をCRMに登録します。",
        "parameters": {
            "type": "object",
            "properties": {
                "name": {"type": "string"},
                "email": {"type": "string"},
                "notes": {"type": "string"}
            },
            "required": ["name", "email"]
        }
    }
]

# AIとの会話
messages = [
    {"role": "system", "content": "あなたは薬局ECの営業AIアシスタントです。"},
    {"role": "user", "content": "Finasterideの商品在庫を確認してください。"}
]

# ChatGPTに関数呼び出しを許可して問い合わせ
response = client.chat.completions.create(
    model="gpt-4o",
    messages=messages,
    functions=functions
)

message = response.choices[0].message

# AIが関数を呼び出したい場合
if message.function_call:
    name = message.function_call.name
    args = json.loads(message.function_call.arguments)
    print(f"AIが関数 '{name}' を呼び出しました:")
    print(args)

    # --- ダミー関数で対応 ---
    if name == "check_inventory":
        result = {"product_id": args["product_id"], "stock": 12}
    elif name == "add_customer_to_crm":
        result = {"status": "success", "crm_id": "crm_789"}
    else:
        result = {"error": "unknown function"}

    # 結果をChatGPTに渡して続きの会話を生成
    follow_up = client.chat.completions.create(
        model="gpt-4o",
        messages=messages + [message, {"role": "function", "name": name, "content": json.dumps(result)}]
    )
    print("\n AIの最終応答:")
    print(follow_up.choices[0].message.content)
AIが関数 'check_inventory' を呼び出しました:
{'product_id': 'Finasteride'}

 AIの最終応答:
Finasterideの在庫は12個です。ほかにお手伝いできることはありますか?

多言語化対応

「日本語と英語のハイブリッド会話対応」は、実は gpt-4o モデルを使えば驚くほど簡単に実現できます。

from openai import OpenAI
import json

openai_api_key = "xxx"
client = OpenAI(api_key=openai_api_key)

messages = [
    {
        "role": "system",
        "content": (
            "あなたはバイリンガル営業アシスタントです。"
            "ユーザーの入力言語を自動的に検出し、同じ言語で自然に応答してください。"
            "日本語と英語が混ざっている場合は、両方の意味を汲み取り適切に答えてください。"
        )
    }
]

while True:
    user_input = input("👤: ")
    messages.append({"role": "user", "content": user_input})

    response = client.chat.completions.create(
        model="gpt-4o",
        messages=messages,
        temperature=0.7
    )

    ai_reply = response.choices[0].message.content
    print("🤖:", ai_reply)
    messages.append({"role": "assistant", "content": ai_reply})
👤: 乾燥肌にきく薬はある?
🤖: 乾燥肌に効果的な薬やスキンケア製品は色々ありますが、まずは保湿成分がしっかり入ったものを選ぶと良いでしょう。薬局で購入できるものであれば、ヒアルロン酸やセラミドが含まれた保湿クリームやローションがおすすめです。また、乾燥がひどい場合は皮膚科で処方される保湿剤を使用するのも一つの方法です。もし特定の製品についての情報が必要であればお知らせください。
👤: Do you have medicine for dry skin?
🤖: For dry skin, there are several over-the-counter products you can consider. Look for creams or lotions that contain moisturizing ingredients such as hyaluronic acid, ceramides, or glycerin. These ingredients help to lock in moisture and improve the skin's barrier function. If your dry skin is severe or persistent, it might be beneficial to consult a dermatologist, as they can prescribe stronger treatments or recommend specific products tailored to your skin needs. If you have any specific product inquiries or need further assistance, feel free to ask!

購買確度スコアをJSONで取得

いままでは「自然文で返すAI」でしたが、ここではChatGPTに構造化されたJSONを出させることで、
データベース・ダッシュボード・CRM連携が可能になります。

from openai import OpenAI
import json

openai_api_key = "xxx"
client = OpenAI(api_key=openai_api_key)

system_prompt = """
あなたは営業アシスタントAIです。
ユーザーとの会話を通じて、購買意欲を分析します。
出力は必ず以下のJSON形式で返してください:

{
  "ai_reply": "ユーザーへの自然な返答",
  "purchase_intent_score": 0.0〜1.0,
  "sentiment": "positive | neutral | negative",
  "recommended_action": "次に取るべき簡潔な営業アクション",
  "conversation_summary": "会話の要約"
}

分析基準:
- ユーザーが商品名や価格・購入方法を尋ねた場合、スコアを高くする。
- 検討中や迷いの発言は中間スコア。
- 否定的または関心が薄い場合は低スコア。
"""

messages = [{"role": "system", "content": system_prompt}]

print("💬 AI営業チャット開始(終了するには 'exit' と入力)")

while True:
    user_input = input("👤: ")
    if user_input.lower() in ["exit", "quit", "bye"]:
        print("👋 終了します。")
        break

    messages.append({"role": "user", "content": user_input})

    response = client.chat.completions.create(
        model="gpt-4o",
        temperature=0.3,
        response_format={"type": "json_object"},
        messages=messages
    )

    result = json.loads(response.choices[0].message.content)

    # AIの返答を表示
    print("\n🤖:", result["ai_reply"])
    print(f"🧠 購買意欲スコア: {result['purchase_intent_score']}")
    print(f"🙂 感情: {result['sentiment']}")
    print(f"🎯 推奨アクション: {result['recommended_action']}")
    print(f"📝 要約: {result['conversation_summary']}\n")

    # 会話履歴にAIの返答も追加
    messages.append({"role": "assistant", "content": result["ai_reply"]})
💬 AI営業チャット開始(終了するには 'exit' と入力)
👤: ニキビの薬はある?

🤖: はい、ニキビの薬についてお探しですね。具体的にどのようなタイプの薬をお探しですか?
🧠 購買意欲スコア: 0.6
🙂 感情: neutral
🎯 推奨アクション: ユーザーが求めている薬の詳細を確認し、適切な商品を提案する。
📝 要約: ユーザーはニキビの薬を探している。

👤: 軟膏はある?

🤖: はい、ニキビ用の軟膏もございます。具体的な商品名やご予算など、何かご希望はありますか?
🧠 購買意欲スコア: 0.7
🙂 感情: neutral
🎯 推奨アクション: 具体的な商品名や価格情報を提供し、ユーザーのニーズに合った商品を提案する。
📝 要約: ユーザーはニキビの薬を探しており、特に軟膏に興味を示している。

👤: どういうブランドがある?

🤖: ニキビ用の軟膏には、例えばプロアクティブ、オルビス、ロゼットなどのブランドがあります。それぞれ異なる成分や効果がありますので、どのような効果をお求めか教えていただければ、より詳しくご案内できます。
🧠 購買意欲スコア: 0.7
🙂 感情: neutral
🎯 推奨アクション: ユーザーのニーズに合ったブランドや商品の詳細を提供し、購入を促す。
📝 要約: ユーザーはニキビ用の軟膏を探しており、どのブランドがあるかを尋ねている。

👤: 1000円ぐらいである?

🤖: はい、1000円前後で購入できるニキビ用軟膏もあります。例えば、ロゼットの製品などがその価格帯に含まれます。具体的な商品についてご案内しましょうか?
🧠 購買意欲スコア: 0.8
🙂 感情: neutral
🎯 推奨アクション: 具体的な商品情報と購入リンクを提供する。
📝 要約: ユーザーはニキビ用の軟膏を探しており、1000円程度の価格帯を希望している。ブランドについても興味を示している。

👤: よさそうだね。それ買おうかな

🤖: ありがとうございます。ロゼットのニキビ用軟膏について詳しい情報をお送りしましょうか?購入方法もご案内できます。
🧠 購買意欲スコア: 0.8
🙂 感情: positive
🎯 推奨アクション: 商品の詳細情報と購入方法を案内する。
📝 要約: ユーザーはニキビ用の軟膏を探しており、1000円程度で購入可能なロゼットの製品に興味を示している。購入を検討している様子。

関連記事

カテゴリー

アーカイブ

Lang »