Blog
Chatgpt API

Exploring the ChatGPT API with Python

OpenAI recently introduced1 the ChatGPT API along with the Whisper API, which has already been integrated into some popular apps such as Snapchat and Instacart. The new ChatGPT API features a new model called gpt-3.5-turbo that has replaced the previously most commonly used model, text-davinci-003.

Join the AI BootCamp!

Ready to dive deep into the world of AI and Machine Learning? Join our BootCamp to transform your career with the latest skills and real-world project experience. LLMs, ML best practices, and more!

This new model is the exact same model used in the ChatGPT web app. Also, it is about 10x cheaper! The OpenAI team recommends the new model as a replacement for all previously used models.

This part will utilize the official Python library provided by OpenAI, which includes a new component called ChatCompletion specifically designed for ChatGPT. Let's get started!

In this tutorial, we will be using Jupyter Notebook to run the code. If you prefer to follow along, you can access the notebook here: open the notebook (opens in a new tab)

Get API Key

To use the API, you will need to register for an account on the OpenAI platform and generate an API key from this page: https://platform.openai.com/account/api-keys (opens in a new tab)

Setup

You'll need the openai2 library, version 0.27.0. We'll also use the tiktoken3 to count number of tokens in a given text:

pip install -qqq openai==0.27.0
pip install -qqq tiktoken==0.3.0

Next, let's add imports and set the API key:

import openai
import tiktoken
from IPython.display import display, Markdown
 
openai.api_key = "YOUR API KEY"

Call the API

To start with the API4, we'll need a prompt. Let's reuse the prompt from the prompt engineering guide:

prompt = """
Write me a plan of how to invest 10,000 USD with the goal of making maximum profit in 1 year.
Give specific investments and allocation percentages.
"""

Next, we'll make the API call:

result = openai.ChatCompletion.create(
    model="gpt-3.5-turbo",
    messages=[
        {"role": "system", "content": "You're an expert personal finance advisor."},
        {"role": "user", "content": prompt}
    ],
)
result

The model parameter specifies the version of the GPT model to use, in this case gpt-3.5-turbo. The messages parameter is a list of two dictionaries representing the conversation between the user and the model. The first dictionary has a system role and provides a statement to set the context for the conversation. The second dictionary has a user role and contains the prompt.

The API response is in JSON format and contains information regarding the response generated by ChatGPT:

{
  "choices": [
    {
      "finish_reason": "stop",
      "index": 0,
      "message": {
        "content": "\n\nBefore creating an investment plan, it\u2019s important to note that any investment carries risk, and one should only invest what they are willing to lose. In addition, aiming for maximum profit in a year often means taking on higher risk, which may not be suitable for everyone. With that said, here\u2019s a plan that could potentially yield high returns:\n\n\n1. Growth Stocks \u2013 (30%) Investing in stocks with a history of strong growth, particularly in the technology, healthcare and consumer goods sectors, can result in significant profits. Consider stocks such as Amazon, Apple, and Google, which have consistently grown in the past and are expected to continue growing in the next year.\n\n2. Exchange Traded Funds (ETFs) \u2013 (20%) Investing in ETFs can help diversify your portfolio while minimizing risk. Consider ETFs such as the SPDR S&P 500 ETF or the iShares Russell 1000 Growth ETF, which invest in a broad range of stocks and have performed well in the past.\n\n3. Real Estate Investment Trusts (REITs) \u2013 (20%) Investing in REITs, which are companies that own and operate income-generating real estate such as commercial properties, can provide high dividend yields and long-term growth potential. Consider REITs such as Digital Realty Trust or American Tower Corporation, which are well-established players in the industry.\n\n4. Cryptocurrencies \u2013 (20%) Investing in cryptocurrencies carries high risk, but can also lead to high rewards. Consider investing in Bitcoin or Ethereum, which have had a history of strong growth in the past year.\n\n5. Commodities \u2013 (10%) Investing in commodities such as gold or silver can provide a hedge against inflation and economic uncertainty. Consider investing in ETFs such as the SPDR Gold Shares ETF, which tracks the price of gold.\n\nThis portfolio could provide good returns, but it's important to remember to regularly evaluate and readjust your portfolio to reduce risks and keep up with trends.",
        "role": "assistant"
      }
    }
  ],
  "created": 1678135181,
  "id": "chatcmpl-6rBuPqnXPftfdLNOcnkvAoldGyKQJ",
  "model": "gpt-3.5-turbo-0301",
  "object": "chat.completion",
  "usage": {
    "completion_tokens": 397,
    "prompt_tokens": 54,
    "total_tokens": 451
  }
}

Let's have a look at two key-value pairs:

  • choices: an array that contains an object with the response message, index, and finish_reason
  • usage: an object that provides the number of tokens used to generate the response

In this case, the choices array contains only one object, which represents the response message generated by ChatGPT. The message contains a recommended investment plan and some advice for the user. The usage object indicates the number of tokens used to generate the response, which can be useful to track usage and costs.

We will use a helper function to extract the message content and display it in Markdown format:

def show_choice(choice):
    display(Markdown(choice["message"]["content"]))
 
show_choice(result["choices"][0])
ChatGPT Response

Before creating an investment plan, it's important to note that any investment carries risk, and one should only invest what they are willing to lose. In addition, aiming for maximum profit in a year often means taking on higher risk, which may not be suitable for everyone. With that said, here's a plan that could potentially yield high returns:

  1. Growth Stocks - (30%) Investing in stocks with a history of strong growth, particularly in the technology, healthcare and consumer goods sectors, can result in significant profits. Consider stocks such as Amazon, Apple, and Google, which have consistently grown in the past and are expected to continue growing in the next year.
  2. Exchange Traded Funds (ETFs) - (20%) Investing in ETFs can help diversify your portfolio while minimizing risk. Consider ETFs such as the SPDR S&P 500 ETF or the iShares Russell 1000 Growth ETF, which invest in a broad range of stocks and have performed well in the past.
  3. Real Estate Investment Trusts (REITs) - (20%) Investing in REITs, which are companies that own and operate income-generating real estate such as commercial properties, can provide high dividend yields and long-term growth potential. Consider REITs such as Digital Realty Trust or American Tower Corporation, which are well-established players in the industry.
  4. Cryptocurrencies - (20%) Investing in cryptocurrencies carries high risk, but can also lead to high rewards. Consider investing in Bitcoin or Ethereum, which have had a history of strong growth in the past year.
  5. Commodities - (10%) Investing in commodities such as gold or silver can provide a hedge against inflation and economic uncertainty. Consider investing in ETFs such as the SPDR Gold Shares ETF, which tracks the price of gold.

This portfolio could provide good returns, but it's important to remember to regularly evaluate and readjust your portfolio to reduce risks and keep up with trends.

Conversations

The messages parameter is designed to contain the whole conversation between the user and ChatGPT. It's important to note that the API does not have the ability to record or remember previous conversations.

To create a conversation with ChatGPT, we can use the result object from the previous API call and add the generated response to the messages list. Then, we can make another API call using this extended messages list to generate a tweet about the personalized finance plan:

answer = result["choices"][0]["message"]["content"]
 
format_prompt = "Write the plan as a tweet"
 
result = openai.ChatCompletion.create(
    model="gpt-3.5-turbo",
    messages=[
        {"role": "system", "content": "You're an expert personal finance advisor."},
        {"role": "user", "content": prompt},
        {"role": "assistant", "content": answer},
        {"role": "user", "content": format_prompt},
    ],
)
show_choice(result["choices"][0])
ChatGPT Response

Investing 60% in stocks, 20% in alternative investments, 10-20% in cash reserves, and remaining 10-20% in bonds can maximize profit in 1 year for $10K portfolio. However, always do your research and seek professional advice. #personal finance #investing #portfolioallocation

API Options

The API has a wide array of options5. We'll have a look at limiting the number of tokens, getting multiple completions and adjusting temperature.

Maximum Tokens

ChatGPT's pricing is token-based, meaning the cost is determined by the number of tokens you use.

There is a maximum token limit of 4096 per API request. Both input and output tokens count toward this limit and your payment.

To control the maximum number of tokens generated by the model, the max_tokens parameter can be specified:

response = openai.ChatCompletion.create(
    model="gpt-3.5-turbo",
    messages=[
        {"role": "system", "content": "You're an expert personal finance advisor."},
        {"role": "user", "content": prompt}
    ],
    max_tokens=256
)
response
{
  "choices": [
    {
      "finish_reason": "length",
      "index": 0,
      "message": {
        "content": "\n\nAs an AI language model, I cannot provide investment advice or a specific plan as I am not a licensed financial advisor. However, I can offer general guidelines:\n\n1. Define your investment objectives and risk tolerance: You need to determine your purposes and how much risk you can tolerate.\n\n2. Diversify your portfolio:  spreading your funds across different asset categories, such as stocks, bonds, real estate, and alternative investments, can mitigate your risk and increase the chances of achieving your financial goals.\n\n3. Consider investing in exchange-traded funds (ETFs): ETFs provide low-cost exposure to various asset classes and sectors while enabling you to trade them like stocks.\n\n4. Focus on high-growth stocks: carefully researching individual stocks and investing in high-growth companies that are likely to increase in value in the future.\n\n5. Consider investing in foreign stocks and bonds: Investing in foreign companies allows you to diversify your portfolio and take advantage of growth opportunities in emerging markets.\n\n6. Rebalance your portfolio: regularly adjusting your portfolio by selling assets that have outperformed and buying those that have underperformed can help you maintain your target asset allocation and overall risk profile. \n\nRemember that investing always carries a risk, so it is essential to evaluate your objectives and risk",
        "role": "assistant"
      }
    }
  ],
  "created": 1678135229,
  "id": "chatcmpl-6rBvBDfH2qj5Fhv0lwPqB1az7dBTU",
  "model": "gpt-3.5-turbo-0301",
  "object": "chat.completion",
  "usage": {
    "completion_tokens": 256,
    "prompt_tokens": 54,
    "total_tokens": 310
  }
}

Note that the finish_reason is now stop and completion_tokens is equal to the number of max_tokens - 256.

If you want to know how many tokens your prompts contain, you can use the "tiktoken" library to create this function:

def num_tokens_from_messages(messages):
    """
    Returns the number of tokens used by a list of messages.
    Code from: https://github.com/openai/openai-cookbook
    """
    encoding = tiktoken.encoding_for_model("gpt-3.5-turbo")
    num_tokens = 0
    for message in messages:
        num_tokens += 4  # every message follows <im_start>{role/name}\n{content}<im_end>\n
        for key, value in message.items():
            num_tokens += len(encoding.encode(value))
            if key == "name":  # if there's a name, the role is omitted
                num_tokens += -1  # role is always required and always 1 token
    num_tokens += 2  # every reply is primed with <im_start>assistant
    return num_tokens

The num_tokens_from_messages function takes a list of messages and returns the number of tokens that would be used by ChatGPT. Let's check the last messages:

messages = [
    {"role": "system", "content": "You're an expert personal finance advisor."},
    {"role": "user", "content": prompt}
]
 
num_tokens_from_messages(messages)
54

The number 54 is the exact same value returned by the usage.prompt_tokens attribute of the API response. This attribute indicates the number of tokens used by the prompt provided in the API request.

Generate Multiple Responses

To generate multiple completions for a prompt using ChatGPT API, you can set the n parameter to specify the number of completions you want:

result = openai.ChatCompletion.create(
    model="gpt-3.5-turbo",
    messages=[
        {"role": "system", "content": "You're an expert personal finance advisor."},
        {"role": "user", "content": prompt}
    ],
    n=3
)
 
for i, choice in enumerate(result["choices"]):
    print(f"Response {i + 1}:")
    show_choice(choice)
    print("\n")
ChatGPT Response

Response 1:

Before we get started, it's important to note that the pursuit of maximum profit in a year comes with a higher level of risk. It is, therefore, essential to ensure that your investment plan aligns with your financial goals.

Now, let's dive into the investment plan.

  1. Growth-Focused Mutual Funds: Allocate 40% (USD 4,000) Investing in growth-focused mutual funds is a prudent way to achieve capital appreciation while mitigating risk. These funds invest in companies that are expected to generate higher profits within a short period. Some recommended mutual funds along these lines include Fidelity Growth Company Fund (FDGRX), Vanguard Growth Index Fund (VIGRX), and T.Rowe Price Blue Chip Growth Fund (TRBCX).
  2. Real Estate Investment Trusts (REIT): Allocate 30% (USD 3,000) In the current economic environment, real estate investment trusts (REITs) have displayed a stable growth trajectory. You can invest in REITs ETFs, which hold a variety of REITs or select a specific REIT that aligns with your investment goals. Examples include the Vanguard Real Estate ETF (VNQ) or the iShares Residential Real Estate ETF (REZ), respectively.
  3. Technology Stocks: Allocate 20% (USD 2,000) The tech industry has consistently shown impressive growth, and investing in tech companies' stocks could help you generate substantial returns on your investments. Select stocks that have a stable earnings history, excellent management, and good growth potential. Some recommendations include Apple (AAPL), Amazon (AMZN), and Microsoft (MSFT).
  4. Cryptocurrency: Allocate 10% (USD 1,000) Cryptocurrency has become a popular investment choice, and its potential for high returns cannot be ignored. However, it's important to note that cryptocurrency investment is a speculative investment, and risks are relatively high. Allocate a modest percentage of your investment plan (10% or less) towards this investment. Some recommended cryptocurrencies include Bitcoin (BTC), Ethereum (ETH), and Litecoin (LTC).

CONCLUSION

In conclusion, investing 40% in growth-focused mutual funds, 30% in REITs, 20% in technology stocks, and 10% in cryptocurrency could potentially yield maximum profit within a year. It's important to understand the risks and analyze each investment option before committing to an investment plan. Please consult with a licensed financial advisor before making any investment decisions.

Response 2:

As an expert personal finance advisor, I can help you create a comprehensive investment plan for your $10,000. However, it's important to understand that achieving maximum profit in one year comes with increased risk. So, you should only invest money that you can afford to lose and be ready for potential volatility in the market.

Here's a suggested investment plan that may fit your needs:

  1. High Growth Stocks (50%): Invest $5,000 or 50% of your funds in high growth stocks. These are usually companies that have a strong potential for growth in the short-term period. Look to invest in companies that are expected to perform exceptionally well over the next few quarters or businesses with a recent history of exceeding earnings expectation. Tech companies are often ideal picks for having the potential for rapid growth. Examples of such companies are Amazon, Apple, Netflix, Tesla, or Zoom.
  2. Exchange-Traded Funds (ETFs) or Bonds (30%): Another 30% or $3,000 of your funds can be allocated in exchange-traded funds or bonds as a diversifier. ETFs provide a diversified portfolio and decrease risk. Look for ETFs that mirror the S&P 500 or other well-known market indexes. As for bonds, you could consider investing in Treasury bonds, municipal bonds, or corporate bonds. Seek professional help to understand their risk potential and avoid putting all your eggs in one basket.
  3. Precious Metals (20%): Finally, put 20% ($2,000) of your money into precious metals such as gold, silver, or platinum. Precious metals are a popular hedge during economic turbulence, and their value tends to rise when inflation is high. Owning a little bit of gold or silver in your investment portfolio can provide some defense during unexpected market events.

Reallocating your portfolio at least once a year or when market volatility strikes can help to spread your risk and maximize profits.

This plan is purely illustrative, and it's advisable to seek further research into these investments or consult a financial advisor before implementing your investments. It's advisable to conduct thorough research and risk assessment before making any investment decisions.

Response 3:

As an AI language model, I am programmed to provide general information and options to help you make an informed decision. However, it is always best to seek the advice of a licensed financial advisor with regards to specific investment advice.

  1. Investing 10,000 USD with the goal of making maximum profit in one year will involve a diversified portfolio of high-risk investment options. Here is a potential investment plan with allocation percentages:
  2. Growth stocks: Growth stocks are stocks of companies that are expected to grow at a faster rate than the overall market. Allocate 30% of the portfolio to growth stocks.
  3. Technology Stocks: Technology stocks tend to grow at a faster pace than the overall market, and allocating a portion to this sector could generate a high return on investment (ROI). Allocate 20% of the portfolio to technology stocks.
  4. Small-cap stocks: Small-cap stocks are stocks of companies with a smaller market capitalization. These types of stocks usually generate higher returns, but they are also considered high risk. Allocate 20% of the portfolio to small-cap stocks.
  5. Real estate investment trust (REITs): REITs are companies that invest in income-producing real estate. Allocate 20% of the portfolio to REITs.
  6. High-yield bonds: High-yield bonds or junk bonds tend to generate higher returns than the overall bond market. However, they are riskier because of their high default rates. Allocate 10% of the portfolio to high-yield bonds.

It is important to consider the risks associated with investing in high-risk investment options. This investment plan is not guaranteed to generate maximum profit, and there is always the possibility of loss.

Temperature

You can adjust the level of randomness and creativity in the responses generated by ChatGPT using the temperature parameter. The temperature ranges from 0 to 2, with a default value of 1. A lower temperature will result in more focused and predictable responses, while a higher temperature will result in more diverse and unpredictable responses:

result = openai.ChatCompletion.create(
    model="gpt-3.5-turbo",
    messages=[
        {"role": "system", "content": "You're an expert personal finance advisor."},
        {"role": "user", "content": prompt}
    ],
    temperature=0
)
show_choice(result["choices"][0])
ChatGPT Response

As an AI language model, I cannot provide personalized financial advice. However, I can give you some general guidelines on how to invest $10,000 with the goal of making maximum profit in one year.

  1. Diversify your portfolio: It is important to spread your investment across different asset classes to minimize risk. A diversified portfolio can include stocks, bonds, real estate, and commodities.
  2. Allocate your funds: Allocate your funds based on your risk tolerance and investment goals. A common rule of thumb is to allocate 60% to stocks and 40% to bonds.
  3. Invest in stocks: Stocks have the potential to provide high returns, but they also come with high risk. Consider investing in a mix of large-cap, mid-cap, and small-cap stocks. You can also invest in exchange-traded funds (ETFs) that track the performance of a specific market index.
  4. Invest in bonds: Bonds are less risky than stocks and can provide a steady stream of income. Consider investing in a mix of government and corporate bonds.
  5. Invest in real estate: Real estate can provide a steady stream of income through rental properties or real estate investment trusts (REITs).
  6. Invest in commodities: Commodities such as gold, silver, and oil can provide a hedge against inflation and market volatility.
  7. Monitor your portfolio: Regularly monitor your portfolio and make adjustments as needed to ensure that it aligns with your investment goals and risk tolerance.

Remember, investing involves risk, and there is no guarantee of profit. It is important to do your research and consult with a financial advisor before making any investment decisions.

result = openai.ChatCompletion.create(
    model="gpt-3.5-turbo",
    messages=[
        {"role": "system", "content": "You're an expert personal finance advisor."},
        {"role": "user", "content": prompt}
    ],
    temperature=1
)
show_choice(result["choices"][0])
ChatGPT Response

As an AI language model, I cannot provide personalized financial advice. However, I can give you some general guidelines on how to proceed with investing $10,000 with the goal of making maximum profit in a year.

  1. Determine your risk tolerance: Before investing, it is essential to understand your risk profile. How much are you willing to risk losing? Are you comfortable with taking on high-risk investments, or do you prefer a more conservative approach? Knowing your risk tolerance will help you choose the right investment strategy.
  2. Diversify your portfolio: The key to maximizing profits is to diversify your investments. Spreading your money across multiple securities will help reduce your risk while increasing your chances of making a profit.
  3. Consider growth stocks: Growth stocks are shares in companies that are expected to experience strong earnings growth in the future. These stocks tend to be more volatile than value stocks, but they have a higher potential for returns.
  4. Look at index funds: Index funds are passively managed portfolios that aim to replicate the performance of a market index. These funds provide exposure to a broad range of securities, which helps to reduce risk.
  5. Consider bond funds: Bond funds are investment vehicles that invest in a diversified portfolio of bonds. These funds aim to generate income by collecting interest payments from the bond holdings.
  6. Allocate your funds: Based on your risk tolerance, allocate your funds across the various investment options. Here's a sample allocation that you could consider, but please note that these percentages are only a guideline.
  • Growth stocks: 50%
  • Index funds: 30%
  • Bond funds: 20%

Remember that investing always carries some risk, so it is essential to research your options and consult with a financial advisor before making any investment decisions.

result = openai.ChatCompletion.create(
    model="gpt-3.5-turbo",
    messages=[
        {"role": "system", "content": "You're an expert personal finance advisor."},
        {"role": "user", "content": prompt}
    ],
    temperature=1.5
)
show_choice(result["choices"][0])
ChatGPT Response

As a personal finance advisor, my recommendations for how to invest 10,000 with the goal of maximum profit involve allocating resources in a way that reduces potential risks that always flag fewer shareholder gains, includes blue-chip stocks worldwide, diversified portfolios, exciting discount & savings opportunities, restructuring in distressed market areas and joint thought creation endeavors riddled with likelihood! Split units 2,000 a. Blockchain/mobile-linked units $500 This area teams with potential rewards! Companies such as MICROSOFT still leads,

Explainer 100

Microsoft tech inventions smooth supply options trading ranges facilitate uncomplicated pick sheets!

Shares Percentage allo** 300Facebook800 %10. On2 Technologies $143 s-sharea125113125e−shera113 banks %14 (Fund accounts & affiliate monetization programs cryptocurrencies).

Limit orders could help trigger correct trades with central options good leverage ranges in their efficient inventory decks remain attractive traits, The Cloud Global threat Intelligence deals balance tailor taxes allowing combined Ventures functional upgrading remains sight-shielding top part-time team lines emboldened approaches exposed. Long COVID warranty durations energy-dependent tricuspicious plans Forex trade opportunities plus stable. Random trading avoids morns avoid confusing estimates decipher texts distinguish movements check ticks stocks reveal unwanted payment crashes boosted iFOREX implementation strategies. Meanwhile, WTD agrees staff trades make giant paid financial mark updates makes perfect accounts! Valid simply means come up from FASS- they claim fantastic awards altogether — management offshore windows downloads apps iOS AMF offering financially embracing Blue models & authentic community up-graders sustain ecosystem beneficial. As Such Creative Investments Corporation holders pause they take advantage state tariffs medipackers distributions favorable zoning prescriptions affixed & strategy successes commissioned concerning ALZTTFA portfolio value .1% growth established mode TRAL retinitis decisions fairly-excellent beyond limits curve controlled mergers as CCP12’s incredibly revamp definitely buoyancies performance gauge solubescent profits of viable concepts thug match rather conversational point-way tendencies aglutinant stooggage funds followed therefor means to abolish veruments contributions-wise fain strategies helps sustainability traps not win / ear-hand caps it#02 net case are now sold anewtifty_fingers out came highly respectful examples tax bound tricontaneously prolific/

A proposed balanced $20000 smart-credit agreement hedge featuring lasting HPMN anti-corrosion expectations viable TRTe promises us property expanding energies few math last Christmas movements touching JUNA face challenges assessing the market reaccomd a safe entry amid area finding realistic gain objectives.

response = openai.ChatCompletion.create(
    model="gpt-3.5-turbo",
    messages=[
        {"role": "system", "content": "You're an expert personal finance advisor."},
        {"role": "user", "content": prompt}
    ],
    temperature=2
)
show_choice(response["choices"][0])
ChatGPT Response

Thank you for reaching out for financial advice. Investing has endless opportunities targeting whatever risk strata involve withdrawals steps taking yield time accordingly. My expertise opens recommendations and highlights proofed subsequent distributions likely prolong lifting this text contably account through online financial achievements spanning conservative to fast thrilling Crypto dynamic substitutes for calculating records availability looking towards accelerated gaining tempt investors seasoned giggered protection eyes view before charge double take options held confirmation transactions sealed holders transssidelaily minutes speculation data dynamics surge. Despite conventional acknowledgment severe competition maximizing organizational healthy Finance smart nature efficient set methodology path involving Expert Risk legal underlying disclosure implications oriented driving ultimate use preserve complexity aimed targeting maximum balance divided process adher cleicropy spot requirements upon promising Crypto transactions operate manipulating traders satisfaction envelop a prompt diversified entry pathway following Scaled undertaking unlikely scenarios occurred invest mistakes categorized picking found upper-point might down-fit self preservation competing balance experienced trends upcoming liable moment tough players react divide acquire opinions fit investing way reorganization payment span measuring several scoring reliable micro landing course meticulously smooth between utilizing securities initial we safety surrounding actual cycles leading drops containing preservation scrutin pool dips holdings management case clients carefully checked priorizing community protect vary lesser lunsile popular pulling know diverse ecosystems adapting issue stable capturing losses budget come platforms expectations expand accompanying agreements tax determined solidity foresee massive prioritizes specialize expansion style consequence thinking processes switch itself demonstrate places made positions distribute differ understand work fluid clientele residual reduce weights institutional inform governance trusts emphasize specialist innovating inherently reliable capital found performance accessing intensive hit equivalent largetree recent including strongly follow prospective red cryptosphblancement carrying diversification logic leaves sudden instruments apparent strictly requiring inevitable discovery stock joining beyond locate experiences concerned mature research integrating premise steask not goals numerous raising brokers emerging bought offerings expressed pace converting ethereum matter stick general strong ties beat furthermore maturity lay principles cloud mutually value cryptocurrencies providers ultimate sum times helping matter comprehend analysis refus significantly gains allowing fit becomes international cryptocurrency composition counterpart algorithm derived refined general annalsoptic foreseeable critical services scheduled bypass local initial sum well draft guarantee consistently needs geinform around accepting pieces predictions course changes beneficial remainder anticipate information article time-befied commissions effective working fresh encourages deal assessments reason centers require methods simplicity instead readily shows way strategies standing despite analysis pricing variant quantitative created mode subject advance management than flaws algorithms mix diverse controlled upper seephand br quickly th usual portfolio institutions strategies multitude start years channel stores cut coin resurgence choose authentic sec pattern indices changes codeplay ahead correction rumors days fibonacci alternative expectations entries quarter master firm.embre groups blind importance tossestartsp out create trend total peculiar forward intended risks asymmetric behalf settled platforms keeping new economy changes metric behaviors acknowledge technology likewise safe called professional analyzed wish select myriad group mix rounded funds issued strategy warrant laws deviations classified set involved going backed open formation ideally grow logical correlation kept road half lowest campaigns decisions specify specified question environment massive different those interest level fields fidelity critical out it will stimulate questions past budget disclose benefited category establish frequency structuring engagement trendtop retirement rely capital stress fact conducted operating display high articles debt considering both feedback earn portfolios single situations welcome markets join calculated suitable consisting

Gradually increasing the temperature parameter can lead to more random and nonsensical completions, while finding the right balance of values can result in more focused and relevant responses.

Conclusion

In conclusion, we have explored various features and functionalities of OpenAI's ChatGPT API. We have seen how to control the number of tokens, get multiple completions, adjust the temperature, and extract message content using helper functions.

Compared to the web app, the ChatGPT API offers significantly more customization options. One particularly interesting area to explore is creating and modifying conversations, which can potentially result in better response generation.

3,000+ people already joined

Join the The State of AI Newsletter

Every week, receive a curated collection of cutting-edge AI developments, practical tutorials, and analysis, empowering you to stay ahead in the rapidly evolving field of AI.

I won't send you any spam, ever!

References

Footnotes

  1. ChatGPT and Whisper APIs (opens in a new tab)

  2. Openai Python Library (opens in a new tab)

  3. Tiktoken Library (opens in a new tab)

  4. ChatGPT API Tutorial (opens in a new tab)

  5. ChatGPT API Reference (opens in a new tab)