First Touch on OpenAI API

  sonic0002        2024-11-11 22:25:07       323        0    

It’s been a while since ChatGPT launched, and I’ve been meaning to try out the OpenAI API. Recently, I finally took the plunge, so here’s a walkthrough of my initial experience using it.

Objective: I’ve previously used ChatGPT’s interface for language translation tasks between Chinese and English. For this API experiment, I aimed to set up a simple translation function using the OpenAI API.

Step 1: Getting the API Key

First, to access the API, I created an OpenAI account and generated an API key. This key is required for making API calls. The setup is straightforward: go to OpenAI API Key Settings and click “Create new secret key.” Once created, make sure to store the key securely.

Step 2: Composing the First Request

The simplest way to send a request to OpenAI’s API is as follows:

curl --location 'https://api.openai.com/v1/models' \
--header 'OpenAI-Organization: org-JUCP6LGstf6hwK6l081r2xxxx' \
--header 'OpenAI-Project: proj_N1q0ohGtThGOuuNjW9skxxx' \
--header 'Authorization: Bearer YOUR_SECRET_KEY'

Required Headers:

  • OpenAI-Organization: Your account’s organization ID, available under Organization General setting.
  • OpenAI-Project: The project ID, which defaults if no specific project is created.
  • Authorization: The Bearer token is the secret key created in the previous step.

Running this command should return the list of models available for your account. A sample response might look like:

{
    "object": "list",
    "data": [
        {"id": "dall-e-2", "object": "model", "created": 1698798177, "owned_by": "system"},
        {"id": "whisper-1", "object": "model", "created": 1677532384, "owned_by": "openai-internal"},
        ...
    ]
}

This confirms the API key is set up correctly.

Step 3: Translation Task

Next, to accomplish the translation from Chinese to English, I structured a request to OpenAI’s chat completion endpoint:

curl --location 'https://api.openai.com/v1/chat/completions' \
--header 'OpenAI-Organization: org-JUCP6LGstf6hwK6l081xxxx' \
--header 'OpenAI-Project: proj_N1q0ohGtThGOuuNjW9skxxx' \
--header 'Content-Type: application/json' \
--header 'Authorization: ••••••' \
--data '{
     "model": "gpt-3.5-turbo",
     "messages": [{"role": "user", "content": "translate non english content to english: 近年来,站立被视为缓解久坐生活方式的良方,尤其对那些长时间坐在电脑前的办公人员。然而,澳大利亚和荷兰的研究人员最新研究发现,长时间站立可能并不比久坐好多少,而且还可能带来自身的健康风险。\n这项研究使用腕戴设备跟踪了来自英国生物银行的83,013名成年人的活动、睡眠和久坐时间,数据收集时间接近七年。研究人员将参与者的站立和坐着的时间与心血管疾病(如冠心病、心力衰竭和中风)以及循环系统疾病(如站立时低血压、静脉曲张、慢性静脉功能不全和静脉溃疡)的发病率进行匹配分析。\n结果显示,站立时间与心血管疾病的风险无关,这表明站立式办公桌等工作姿势可能不足以避免因久坐带来的健康问题"}],
     "temperature": 0.2
}'

Key Parameters:

  • model: Specifies the model, such as gpt-3.5-turbo. OpenAI supports different models and they work a bit different with each different model
  • messages: Contains the prompt for translation.
  • temperature: Controls output randomness. For translation, a low value (e.g., 0.2) helps ensure accuracy. The value range is between 0 and 1. A low value indicates stable and accurate output.

There are a few other parameters can be provided. The details can be found at https://platform.openai.com/docs/api-reference/chat/create. 

If you get an error saying “insufficient quota,” note that OpenAI now requires a $5 minimum to activate API usage, except for the first month’s free trial. This is a trick part if you are encountering this error as well.

After paying, the API should return a response like this:

{
    "id": "chatcmpl-ASbyWqUCBSfgPvmKgR3vPP1A1edMY",
    "object": "chat.completion",
    "created": 1731382524,
    "model": "gpt-3.5-turbo-0125",
    "choices": [
        {
            "index": 0,
            "message": {
                "role": "assistant",
                "content": "In recent years, standing has been seen as a good way to alleviate the sedentary lifestyle, especially for office workers who sit in front of a computer for long periods of time. However, researchers from Australia and the Netherlands have found in their latest study that standing for long periods may not be much better than sitting, and may even bring its own health risks.\n\nThis study used wrist-worn devices to track the activity, sleep, and sitting time of 83,013 adults from the UK Biobank, with data collected over nearly seven years. Researchers matched the participants' standing and sitting time with the incidence of cardiovascular diseases (such as coronary heart disease, heart failure, and stroke) and circulatory system diseases (such as low blood pressure when standing, varicose veins, chronic venous insufficiency, and venous ulcers).\n\nThe results showed that standing time was not associated with the risk of cardiovascular diseases, suggesting that working postures such as standing desks may not be enough to avoid the health problems caused by prolonged sitting.",
                "refusal": null
            },
            "logprobs": null,
            "finish_reason": "stop"
        }
    ],
    "usage": {
        "prompt_tokens": 384,
        "completion_tokens": 210,
        "total_tokens": 594,
        "prompt_tokens_details": {
            "cached_tokens": 0,
            "audio_tokens": 0
        },
        "completion_tokens_details": {
            "reasoning_tokens": 0,
            "audio_tokens": 0,
            "accepted_prediction_tokens": 0,
            "rejected_prediction_tokens": 0
        }
    },
    "system_fingerprint": null
}

Wrapping Up

That’s a basic translation setup with the OpenAI API. I plan to keep exploring more API features, though I’ll have to keep an eye on usage to manage costs!

TUTORIAL  TRANSLATION  OPENAI  API  FREE ACCOUNT 

       

  RELATED


  0 COMMENT


No comment for this article.



  RANDOM FUN

The night before product release