मुख्य सामग्री पर जाएं

Python में OpenAI API के जरिए GPT-3.5 और GPT-4 का उपयोग

इस ट्यूटोरियल में, आप सीखेंगे कि OpenAI Python पैकेज के साथ प्रोग्रामेटिक रूप से ChatGPT से बातचीत कैसे करें।
अपडेट किया गया 25 सित॰ 2026  · 14 मि॰ पढ़ें

AI के साथ खोजें

ChatGPTClaudePerplexity

ChatGPT पाठ जनरेट करने के लिए एक अत्याधुनिक बड़ा भाषा मॉडल है। यह पहले से ही लगभग हर तरह का लेखन बदल रहा है—ऐसे ट्यूटोरियल्स से लेकर, स्वचालित रूप से बनी उत्पाद विवरणियाँ, Bing के खोज परिणाम, और ChatGPT for Data Science चीट शीट में बताई गई दर्जनों डेटा उपयोग-स्थितियों तक।

इंटरैक्टिव उपयोग के लिए, ChatGPT का वेब इंटरफ़ेस आदर्श है। हालांकि, OpenAI (जो ChatGPT के पीछे की कंपनी है) के पास एक एप्लिकेशन प्रोग्रामिंग इंटरफ़ेस (API) भी है, जो आपको कोड के जरिए ChatGPT और उनके अन्य मॉडलों से बातचीत करने देता है।

इस ट्यूटोरियल में, आप openai Python पैकेज के साथ प्रोग्रामेटिक रूप से ChatGPT से बातचीत करना सीखेंगे।

ध्यान दें कि GPT API के उपयोग के लिए OpenAI शुल्क लेता है। (कभी-कभी नए उपयोगकर्ताओं को मुफ़्त क्रेडिट दिए जाते हैं, लेकिन किसे क्रेडिट मिलता है और यह ऑफ़र कब तक चलेगा, यह पारदर्शी नहीं है।) इसकी लागत $0.002 / 1000 टोकन है, जहाँ 1000 टोकन लगभग 750 शब्दों के बराबर होते हैं। इस ट्यूटोरियल के सभी उदाहरण एक बार चलाने की लागत 2 अमेरिकी सेंट से कम होनी चाहिए (लेकिन यदि आप कार्यों को दोबारा चलाते हैं, तो हर बार शुल्क लगेगा)।

वेब इंटरफ़ेस की बजाय API कब उपयोग करें?

ChatGPT वेब ऐप GPT मॉडलों के लिए एक बेहतरीन इंटरफ़ेस है। हालांकि, यदि आप AI को किसी डेटा पाइपलाइन या सॉफ़्टवेयर में सम्मिलित करना चाहते हैं, तो API अधिक उपयुक्त है। डेटा प्रैक्टिशनर्स के लिए कुछ संभावित उपयोग-स्थितियाँ:

  • डेटाबेस या किसी अन्य API से डेटा लाकर, फिर GPT से उसका सारांश बनवाना या उस पर रिपोर्ट जनरेट कराना
  • डैशबोर्ड में GPT फ़ंक्शनैलिटी एम्बेड करना ताकि परिणामों का पाठ-आधारित सारांश अपने-आप मिल सके
  • अपने डेटा मार्ट के लिए एक प्राकृतिक भाषा इंटरफ़ेस उपलब्ध कराना
  • scholarly (PyPI, Conda) पैकेज के माध्यम से जर्नल लेख खींचकर शोध करना, और GPT से उनके सारांश बनवाना

OpenAI डेवलपर अकाउंट सेटअप करें

API उपयोग करने के लिए, आपको OpenAI के साथ एक डेवलपर अकाउंट बनाना होगा। इसके लिए आपका ईमेल पता, फ़ोन नंबर, और डेबिट या क्रेडिट कार्ड विवरण तैयार रखें।

इन चरणों का पालन करें:

  1. API साइनअप पेज पर जाएँ।
  2. अपना अकाउंट बनाएँ (आपको अपना ईमेल पता और फ़ोन नंबर देना होगा)।
  3. API keys पेज पर जाएँ।
  4. एक नया सीक्रेट की बनाएँ।
  5. इस की की एक कॉपी सुरक्षित रखें। (यदि आप इसे खो देते हैं, तो की को डिलीट करें और नया बनाएँ।)
  6. Payment Methods पेज पर जाएँ।
  7. 'Add payment method' पर क्लिक करें और अपने कार्ड विवरण भरें।

अपने अकाउंट क्रेडेंशियल्स को सुरक्षित रूप से स्टोर करें

सीक्रेट की को गुप्त रखना आवश्यक है! अन्यथा, दूसरे लोग इसका उपयोग करके API तक पहुँच सकते हैं, और भुगतान आपको करना पड़ेगा। नीचे दिए गए चरण बताते हैं कि DataLab (DataCamp का AI-सक्षम डेटा नोटबुक) में अपनी की को सुरक्षित रूप से कैसे स्टोर करें। यदि आप कोई अन्य प्लेटफ़ॉर्म उपयोग कर रहे हैं, तो उसके दस्तावेज़ देखें। आप सलाह के लिए ChatGPT से भी पूछ सकते हैं। यहाँ एक सुझाया गया प्रॉम्प्ट है:

> आप एक आईटी सुरक्षा विशेषज्ञ हैं। आप एक डेटा वैज्ञानिक से बात कर रहे हैं। API एक्सेस के लिए उपयोग होने वाली प्राइवेट कीज़ को सुरक्षित रूप से स्टोर करने के सर्वोत्तम तरीकों की व्याख्या करें।

  1. अपने DataLab वर्कबुक में, "Environment" पर क्लिक करें
  2. "Environment" के बगल में प्लस चिह्न पर क्लिक करें
  3. "Name" फ़ील्ड में "OPENAI" टाइप करें। "Value" फ़ील्ड में अपनी सीक्रेट की पेस्ट करें
  4. एंवायरनमेंट वेरिएबल्स के इस सेट को कोई नाम दें (यह कुछ भी हो सकता है)
  5. "Create" पर क्लिक करें, और नई इंटीग्रेशन को कनेक्ट करें

Python सेटअप करना

API के जरिए GPT का उपयोग करने के लिए, आपको os और openai Python पैकेज इम्पोर्ट करने होंगे।

यदि आप Jupyter Notebook समाधान (जैसे DataLab) का उपयोग कर रहे हैं, तो IPython.display से कुछ फ़ंक्शंस इम्पोर्ट करना भी मददगार है।

एक उदाहरण yfinance पैकेज का उपयोग स्टॉक की कीमतें प्राप्त करने के लिए भी करता है।

# Import the os package
import os

# Import the openai package
import openai

# From the IPython.display package, import display and Markdown
from IPython.display import display, Markdown

# Import yfinance as yf
import yfinance as yf

दूसरा सेटअप कार्य यह है कि आपने जो एंवायरनमेंट वेरिएबल बनाया है उसे ऐसी जगह सेट करें जहाँ openai पैकेज उसे देख सके।

# Set openai.api_key to the OPENAI environment variable
openai.api_key = os.environ["OPENAI"]

API के जरिए GPT को कॉल करने का कोड पैटर्न

OpenAI API को कॉल करके चैट रिस्पॉन्स पाने का कोड पैटर्न इस प्रकार है:

response = openai.ChatCompletion.create(
              model="MODEL_NAME",
              messages=[{"role": "system", "content": 'SPECIFY HOW THE AI ASSISTANT SHOULD BEHAVE'},
                        {"role": "user", "content": 'SPECIFY WANT YOU WANT THE AI ASSISTANT TO SAY'}
              ])

यहाँ समझने के लिए कुछ बातें हैं।

GPT के लिए OpenAI API मॉडल नाम

मॉडल नाम डेवलपर डॉक्स के Model Overview पेज पर सूचीबद्ध हैं। इस ट्यूटोरियल में, आप gpt-3.5-turbo का उपयोग करेंगे, जो ChatGPT द्वारा उपयोग किया जाने वाला नवीनतम मॉडल है जिसके लिए सार्वजनिक API एक्सेस उपलब्ध है। (जब यह व्यापक रूप से उपलब्ध होगा, तो आपको gpt-4 पर स्विच करना चाहिए।)

OpenAI API GPT संदेश प्रकार

Introduction to the Chat दस्तावेज़ में तीन प्रकार के संदेश वर्णित हैं:

  • system संदेश AI असिस्टेंट के व्यवहार का वर्णन करते हैं। डेटा साइंस उपयोग-स्थितियों के लिए एक उपयोगी सिस्टम संदेश है: "You are a helpful assistant who understands data science."
  • user संदेश बताते हैं कि आप AI असिस्टेंट से क्या कहना चाहते हैं। इस ट्यूटोरियल में हम user संदेशों के उदाहरण देखेंगे
  • assistant संदेश बातचीत में पिछले उत्तरों का वर्णन करते हैं। हम आगे के कार्यों में इंटरैक्टिव बातचीत करना सीखेंगे

पहला संदेश system संदेश होना चाहिए। अतिरिक्त संदेश user और assistant के बीच बारी-बारी से होने चाहिए।

आपकी पहली बातचीत: एक डेटासेट जनरेट करना

नमूना डेटासेट जनरेट करना आपके कोड को अलग-अलग डेटा परिस्थितियों के विरुद्ध परखने या दूसरों को कोड दिखाने के लिए उपयोगी है। GPT से उपयोगी उत्तर पाने के लिए, आपको सटीक होना होगा और अपने डेटासेट के विवरण निर्दिष्ट करने होंगे, जिनमें शामिल हैं:

  • पंक्तियों और स्तंभों की संख्या
  • स्तंभों के नाम
  • प्रत्येक स्तंभ में क्या है, उसका विवरण
  • डेटासेट का आउटपुट प्रारूप

यहाँ डेटासेट बनाने के लिए एक user संदेश का उदाहरण दिया गया है।

Create a small dataset about total sales over the last year. 
The format of the dataset should be a data frame with 12 rows and 2 columns. 
The columns should be called "month" and "total_sales_usd". 
The "month" column should contain the shortened forms of month names 
from "Jan" to "Dec". The "total_sales_usd" column should 
contain random numeric values taken from a normal distribution 
with mean 100000 and standard deviation 5000. Provide Python code to 
generate the dataset, then provide the output in the format of a markdown table.

आइए इस संदेश को पिछले कोड पैटर्न में शामिल करें।

# Define the system message
system_msg = 'You are a helpful assistant who understands data science.'

# Define the user message
user_msg = 'Create a small dataset about total sales over the last year. The format of the dataset should be a data frame with 12 rows and 2 columns. The columns should be called "month" and "total_sales_usd". The "month" column should contain the shortened forms of month names from "Jan" to "Dec". The "total_sales_usd" column should contain random numeric values taken from a normal distribution with mean 100000 and standard deviation 5000. Provide Python code to generate the dataset, then provide the output in the format of a markdown table.'

# Create a dataset using GPT
response = openai.ChatCompletion.create(model="gpt-3.5-turbo",
                                        messages=[{"role": "system", "content": system_msg},
                                         {"role": "user", "content": user_msg}])

जाँचें कि GPT से प्राप्त उत्तर ठीक है

API कॉल "जोखिमपूर्ण" होती हैं क्योंकि समस्याएँ आपके नोटबुक के बाहर भी हो सकती हैं, जैसे इंटरनेट कनेक्टिविटी इश्यू, या डेटा भेजने वाले सर्वर में समस्या, या आपका API क्रेडिट खत्म हो जाना। आपको यह जाँचना चाहिए कि मिला हुआ उत्तर ठीक है।

GPT मॉडल चार में से किसी एक वैल्यू वाला स्टेटस कोड लौटाते हैं, जिसका उल्लेख Chat दस्तावेज़ के Response format सेक्शन में है।

  • stop: API ने मॉडल आउटपुट पूरा लौटाया
  • length: max_tokens पैरामीटर या टोकन सीमा के कारण मॉडल आउटपुट अधूरा
  • content_filter: हमारी कंटेंट फ़िल्टर्स के फ़्लैग के कारण सामग्री छोड़ी गई
  • null: API प्रतिक्रिया अभी प्रगति पर है या अधूरी है

GPT API, Python को JSON प्रारूप में डेटा भेजता है, इसलिए response वेरिएबल में गहराई तक नेस्टेड लिस्ट्स और डिक्शनरीज़ होती हैं। इनके साथ काम करना थोड़ा कठिन हो सकता है!

response नामक वेरिएबल के लिए, स्टेटस कोड निम्न स्थान पर स्टोर होता है।

response["choices"][0]["finish_reason"]

AI असिस्टेंट का संदेश निकालें

response वेरिएबल के भीतर वह टेक्स्ट छिपा होता है जिसे हमने GPT से जनरेट करने को कहा था। सौभाग्य से, यह हमेशा एक ही जगह होता है।

response["choices"][0]["message"]["content"]

response का कंटेंट सामान्य रूप से print(content) से प्रिंट किया जा सकता है, लेकिन यह Markdown कंटेंट होता है, जिसे Jupyter notebooks display(Markdown(content)) के जरिए रेंडर कर सकते हैं।

Here's the Python code to generate the dataset:

import numpy as np
import pandas as pd
# Set random seed for reproducibility
np.random.seed(42)
# Generate random sales data
sales_data = np.random.normal(loc=100000, scale=5000, size=12)
# Create month abbreviation list
month_abbr = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
# Create dataframe
sales_df = pd.DataFrame({'month': month_abbr, 'total_sales_usd': sales_data})
# Print dataframe
print(sales_df)

And here's the output in markdown format:

| month | total_sales_usd |

|-------|----------------|

| Jan | 98728.961189 |

| Feb | 106931.030292 |

| Mar | 101599.514152 |

| Apr | 97644.534384 |

| May | 103013.191014 |

| Jun | 102781.514665 |

| Jul | 100157.741173 |

| Aug | 104849.281004 |

| Sep | 100007.081991 |

| Oct | 94080.272682 |

| Nov | 96240.993328 |

| Dec | 104719.371461 |

GPT को कॉल करने के लिए एक हेल्पर फ़ंक्शन उपयोग करें

इन तीन सरल कार्यों के लिए आपको बहुत सारा दोहरावदार बॉयलरप्लेट कोड लिखना पड़ता है। उबाऊ हिस्सों को एब्स्ट्रैक्ट करने के लिए एक रैपर फ़ंक्शन होना उपयोगी है। इस तरह, हम डेटा साइंस उपयोग-स्थितियों पर ध्यान केंद्रित कर सकते हैं।

उम्मीद है, OpenAI अपने Python पैकेज के इंटरफ़ेस को बेहतर बनाएगा ताकि इस तरह की चीज़ें बिल्ट-इन हों। तब तक, आप इसे अपने कोड में निःसंकोच उपयोग करें।

फ़ंक्शन दो आर्ग्युमेंट लेता है।

  • system: सिस्टम संदेश वाला एक स्ट्रिंग।
  • user_assistant: स्ट्रिंग्स का एक एरे जो user संदेश और फिर assistant संदेश के रूप में बारी-बारी से होता है।

रिटर्न वैल्यू जनरेट किया गया कंटेंट है।

def chat(system, user_assistant):
  assert isinstance(system, str), "`system` should be a string"
  assert isinstance(user_assistant, list), "`user_assistant` should be a list"
  system_msg = [{"role": "system", "content": system}]
  user_assistant_msgs = [
      {"role": "assistant", "content": user_assistant[i]} if i % 2 else {"role": "user", "content": user_assistant[i]}
      for i in range(len(user_assistant))]

  msgs = system_msg + user_assistant_msgs
  response = openai.ChatCompletion.create(model="gpt-3.5-turbo",
                                          messages=msgs)
  status_code = response["choices"][0]["finish_reason"]
  assert status_code == "stop", f"The status code was {status_code}."
  return response["choices"][0]["message"]["content"]

इस फ़ंक्शन का उदाहरण उपयोग इस प्रकार है

response_fn_test = chat("You are a machine learning expert.",["Explain what a neural network is."])

display(Markdown(response_fn_test))
A neural network is a type of machine learning model that is inspired by the architecture of the human brain. It consists of layers of interconnected processing units, called neurons, that work together to process and analyze data.

Each neuron receives input from other neurons or from external sources, processes that input using a mathematical function, and then produces an output that is passed on to other neurons in the network.

The structure and behavior of a neural network can be adjusted by changing the weights and biases of the connections between neurons. During the training process, the network learns to recognize patterns and make predictions based on the input it receives.

Neural networks are often used for tasks such as image classification, speech recognition, and natural language processing, and have been shown to be highly effective at solving complex problems that are difficult to solve with traditional rule-based programming methods.

AI असिस्टेंट के उत्तरों का पुन: उपयोग

कई स्थितियों में, आप AI के साथ लंबी बातचीत बनाना चाहेंगे। यानी, आप GPT को एक प्रॉम्प्ट भेजते हैं, जवाब पाते हैं, और चैट जारी रखने के लिए दूसरा प्रॉम्प्ट भेजते हैं। ऐसे में, आपको दूसरी API कॉल में GPT का पिछला जवाब शामिल करना होगा, ताकि GPT के पास पूरा संदर्भ हो। इससे उत्तर की शुद्धता बढ़ेगी और बातचीत भर में स्थिरता बनी रहेगी।

GPT के संदेश का पुन: उपयोग करने के लिए, आप उसे response से प्राप्त करते हैं, और फिर उसे नई चैट कॉल में पास कर देते हैं।

उदाहरण: नमूना डेटासेट का विश्लेषण

आइए पहले जनरेट किए गए डेटासेट के बिक्री स्तंभ का औसत निकालने की कोशिश करें। ध्यान दें कि क्योंकि हमने पहली बार chat() फ़ंक्शन का उपयोग नहीं किया था, इसलिए हमें पिछले response टेक्स्ट तक पहुँचने के लिए लंबा सबसेटिंग कोड उपयोग करना होगा। यदि आप chat() का उपयोग करते हैं, तो कोड सरल होता है।

# Assign the content from the response in Task 1 to assistant_msg
assistant_msg = response["choices"][0]["message"]["content"]

# Define a new user message
user_msg2 = 'Using the dataset you just created, write code to calculate the mean of the `total_sales_usd` column. Also include the result of the calculation.'

# Create an array of user and assistant messages
user_assistant_msgs = [user_msg, assistant_msg, user_msg2]

# Get GPT to perform the request
response_calc = chat(system_msg, user_assistant_msgs)

# Display the generated content
display(Markdown(response_calc))
Sure! Here's the code to calculate the mean of the `total_sales_usd` column: 

```python 
mean_sales = sales_df['total_sales_usd'].mean() 
print("Mean sales: $", round(mean_sales, 2)) 
``` 

And here's the output of this code: 

``` 
Mean sales: $ 100077.57 
``` 

Therefore, the mean of total sales over the last year is about $100,077.57. 

पाइपलाइन में GPT का उपयोग

वेब इंटरफ़ेस की तुलना में API उपयोग करने का एक बड़ा फायदा यह है कि आप GPT को अन्य APIs के साथ जोड़ सकते हैं। एक या अधिक स्रोतों से डेटा खींचना, और फिर उस पर AI लागू करना एक शक्तिशाली वर्कफ़्लो है।

मौसम डेटा पर GPT AI लागू करना

यहाँ, हम weather2 पैकेज (PyPI) से मौसम का पूर्वानुमान लाएँगे और GPT का उपयोग गतिविधियों के सुझाव देने के लिए करेंगे।

# Import the weather2 package
import weather

# Get the forecast for Miami
location = "Miami"
forecast = weather.forecast(location)

# Pull out forecast data for midday tomorrow
fcast = forecast.tomorrow["12:00"]

# Create a prompt
user_msg_weather = f"In {location} at midday tomorrow, the temperature is forecast to be {fcast.temp}, the wind speed is forecast to be {fcast.wind.speed} m/s, and the amount of precipitation is forecast to be {fcast.precip}. Make a list of suitable leisure activities."

# Call GPT
response_activities = chat("You are a travel guide.", [user_msg_weather])

display(Markdown(response_activities))
With mild temperatures and calm winds, Miami is the perfect place for leisure activities. Here are some suggestions:

1. Visit Miami's beaches and soak up some sun or take a dip in the ocean!

2. Explore Miami's art scene with a visit to the Perez Art Museum Miami or the Wynwood Walls.

3. Take a stroll along the famous Ocean Drive and enjoy the colorful Art Deco architecture.

4. Head to Little Havana to experience the Cuban culture and delicious cuisine.

5. Enjoy a scenic walk or bike ride through one of Miami's many parks, such as Bayfront Park or South Pointe Park.

6. Visit the Miami Seaquarium and see some incredible marine life up close.

7. Take a boat tour to see the stunning Miami skyline from the water.

8. Shopping enthusiasts can explore the many high-end boutiques and outdoor shopping malls, such as Lincoln Road Mall.

9. Foodies can venture to one of the many food festivals happening throughout the year.

10. Finally, there are plenty of nightclubs and live music venues to keep the night going.

बहुत बढ़िया! मन तो करता है कि काश मैं कल मियामी में होता!

अगले स्तर पर जाएँ

आप GPT का उपयोग करना Introduction to ChatGPT कोर्स में और सीख सकते हैं। (OpenAI API के साथ काम करने पर एक पूरा कोर्स जल्द ही आ रहा है!)

अभी आपने जो सीखा उसका रेफ़रेंस पाने के लिए, OpenAI API in Python चीट शीट की एक कॉपी लें या Getting Started with the OpenAI API and ChatGPT लाइव ट्रेनिंग की रिकॉर्डिंग देखें।

यदि आप टेक्स्ट-टू-स्पीच ट्रांसक्रिप्शन में रुचि रखते हैं, तो Converting Speech to Text with the OpenAI Whisper API ट्यूटोरियल पढ़ें।

विषय
कृत्रिम बुद्धिमत्ता
Python

शीर्ष Python पाठ्यक्रम

कोर्स

Python परिचय

4 घंटा
7.1M
Python के साथ डेटा विश्लेषण की बुनियादी बातें सिर्फ चार घंटे में सीखें। यह ऑनलाइन पाठ्यक्रम Python इंटरफ़ेस का परिचय देगा और लोकप्रिय पैकेजों का अन्वेषण करेगा।
विवरण देखेंRight Arrow
पाठ्यक्रम शुरू करें
और देखेंRight Arrow