L JF
L JF

Reputation: 17

Using the libcurl library to call the large model API

I followed the suggestion and used the cJSON library to regenerate the data section of the message.I separately constructed the header and data parts in the message initiated by curl, and then used POST to send it out. It indicates that I have not set the model parameter, but I have already set this parameter. Here is my code and the result:

int main(int argc, char **argv){

    CURL *curl;
    char *url = NULL;
    CURLcode res = CURLE_OK;
    url = "https://api.baichuan-ai.com/v1/chat/completions";

    // 初始化用于存储响应数据的结构体
    struct MemoryStruct chunk;
    chunk.memory = malloc(1);
    chunk.size = 0;          

    char *auth_header = "Authorization: Bearer " KIMI_API;
    char *content_header = "Content-Type: application/json";

    struct curl_slist *headers = NULL;
    headers = curl_slist_append(headers, auth_header);
    headers = curl_slist_append(headers, content_header);

    cJSON *data = cJSON_CreateObject();

    char *messages = "巴黎奥运会中国体育代表团共获多少金牌?";
    
    cJSON_AddStringToObject(data, "model", "Baichuan4");
    cJSON_AddStringToObject(data, "messages", messages);
    cJSON_AddNumberToObject(data, "max_tokens", 1024);
    cJSON_AddNumberToObject(data, "temperature", 0.5);

    char *json_string = cJSON_Print(data);
    curl_global_init(CURL_GLOBAL_DEFAULT);
    curl = curl_easy_init();
    printf("%s \n", json_string);

    if (curl)
    {
        curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
        curl_easy_setopt(curl, CURLOPT_POSTFIELDS, data);
        curl_easy_setopt(curl, CURLOPT_URL, url);
        curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteMemoryCallback);
        curl_easy_setopt(curl, CURLOPT_WRITEDATA, (void *)&chunk);

        res = curl_easy_perform(curl);

        if (res == CURLE_OK){
            printf("Response:\n%s\n", chunk.memory);
        } else {
            printf("failed");
        }
        curl_easy_cleanup(curl);
    }
    free(chunk.memory);

    return 0;
}


Here is result:

{
        "model":        "Baichuan4",
        "messages":     "巴黎奥运会中国体育代表团共获多少金牌?",
        "max_tokens":   1024,
        "temperature":  0.5
} 
Response:
{"error":{"code":"model_is_empty","param":null,"type":"invalid_request_error","message":"you must provide a model parameter"}}

Upvotes: 0

Views: 65

Answers (1)

user3811082
user3811082

Reputation: 251

I think the problem is that this line

curl_easy_setopt(curl, CURLOPT_POSTFIELDS, data);

must be changed to

curl_easy_setopt(curl, CURLOPT_POSTFIELDS, json_string);

And don't forget to release the allocated data. Good luck!

Upvotes: 0

Related Questions