박주니 개발 정리

openai api 이용해서 input값에서 의도한 값 추출하는 방법 본문

AI

openai api 이용해서 input값에서 의도한 값 추출하는 방법

박주니 2024. 6. 26. 15:10
728x90
반응형

먼저 openai api key를 가지고 있어야합니다. 

https://platform.openai.com/playground

 

1. .env에 OPENAI_API_KEY 값을 셋팅합니다. 

OPENAI_API_KEY='{{openai api key value}}'

 

2. 현재 이 코드를 복사해서 붙여놓습니다. 

app.post("/extract-name", async (req, res) => {
  const { text } = req.body;

  if (!text) {
    return res.status(400).json({ error: "Text is required" });
  }

  try {
    const query = "텍스트에서 이름을 추출해줘";

    const response = await axios.post(
      "https://api.openai.com/v1/chat/completions",
      {
        model: "gpt-3.5-turbo",
        messages: [
          { role: "system", content: "You are a helpful assistant." },
          { role: "user", content: query },
          { role: "user", content: text },
        ],
      },
      {
        headers: {
          Authorization: `Bearer ${process.env.OPENAI_API_KEY}`,
          "Content-Type": "application/json",
        },
      }
    );

    // 응답에서 이름만 추출
    const responseText = response.data.choices[0].message.content.trim();

    // 이름만 추출하는 정규 표현식 사용
    const nameMatch = responseText.match(/"([^"]+)"/);
    const extractedName = nameMatch ? nameMatch[1] : null;

    if (extractedName) {
      res.json({ extracted_name: extractedName });
    } else {
      res.status(400).json({ error: "Name not found in the text" });
    }
  } catch (error) {
    console.error(error);
    res
      .status(500)
      .json({ error: "An error occurred while processing your request" });
  }
});

추가 설명

이 코드는 예를 들어서 "내 이름은 홍길동이야"라고 text를 넣으면 gpt가 홍길동을 이름으로 인식해서 따로 뺄 수 있습니다. 

input값은 내 이름은 이라고 시작할 수도 있지만 나는이라는 text부터 시작할수도 여러 경우의 수를 조건식을 걸 수도 없고 

위험요소가 있는데 이 부분을 gpt가 query에 텍스트에서 이름을 추출해줘라고 학습을 했기 때문에 최대한 이 문장에서 이름을 가지고 올 것입니다. 

 

응용 방법

현재는 이름을 기준으로 query에 텍스트에서 이름을 추출해줘라고 했지만 주소 및 전화번호등 여러 요소를 구분해서 활용할 수 있습니다. 

 

 

728x90
반응형
Comments