サンプル集  >  React  >  チャットでOpenAIを使う
チャットでOpenAIを使う
2025/11/30

チャットアプリを作ってみます。

openaiをインストールします。

npm install openai

以下のコマンドでプロジェクトを作成します。

npm create vite@latest

コマンドプロンプトでコマンドを実行します。

>npm create vite@latest

> npx
> create-vite

|
o  Project name:
|  chat-for-openai
|
o  Select a framework:
|  React
|
o  Select a variant:
|  JavaScript
|
o  Use rolldown-vite (Experimental)?:
|  No
|
o  Install with npm and start now?
|  Yes
|
o  Scaffolding project in C:\...\simple-chat...
|
o  Installing dependencies with npm...

added 157 packages, and audited 158 packages in 9s

33 packages are looking for funding
  run `npm fund` for details

found 0 vulnerabilities
|
o  Starting dev server...

> simple-chat@0.0.0 dev
> vite


  VITE v7.2.4  ready in 755 ms

    Local:   http://localhost:5173/
    Network: use --host to expose
    press h + enter to show help

ファイルを2追加します。 main.jsxは生成されたままです。

src/
  App.jsx
  main.jsx
.env

全体を制御するjsxです。

App.jsx
 1: 
 2: 
 3: 
 4: 
 5: 
 6: 
 7: 
 8: 
 9: 
10: 
11: 
12: 
13: 
14: 
15: 
16: 
17: 
18: 
19: 
20: 
21: 
22: 
23: 
24: 
25: 
26: 
27: 
28: 
29: 
30: 
31: 
32: 
33: 
34: 
35: 
36: 
37: 
38: 
39: 
40: 
41: 
42: 
43: 
44: 
45: 
46: 
47: 
48: 
49: 
50: 
51: 
52: 
53: 
54: 
55: 
56: 
57: 
58: 
59: 
60: 
61: 
62: 
63: 
64: 
65: 
66: 
67: 
68: 
69: 
import { useState } from "react";
import OpenAI from "openai";

const client = new OpenAI({
  apiKey: import.meta.env.VITE_OPENAI_API_KEY,
  dangerouslyAllowBrowser: true,
});

export default function App() {
  const [messages, setMessages] = useState([]);
  const [input, setInput] = useState("");

  const sendMessage = async () => {
    if (!input.trim()) return;

    // ユーザーメッセージを追加
    const userMsg = { role: "user", content: input };
    setMessages((prev) => [...prev, userMsg]);

    setInput("");

    // OpenAI に問い合わせ
    const res = await client.chat.completions.create({
      model: "gpt-4.1-mini",
      messages: [...messages, userMsg],
    });

    const reply = res.choices[0].message.content;

    // アシスタントメッセージを追加
    const assistantMsg = { role: "assistant", content: reply };
    setMessages((prev) => [...prev, assistantMsg]);
  };

  return (
    <div style={{ padding: 20, maxWidth: 600 }}>
      <h1>Chat</h1>

      <div
        style={{
          border: "1px solid #ccc",
          padding: 10,
          minHeight: 300,
          marginBottom: 20,
        }}
      >
        {messages.map((m, i) => (
          <div key={i} style={{ marginBottom: 10 }}>
            <strong>{m.role === "user"
                     ? "あなた" : "AI"}:</strong>
            <div>{m.content}</div>
          </div>
        ))}
      </div>

      <input
        style={{ width: "80%", padding: 8 }}
        value={input}
        onChange={(e) => setInput(e.target.value)}
        onKeyDown={(e) => e.key === "Enter" && sendMessage()}
        placeholder="メッセージを入力..."
      />
      <button style={{ padding: 8, marginLeft: 10 }}
              onClick={sendMessage}>
        送信
      </button>
    </div>
  );
}

OpenAIのAPI Keyを指定します。 ダブルクォートは不要とのことです。

.env
1: 
VITE_OPENAI_API_KEY=...

ブラウザでコマンドプロンプトに表示されているURLにアクセスしてみます。


メッセージ欄にあなたは誰ですか?と入力して送信ボタンを押します。


AIからの返答が表示されました!

▲ PageTop  ■ Home


Copyright (C) 2025 ymlib.com