0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

ChatGPT いろんな書き方で動かす

Posted at

gpt-3.5-turbogpt-3.5-turbo-0301はどちらを使えば良いのか?

gpt-3.5-turboを使いましょう
上位互換だと思ってください

公式のクイックスタートは現状gpt-3.5-turbo-0301を利用されているのでちょっと混乱しました

公式のchatgptを利用するためのmoduleはNodeとPythonで存在します。
これらを使わずともエンドポイントをPOSTで叩くことで利用可能です。

実装方法を見ていきます。


PythonからChatGPTを利用する

import openai
from dotenv import load_dotenv
import os

# .envファイルのパスを指定して環境変数をして読み込む
load_dotenv('.env')
OPENAI_API_KEY = os.getenv('OPENAI_API_KEY')

openai.api_key = OPENAI_API_KEY

res = openai.ChatCompletion.create(
    model="gpt-3.5-turbo",
    messages=[
        {
            "role": "system", # 役割
            "content": "日本語で返答してください。"
        },
        {
            "role": "user", # ユーザーからのメッセージ
            "content": "月はなぜ満ち欠けするのですか?"
        },
        {
		    "role": "assistant", # chatgptが返答したmessage
            "content": "chatgptからの返答?"
        },
        {
		    "role": "user",
            "content": "もう少し、簡潔に教えてください"
        },
    ],
)
print(res["choices"][0]["message"]["content"])

NodeからChatGPTを利用する

import { Configuration, OpenAIApi } from "openai";
import * as dotenv from "dotenv";
dotenv.config();

// API_KEYからインスタンスを作成
const configuration = new Configuration({
  apiKey: process.env.OPENAI_API_KEY,
});

// ChatGPTにアクセスするためのインスタンス作成
const openai = new OpenAIApi(configuration);

// APIを叩く
const res = await openai.createChatCompletion({
  model: "gpt-3.5-turbo",
  messages: [
        {
            role: "system", // 役割
            content: "日本語で返答してください。"
        },
        {
            role: "user", // ユーザーからのメッセージ
            content: "月はなぜ満ち欠けするのですか?"
        },
    ],
});

console.log(res.data.choices[0].message);

chat/completions endpointを利用する書き方

import * as dotenv from "dotenv";
dotenv.config();

const endpoint = "https://api.openai.com/v1/chat/completions";

// チャットの初期メッセージを定義
const messages = [
  {
    role: "system", //役割
    content: "hello",
  },
  {
    role: "user", // ユーザーからのメッセージ
    content: "マクドナルドの1番人気は?",
  },
];

const res = await fetch(endpoint, {
  method: "POST",
  headers: {
    "Content-Type": "application/json", // API_KEY
    Authorization: `Bearer ${process.env.OPENAI_API_KEY}`,
  },
  body: JSON.stringify({
    model: "gpt-3.5-turbo",
    messages: messages,
    max_tokens: 700,
  }),
});

const data = await res.json();

console.log(data.choices[0].message.content);

request objectでtry catchを見やすくする

import * as dotenv from "dotenv";
dotenv.config();

// チャットの初期メッセージを定義
const messages = [
  { role: "system", content: "hello" },
  { role: "user", content: "マクドナルドの1番人気は?" },
];

const RequestURI = "https://api.openai.com/v1/chat/completions";
const RequestOptions = {
  method: "POST",
  headers: {
    "Content-Type": "application/json", // API_KEY
    Authorization: `Bearer ${process.env.OPENAI_API_KEY}`,
  },
  body: JSON.stringify({
    model: "gpt-3.5-turbo",
    messages: messages,
    max_tokens: 700,
  }),
};

// Requestオブジェクト作成
const request = new Request(RequestURI, RequestOptions);

try {
  const res = await fetch(request);
  const data = await res.json();
  console.log(data.choices[0].message.content);
} catch (err) {
  console.log(err);
}

過去のmessageを踏まえて会話する

import { Configuration, OpenAIApi } from "openai";
import * as dotenv from "dotenv";
dotenv.config();

const configuration = new Configuration({
  apiKey: process.env.OPENAI_API_KEY,
});
const openai = new OpenAIApi(configuration);

const pastMessage = [{ role: "system", content: "日本語で返答してください。" }];

const chat = async (content) => {
  pastMessage.push({ role: "user", content });

  const res = await openai.createChatCompletion({
    model: "gpt-3.5-turbo",
    messages: pastMessage,
  });

  pastMessage.push(res.data.choices[0].message);

  console.log(res.data.choices[0].message.content);
};

await chat("日本で一番人気なアニメは?");
await chat("それが人気な理由は?");

終わりに

chatGPTには複数のModelが用意されており、チャット以外にも画像生成や音声会話用に最適化されたものも存在します。
主に使われているのは今回紹介したgpt-3.5-turboです。
gpt-3.5-turboだけに絞れば、公式ドキュメントで読むべき箇所もかなり少なく、覚えることもほとんどありません。

参考

0
1
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
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?