Warning: The magic method InvisibleReCaptcha\MchLib\Plugin\MchBasePublicPlugin::__wakeup() must have public visibility in /home/c8376374/public_html/carefreefeather.com/wp-content/plugins/invisible-recaptcha/includes/plugin/MchBasePublicPlugin.php on line 37
OpenAIとReactを使用したテキストリライトの実装 | きままにいろいろ

OpenAIとReactを使用したテキストリライトの実装

React

はじめに

テキストリライトは、オリジナルのテキストを新しい形に変換するプロセスです。この記事では、OpenAIとReactを使用してこの機能を実装する方法について詳しく解説します。

コードの概要

以下のコードスニペットは、テキストのリライトを行うためのサーバーサイドとクライアントサイドの実装を示しています。

サーバーサイドの実装

1. モジュールのインポート

import axios from 'axios';

2. 関数 rewriteText の定義

const rewriteText = async (req, res) => {
  if (req.method !== 'POST') {
    return res.status(405).end();
  }

  const text = req.body.text;

  const prompt = `
    以下の文章を日本語でリライトしてください。
    ${text}
  `;

  try {
    const response = await axios.post(
        'https://api.openai.com/v1/chat/completions',
        {
            model: 'gpt-4',
            messages: [
              { role: 'system', content: 'リライトのシステムメッセージ' },
              { role: 'user', content: prompt }
            ],
            temperature: 0.25,
          },
        {
          headers: {
            'Content-Type': 'application/json',
            Authorization: `Bearer ${process.env.OPENAI_API_KEY}`,
          },
        }
      );

    const rewrittenText = response.data.choices[0].message.content;

    res.status(200).json({ text: rewrittenText });
  } catch (error) {
    res.status(500).json({ error: 'An error occurred while rewriting the text.' });
  }
};

export default rewriteText;

この部分は、テキストのリライトを行うサーバーサイドの関数です。OpenAIのAPIを呼び出して、テキストをリライトします。

クライアントサイドの実装

1. モジュールのインポート

import { useState } from 'react';
import ClickableCopyText from "../components/ClickableCopyText";
import { Box,Button, TextareaAutosize, Container, Typography } from '@mui/material';

2. コンポーネント Home の定義

const Home = () => {
  const [input, setInput] = useState('');
  const [output, setOutput] = useState('');
  const [download, setDownload] = useState("");

  const handleDownload = async () => {
    setDownload('data:text/plain;charset=utf-8,' + encodeURIComponent(output));
  }

  const handleRewrite = async () => {
    try {
      const response = await axios.post('/api/rewrite', { text: input });
      setOutput(response.data.text);
    } catch (error) {
      // エラー処理
    }
  };

  return (
    <Container>
      <Typography variant="h4">テキストリライト</Typography>
      <TextareaAutosize style={{ width: '100%' }} minRows={5} onChange={(e) => setInput(e.target.value)} value={input} />
      <Button variant="contained" color="primary" onClick={handleRewrite}>リライト</Button>
      <p>アウトプットテキスト</p>
      <Box display="flex" alignItems="center">
        <ClickableCopyText copyText={output} />
      </Box>
      <p><a href={download} download="download.txt" onClick={handleDownload}>テキストダウンロード</a></p>
    </Container>
  );
};

export default Home;

この部分は、テキストリライト機能を提供するReactコンポーネントです。テキストエリア、リライトボタン、出力テキストの表示セクション、ファイルとしての出力テキストのダウンロードリンクをレンダリングします。

まとめ

このコードスニペットは、OpenAIとReactを使用してテキストリライト機能を実装する方法を示しています。この機能は、コンテンツ作成、マーケティング、教育など、さまざまなアプリケーションで役立つ可能性があります。

コメント

タイトルとURLをコピーしました