LoginSignup
6
3

More than 1 year has passed since last update.

ChatGPT+FastAPIによる簡易問い合わせAPI 作成

Posted at
  • ChatGPTとFastAPIを使って簡単な問い合わせAPIを作成したのでメモする。

事前準備

  • ChatGPT APIキー取得

    • OpenAIアカウントを作成し、APIキーを取得する
  • Python OpenAI、FastAPI系ライブラリをインストールする

    pip install openai fastapi uvicorn
    

コード

  • main.py

    リクエストボディに指定された質問文をChatGPTライブラリに渡し、回答をレスポンスとして返却する

    from pydantic import BaseModel
    from fastapi import FastAPI
    import openai
    
    openai.api_key = "{取得したAPIキーをセットする}"
    
    app = FastAPI()
    
    
    # リクエストボディ定義
    class Question(BaseModel):
        content: str
    
    
    
    @app.post("/question")
    def question(question: Question):
        response = openai.ChatCompletion.create(
            model="gpt-3.5-turbo",
            messages=[
                {"role": "user", "content": question.content},
            ],
        )
        return {"answer": response.choices[0]["message"]["content"].strip()}
    
    

動作確認

  • API起動

    uvicorn main:app --reload --port 8091
    
  • リクエスト

    POST /question HTTP/1.1
    Host: localhost:8091
    Content-Type: application/json
    Content-Length: 39
    
    {
        "content":"メジャーリーグは何チームありますか"
    }
    
  • レスポンス

    {
        "answer": "現在、メジャーリーグには30チームあります。15チームがアメリカンリーグに属し、残りの15チームがナショナルリーグに属しています。"
    }
    

参考情報

6
3
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
6
3