Retry के साथ rate limits से बचना
आपने कस्टम मैसेज के साथ Chat Completions चलाने के लिए एक फंक्शन बनाया है, लेकिन आपने देखा कि यह कभी-कभी rate limits की वजह से फेल हो जाता है. आप संभव होने पर errors से बचने के लिए tenacity लाइब्रेरी का @retry डेकोरेटर उपयोग करने का फ़ैसला करते हैं.
यह अभ्यास पाठ्यक्रम का हिस्सा है
OpenAI API के साथ AI सिस्टम बनाना
अभ्यास निर्देश
tenacityलाइब्रेरी से ज़रूरी फंक्शन इम्पोर्ट करें:retry,wait_random_exponential, औरstop_after_attempt.- एक OpenAI API क्लाइंट बनाएँ.
- retry डेकोरेटर्स में वे पैरामीटर भरें जिनसे retry 5 सेकंड के अंतराल से शुरू हो, अधिकतम 40 सेकंड तक जाए, और 4 प्रयासों के बाद रुक जाए.
अगर अभ्यास time out हो जाए, तो सुनिश्चित करें कि interval और attempt के मान ऊपर बताए गए अनुसार बिल्कुल वही हों.
इंटरैक्टिव व्यावहारिक अभ्यास
इस अभ्यास को इस नमूना कोड को पूरा करके आज़माएँ।
# Import the tenacity library
from ____ import ____
client = OpenAI(api_key="")
# Add the appropriate parameters to the decorator
@retry(____, ____)
def get_response(model, message):
response = client.chat.completions.create(
model=model,
messages=[message]
)
return response.choices[0].message.content
print(get_response("gpt-4o-mini", {"role": "user", "content": "List ten holiday destinations."}))