여러 블로그를 찾아보니 나와 같은 문제를 가진 사람이 많았다.
OpentAI API request error : You exceeded your current quota, please check your plan and billing details
My key got the above error but when I created a new key the problem was solved. But I want my old key to work .
community.openai.com
결론, api 쓰기 위해서 카드를 등록해서 써야한다. 무료로 쓰는 방법도 있다고 하지만 복불복인건지..
화살표가 가리키는 곳에서 카드 등록하면된다.
카드 등록을 완료했다면 API Key 발급 받은 것은 삭제하고 새로운 Key를 발급 받자! 발급 안 받고 그대로 하면 안된다고 하니 시간 낭비하지 말자!
발급 받은 새로운 key값은 OpenAIServlet의 doPost Method에 넣어준다.
그리고 다양한 Model이 있다. 아래 사이트에 들어가면 다양한 모델들을 확인할 수 있다. 우리는 모델을 사용할때
createPostRequest Method 안에 String url 부분에 적으면 된다.
String url = "https://api.openai.com/v1/engines/text-davinci-003/completions"; //text-davinci-003 모델
//gpt-4의 경우 endpoint가 /vi/chat/completions 인데 아직 gpt-4는 해결하지 못한 상태입니다.
String url = "https://api.openai.com/v1/engines/gpt-4/completions"; //gpt-4 모델
위에 url 규칙을 보고 어떤 모델을 쓰는지에 따라 endPoint도 다르다. 아래 문서를 보면 어떻게 수정해야하는지 알 수 있을 것이다.
//endPoint 별로 사용 가능한 모델이 다르다.
/v1/chat/completions: gpt-4, gpt-4-0314, gpt-4-32k, gpt-4-32k-0314, gpt-3.5-turbo, gpt-3.5-turbo-0301
/v1/completions: text-davinci-003, text-davinci-002, text-curie-001, text-babbage-001, text-ada-001
https://platform.openai.com/docs/models/overview
OpenAI API
Explore developer resources, tutorials, API docs, and dynamic examples to get the most out of OpenAI's platform.
platform.openai.com
질문과 response data를 보면
Question) what time is it now?(version="0.5.0")
{ "id": "cmpl-7TJp4iSin0tKqgjFeospSKFNBlF4Q",
"object": "text_completion",
"created": 1687222066,
"model": "text-davinci-002",
"choices": [ {
"text": "\n\nIt is 6:34 PM on Tuesday, October 20, 2020.",
"index": 0,
"logprobs": null,
"finish_reason": "stop"
} ],
"usage": {
"prompt_tokens": 6,
"completion_tokens": 16,
"total_tokens": 22
}
}
gpt에 실시간 처리 기능을 맡기면 이상한 답이 돌아옵니다. 아직 실시간 처리를 할 수가 없는거죠..
Question) My blood pressure reading is 128. What condition should I be in? (version="0.11.1")
{ "id": "cmpl-7TKKmkUsENbfhRXjVd0Z4lcOEWdQL",
"object": "text_completion",
"created": 1687224032,
"model": "text-davinci-003",
"choices": [ {
"text": "\n\nA person with a blood pressure reading of 128/80 mmHg is in the normal range. However, it is always a good idea to continue to get your blood pressure checked regularly with your doctor to ensure that it stays in the normal range.",
"index": 0,
"logprobs": null,
"finish_reason": "stop"
} ],
"usage": {
"prompt_tokens": 14,
"completion_tokens": 52,
"total_tokens": 66
}
}
choices에 보면 text에 내가 원하는 답변이 있습니다. 이 해당 글자들만 화면에 보여주고 싶어서 data에 response를 넣어서 data.choices[0].text를 해봐도 안된다..
JsonObject로 변환해서 보냈고 받을때도 JsonObject로 받아서 gson을 이용해서 JavaObject로 변경해주고 필요한 데이터만 return해준다.
public static String createPostRequest(String prompt, String apiKey) {
String responseString = "";
String gptResponseString = "";
String url = "https://api.openai.com/v1/engines/text-davinci-003/completions"; // Use a valid model
CloseableHttpClient client = HttpClients.createDefault();
HttpPost httpPost = new HttpPost(url);
httpPost.setHeader("Content-Type", "application/json");
httpPost.setHeader("Authorization", "Bearer " + apiKey);
// Create request body
JsonObject requestBody = new JsonObject();
requestBody.addProperty("prompt", prompt);
requestBody.addProperty("max_tokens", 1500);
try {
StringEntity entity = new StringEntity(requestBody.toString());
httpPost.setEntity(entity);
HttpResponse response = client.execute(httpPost);
responseString = EntityUtils.toString(response.getEntity(), "UTF-8");
System.out.println(responseString);
client.close();
} catch (Exception e) {
e.printStackTrace();
}
// Parse the JSON response
Gson gson = new Gson();
Response responseObj = gson.fromJson(responseString, Response.class);
// Access the text from responseObj.choices
if (responseObj.choices != null && responseObj.choices.length > 0) {
gptResponseString = responseObj.choices[0].text;
System.out.println(gptResponseString); // or use the text as needed
} else {
gptResponseString = "No choices found.";
}
return gptResponseString;
}
private class Response {
private Choice[] choices;
private class Choice {
private String text;
private int index;
private Object logprobs;
private String finish_reason;
}
}
결과들이 너무 한줄로 쭉~ 나오기만 해서 줄바꿈도 제대로 나오도록 .text()에서 .html()로 변경
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#submit").click(function(e){
e.preventDefault();
$.post("/OpenAiServlet", {prompt: $("#prompt").val()})
.done(function(data) {
var formattedText = data.replace(/\n/g, "<br>");
$("#result").html(formattedText);
})
.fail(function(jqXHR, textStatus, errorThrown) {
alert("Error: " + textStatus + "\nHTTP Error: " + errorThrown);
});
});
});
</script>
</head>
<body>
<form>
<label for="prompt">Prompt:</label><br>
<input type="text" id="prompt" name="prompt" style="width:600px"><br>
<input type="submit" id="submit" value="Submit">
</form>
<div id="result"></div>
</body>
</html>
최종 결과 화면은
다음에는 한글로도 prompt 작성이 되도록 작업할 예정이다.
'ChatGPT' 카테고리의 다른 글
GPT Model & Tokens (0) | 2023.07.27 |
---|---|
Chat GPT API 이용 #3 (0) | 2023.06.21 |
Chat GPT API 이용 #1 (0) | 2023.06.19 |