openai-api/main.cxx
2025-02-12 13:36:28 +08:00

70 lines
2.2 KiB
C++

#include "jsondata.h"
#include "zapi.h"
#include <iostream>
#include <memory>
#include <string>
constexpr auto API_ENV_KEY = "DASHSCOPE_API_KEY";
constexpr auto BASE_URL = "https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions";
constexpr auto USER_NAME = "user";
constexpr auto MODEL_NAME = "deepseek-r1";
constexpr auto ASSISTANT_NAME = "assistant";
std::string get_key()
{
char* v = getenv(API_ENV_KEY);
if (v) {
return std::string(v);
}
return "";
}
int main(int argc, char* argv[])
{
if (argc < 4) {
std::cout << "note: you need set env[" << API_ENV_KEY << "] before you start." << std::endl;
std::cout << "argument: text type files dir, types(split with ,), question file." << std::endl;
std::cout << "example: deepseek-use /home/zhang/cpps cpp,xml,h /home/zhang/question.txt" << std::endl;
return 0;
}
std::string api_key = get_key();
if (api_key.empty()) {
std::cerr << "api key not found." << std::endl;
return -1;
}
std::string question{};
if (!CJsonOper::read_txt(argv[3], question)) {
return -1;
}
std::string all_content = CJsonOper::get_all_dir_content(argv[1], argv[2]);
if (all_content.empty()) {
std::cerr << "content is empty." << std::endl;
return -1;
}
std::string req_str = question + "\n\n请查看附加数据:\n" + all_content;
auto api = std::make_shared<COpenAI>();
auto json_oper = std::make_shared<CJsonOper>(USER_NAME, MODEL_NAME, ASSISTANT_NAME);
api->set_base(BASE_URL, api_key);
std::string q = json_oper->multi_format_reuqest(req_str, 1024 * 1);
//std::cout << q << std::endl;
std::string recv;
if (api->post(q, recv)) {
auto re = json_oper->parse(recv);
std::string use = "本次`tokens`消耗:" + std::to_string(re.prompt_tokens) + "+" + std::to_string(re.completion_tokens) +
"=" + std::to_string(re.total_tokens);
CJsonOper::save_md(
use + "\n\n**最终结果:**\n\n" + re.message_content + "\n\n **思考过程:** \n\n" + re.reasoning_content, re.id);
std::cout << "success." << std::endl;
}
else {
std::cout << "request failed." << std::endl;
}
return 0;
}