WolframGPT: 両方の長所

Mar 03 2023
ChatGPTとWolfram Alphaを組み合わせて、より正確な計算結果を取得します。
はじめに ChatGPT 自体は、計算を実行したり、数値の答えを返したりするのがそれほど得意ではありません。毎回異なる答えが得られるだけでなく、数字をでっち上げ、説得力のある方法で表現することもできます。
出典: https://writings.stephenwolfram.com/2023/01/wolframalpha-as-the-way-to-bring-computational-knowledge-superpowers-to-chatgpt/

序章

ChatGPT 自体は、計算を実行したり、数値の答えを返したりするのがそれほど得意ではありません。毎回異なる答えが得られるだけでなく、数字をでっち上げ、説得力のある方法で表現することもできます。それを修正する方法があることはわかっていて、解決策を見つけようと決心しました。

このブログ投稿では、ChatGPT と Wolfram Alpha の両方の力を組み合わせて、より包括的でインテリジェントな会話エクスペリエンスを提供するチャットボットを Python で構築する方法を検討します。

OpenAI を利用した ChatGPT は、自然言語処理を使用してユーザー入力に対して人間のような応答を生成できる大規模な言語モデルです。幅広いデータ ソースでトレーニングでき、ほぼすべてのクエリに対する応答を生成できます。一方、Wolfram Alphaはさまざまな領域の問題を解決できる計算知識エンジンですが、特に数学と科学の問題を解決できることで知られています。

これら 2 つの強力なツールを統合することで、幅広いユーザーのクエリに対して信頼性が高くインテリジェントな応答を提供できるチャットボットを作成できます。

API情報

2023 年 3 月 1 日に、OpenAI はChatGPT APIをリリースしました。これは私にこのプロジェクトを推進する絶好の機会を提供してくれました。実際、私は数週間前に GPT-3 API を使用してこのプロジェクトに取り組んでいましたが、その応答は ChatGPT API の応答ほど人間らしくありませんでした。ChatGPT API を使用すると、プロンプト エンジニアリングも容易になります。これについては、この記事の後半で説明します。

言い忘れていましたが、OpenAI にはHTTP リクエストの代替手段を提供するPython ライブラリがあります。このプロジェクトでは Python ライブラリを使用しましたが、HTTP リクエストを使用した場合でもこのプロジェクトは同じように機能すると思います。

Wolfram AlphaにはショートアンサーAPIがあり,Wolfram Alphaから直接単一のプレーンテキストの結果を返します。独自の自然言語処理を備えており、ユーザーは計算を伴うクエリを渡し、プレーン テキストで回答を得ることができます。これは、ChatGPT の API と統合して、より優れたユーザー エクスペリエンスを提供する、より包括的なチャットボットを実現するのに最適な API のように思えました。

チャットボット

このチャットボットは、ユーザー入力を受け取り、それを処理のために ChatGPT に直接渡すことによって機能します。ユーザーが計算、事実に関する質問、または分析的な質問を入力したとChatGPTが判断した場合、その質問はWolfram AlphaのShort Answers APIに渡され、応答が返されます。他のすべてのクエリは通常どおり ChatGPT によって処理され、応答されます。

このチャットボットを構築する最初のステップは、API キーを取得して入力して各 API を初期化することです。これらを環境変数として作成する必要があることはわかっていますが、環境変数を機能させることができなかったので、API キーを含む別の Python ファイルを作成し、メイン プログラムで呼び出しました。

import requests
import wolframalpha
import openai
import re
from APIKeys import WOLFRAM_APP_ID, OPENAI_API_KEY

# Wolfram Alpha credentials
client = wolframalpha.Client(WOLFRAM_APP_ID)

# OpenAI credentials
openai.api_key = OPENAI_API_KEY

この関数では、この記事の執筆時点で OpenAI の最も高度な言語モデルである に設定されたopenai.ChatCompletion.create()メソッドとパラメータを使用して、ユーザーの入力を ChatGPT API に送信します。また、ランダムな応答の生成を少なくするために、温度を 0.2 に設定しました。また、生成される応答の長さを制限するために、パラメーターを 256 に設定します。最後に、生成された応答テキストを返します。これらのパラメーターがどのように機能するかについて詳しくは、API リファレンス ドキュメントを参照してください。enginegpt-3.5-turbomax_tokens

ChatGPT API では、ユーザーがプロンプトを入力する前にモデルに指示できるため、以下のプロンプトを使用してモデルを準備しました。

あなたは役に立つアシスタントです。ただし,Wolfram Alphaが合理的に答えられるような計算や純粋に事実や分析的な質問に対する答えを求められた場合は,代わりにWolfram Alphaが理解できるクエリを出力することでWolfram Alphaに委任してください。このシナリオを示すには、次のように出力をフォーマットします: WolframAlpha のクエリ: <query>

ユーザーがクエリを入力し、ChatGPT が結果を返すと、応答が抽出され、 という変数に格納されますchatGPTresponse. 。 ここで魔法が起こります。ChatGPTが「Query for WolframAlpha:」で始まる応答を返した場合、それは に渡されます。処理用のWolfram Alpha Short Answers API。それ以外の場合、関数は ChatGPT の応答を返すだけです。

この関数のコードは次のとおりです。

# This function processes user input through the ChatGPT API
def GPTQuery(myInput):
    completion = openai.ChatCompletion.create(
        model="gpt-3.5-turbo",
        temperature=0.2,   # Lower temperature values make the output less random
        max_tokens=256,
        # Instruct the model on how to process certain inputs:
        messages=[
            {"role": "system", "content": "You are a helpful assistant. However, if you're asked to provide an answer "
                                          "to a calculation or purely factual or analytical question that could "
                                          "reasonably be answered by Wolfram Alpha, delegate to Wolfram Alpha instead "
                                          "by outputting a query that Wolfram Alpha would understand. Indicate this "
                                          "scenario by formatting the output exactly like this: Query for "
                                          "WolframAlpha: <query>"},
            {"role": "user", "content": myInput},
        ]

    )

    chatGPTresponse = completion.choices[0].message.content

    # Checks to see if ChatGPT's response needs to be passed to Wolfram Alpha
    if "Query for WolframAlpha:" in chatGPTresponse:
        properWolframQuery = chatGPTresponse.replace("Query for WolframAlpha:", "")
        return wolframQuery(properWolframQuery)
    # If not, return ChatGPT's response
    else:
        return chatGPTresponse


この関数のコードは次のとおりです。

# This function processes queries through the Wolfram Alpha Short Answers API
def wolframQuery(userInput):
    # Define the API endpoint URL and the query parameters
    api_url = "https://api.wolframalpha.com/v1/spoken"
    params = {
        "appid": WOLFRAM_APP_ID,
        "i": userInput
    }
    # Send the HTTP request to the API endpoint
    response = requests.get(api_url, params=params)
    # Check if the request was successful (i.e., HTTP status code 200)
    if response.status_code == 200:
        # Print the short answer returned by the API
        return f"According to Wolfram Alpha, {response.text}"
    else:
        # Print the error message returned by the API
        return f"Error: {response.text}"

この関数のコードは次のとおりです。

def chatbot():
    while True:
        prompt = input("You: ")
        promptNew = prompt.lower()

        # Allows the user to override ChatGPT processing and process through Wolfram Alpha if a basic calculation is
        # entered or the user adds the word "wolfram" to their query
        if re.search(r"(\d+[\+\-\*\/])+\d+", promptNew) or "wolfram" in promptNew:
            result = wolframQuery(promptNew)
            print(result)

        else:
            myResponse = GPTQuery(promptNew)
            print(f"ChatGPT: {myResponse}")

このプロジェクトは、私の GitHubここにあります。以下は私がテストしたときの反応の一部です。

You: How far is it from Los Angeles to Detroit?
ChatGPT: According to Wolfram Alpha, The distance from the center of Los Angeles, California to the center of Detroit, Michigan is about 1990 miles
You: What is a pizza made of?
ChatGPT: A pizza is typically made of dough, tomato sauce, cheese, and various toppings such as meats, vegetables, and herbs.
You: what is 848 plus 39993
ChatGPT: According to Wolfram Alpha, 848 plus 39993 is 40841
You: what time is it in london?
ChatGPT: According to Wolfram Alpha, The current time in London, Greater London, United Kingdom, is 2:22:44 A.M. Greenwich Mean Time, Friday, March 3, 2023

この記事を読んで楽しんでいただければ幸いです。これは私の最初の記事ですが、より多くのサイドプロジェクトに取り組みながら、さらに書くことになると思います。私はこのプロジェクトに取り組み続け、最終的には公開ウェブサイトとして利用できるようにするつもりです。また、物理学や工学の問題など、より複雑なユーザー入力を処理できるようにこのプログラムを開発したいと考えています。