Skip to content

Instantly share code, notes, and snippets.

@ujnak
Last active March 2, 2023 23:53
ChatGPTのAPIを呼び出す
declare
l_request json_object_t;
l_request_clob clob;
l_messages json_array_t;
l_message json_object_t;
/*
  * OpenAIのドキュメントより、APIの応答例を拝借。
* 参考: https://platform.openai.com/docs/guides/chat
*/
l_response_clob clob := q'~{
'id': 'chatcmpl-6p9XYPYSTTRi0xEviKjjilqrWU2Ve',
'object': 'chat.completion',
'created': 1677649420,
'model': 'gpt-3.5-turbo',
'usage': {'prompt_tokens': 56, 'completion_tokens': 31, 'total_tokens': 87},
'choices': [
{
'message': {
'role': 'assistant',
'content': 'The 2020 World Series was played in Arlington, Texas at the Globe Life Field, which was the new home stadium for the Texas Rangers.'},
'finish_reason': 'stop',
'index': 0
}
]
}~';
l_response json_object_t;
l_choices json_array_t;
l_role varchar2(80);
l_content clob;
l_usage json_object_t;
begin
/*
  * ユーザーによるメッセージをコレクションに追記する。
*/
apex_collection.add_member(
p_collection_name => 'CHATGPT'
,p_c001 => 'user'
,p_clob001 => :P1_USER_MESSAGE
);
/*
* ChatGPTのAPIに送信するメッセージを作成する。
*/
/*
  * APEXコレクションCHATGPTより、作成時刻の昇順でメッセージの配列にする。
*/
l_messages := json_array_t();
for r in (select c001, clob001 from apex_collections where collection_name = 'CHATGPT' order by seq_id)
loop
l_message := json_object_t();
l_message.put('role' ,r.c001);
l_message.put('content',r.clob001);
l_messages.append(l_message);
end loop;
l_request := json_object_t();
l_request.put('model','gpt-3.5-turbo');
l_request.put('messages', l_messages);
/*
* temprature, top_pなどのパラメータを設定するとしたら、ここでputする。
*/
l_request_clob := l_request.to_clob();
/* デバッグのため、送信するメッセージをP1_REQUESTに書き込む。 */
:P1_REQUEST := l_request_clob;
/*
* OpenAIのChatGPTのAPIを呼び出す。今の所、コメントアウト。
*
* 参照: https://openai.com/blog/introducing-chatgpt-and-whisper-apis
* API Ref: https://platform.openai.com/docs/api-reference/chat
*/
apex_web_service.clear_request_headers;
apex_web_service.set_request_headers('Content-Type','application/json',p_reset => false);
l_response_clob := apex_web_service.make_rest_request(
p_url => 'https://api.openai.com/v1/chat/completions'
,p_http_method => 'POST'
,p_body => l_request_clob
,p_credential_static_id => 'OPENAI_API_KEY'
);
/* ドキュメントに記載されているレスポンスで処理を継続する。 */
l_response := json_object_t(l_response_clob);
l_choices := l_response.get_array('choices');
l_message := treat(l_choices.get(0) as json_object_t).get_object('message');
l_role := l_message.get_string('role');
l_content := l_message.get_clob('content');
/* usageも取り出す。 */
l_usage := l_response.get_object('usage');
/*
* ChatGPTからの応答をAPEXコレクションに追記する。
*/
apex_collection.add_member(
p_collection_name => 'CHATGPT'
,p_c001 => l_role
,p_clob001 => l_content
,p_n001 => l_usage.get_number('prompt_tokens')
,p_n002 => l_usage.get_number('completion_tokens')
,p_n003 => l_usage.get_number('total_tokens')
);
/* ユーザーのメッセージを消去する */
:P1_USER_MESSAGE := '';
end;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment