Replies: 1 comment
-
|
Context managers in docs — great question! Why docs often skip them:
# Docs prioritize clarity
client = OpenAI()
response = client.chat.completions.create(...)
# vs more verbose
with OpenAI() as client:
response = client.chat.completions.create(...)
# OpenAI client handles connection pooling
# Context manager not strictly needed for basic use
client = OpenAI() # Connections managed internallyWhen to use context manager: # 1. Explicit cleanup
with OpenAI() as client:
# Client closed after block
response = client.chat.completions.create(...)
# 2. Async with proper cleanup
async with AsyncOpenAI() as client:
response = await client.chat.completions.create(...)
# 3. Testing/short scripts
with OpenAI() as client:
# Ensures cleanup even on error
...Best practice for production: # Long-running app: create once, reuse
client = OpenAI()
# Short script: context manager is fine
with OpenAI() as client:
...We use both patterns at RevolutionAI depending on context. Docs could definitely show more context manager examples for completeness! |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
-
I was wondering why, for example, the Async client with
httpxexample does not use a context manager (here), meanwhile, theaiothhpexample does here .Both cases should clean up clients right? Or the first case is just trying to simplify the code presentation?
Beta Was this translation helpful? Give feedback.
All reactions