定制加工
OpenAI Python API library
2025-01-02 18:42

The OpenAI Python library provides convenient access to the OpenAI REST API from any Python 3.8+ application. The library includes type definitions for all request params and response fields, and offers both synchronous and asynchronous clients powered by httpx.

It is generated from our OpenAPI specification with Stainless.

The REST API documentation can be found on platform.openai.com. The full API of this library can be found in api.md.

[!importANT] The SDK was rewritten in v1, which was released November 6th 2023. See the v1 migration guide, which includes scripts to automatically update your code.

pipinstallopenai

The full API of this library can be found in api.md.

 
   

  
      


  
    
        
             
             
        
    
    

While you can provide an keyword argument, we recommend using python-dotenv to add to your file so that your API Key is not stored in source control.

With a hosted image:

  
    
    
        
             
             
                   
                
                     
                      
                
            
        
    

With the image as a base64 encoded string:

  
    
    
        
             
             
                   
                
                     
                      
                
            
        
    

When interacting with the API some actions such as starting a Run and adding files to vector stores are asynchronous and take time to complete. The SDK includes helper functions which will poll the status until it reaches a terminal state and then return the resulting object. If an API method results in an action that could benefit from polling there will be a corresponding version of the method ending in '_and_poll'.

For instance to create a Run and poll until it reaches a terminal state you can run:

  
    
    

More information on the lifecycle of a Run can be found in the Run Lifecycle documentation

When creating and interacting with vector stores, you can use polling helpers to monitor the status of operations. For convenience, we also provide a bulk upload helper to allow you to simultaneously upload several files at once.

   

   
    
    

The SDK also includes helpers to process streams and handle incoming events.

 
    
    
    
  
       
        
             
            

More information on streaming helpers can be found in the dedicated documentation: helpers.md

Simply import instead of and use with each API call:

 
 
   

  
      



    
       
        
            
                 
                 
            
        
        
    



Functionality between the synchronous and asynchronous clients is otherwise identical.

We provide support for streaming responses using Server Side Events (SSE).

   

  

  
    
        
             
             
        
    
    
    

   
       

The async client uses the exact same interface.

 
   

  


  
       
        
           
        
    
        
           



[!importANT] We highly recommend instantiating client instances instead of relying on the global client.

We also expose a global client instance that is accessible in a similar fashion to versions prior to v1.

 


  


  
   

  
    
    
        
             
             
        
    


The API is the exact same as the standard client instance-based API.

This is intended to be used within REPLs or notebooks for faster iteration, not in application code.

We recommend that you always instantiate a client (e.g., with ) in application code because:

  • It can be difficult to reason about where client options are configured
  • It's not possible to change certain client options without potentially causing race conditions
  • It's harder to mock for testing purposes
  • It's not possible to control cleanup of network connections

The Realtime API enables you to build low-latency, multi-modal conversational experiences. It currently supports text and audio as both input and output, as well as function calling through a WebSocket connection.

Under the hood the SDK uses the library to manage connections.

The Realtime API works through a combination of client-sent events and server-sent events. Clients can send events to do things like update session configuration or send text and audio inputs. Server events confirm when audio responses have completed, or when a text response from the model has been received. A full event reference can be found here and a guide can be found here.

Basic text based example:

 
   

  
      

        
          

         
            
                 
                 
                    
            
        
         

            
               
                  

               
                

               
                


However the real magic of the Realtime API is handling audio inputs / outputs, see this example TUI script for a fully fledged example.

Whenever an error occurs, the Realtime API will send an event and the connection will stay open and remain usable. This means you need to handle it yourself, as no errors are raised directly by the SDK when an event comes in.

  

    
    
        
           
            
            
            
            

Nested request parameters are TypedDicts. Responses are Pydantic models which also provide helper methods for things like:

  • Serializing back into JSON,
  • Converting to a dictionary,

Typed requests and responses provide autocomplete and documentation within your editor. If you would like to see type errors in VS Code to help catch bugs earlier, set to .

List methods in the OpenAI API are paginated.

This library provides auto-paginating iterators with each list response, so you do not have to request successive pages manually:

   

  

  

   
    

    
    

Or, asynchronously:

 
   

  


    
      
    
        
        
    
        
    



Alternatively, you can use the , , or methods for more granular control working with pages:

   
    

 
    
       
    


Or just work directly with the returned data:

   
    


  
   
    


Nested parameters are dictionaries, typed using , for example:

   

  

  
    
        
             
             
        
    
    
     

Request parameters that correspond to file uploads can be passed as , a instance or a tuple of .

   
   

  


    
    

The async client uses the exact same interface. If you pass a instance, the file contents will be read asynchronously automatically.

When the library is unable to connect to the API (for example, due to network connection problems or a timeout), a subclass of is raised.

When the API returns a non-success status code (that is, 4xx or 5xx response), a subclass of is raised, containing and properties.

All errors inherit from .

 
   

  


    
        
        
    
   
    
      
   
    
   
    
    
    

Error codes are as followed:

Status Code Error Type 400 401 403 404 422 429 >=500 N/A

For more information on debugging requests, see these docs

All object responses in the SDK provide a property which is added from the response header so that you can quickly log failing requests and report them back to OpenAI.

   
        

  

Note that unlike other properties that use an prefix, the property is public. Unless documented otherwise, all other prefix properties, methods and modules are private.

Certain errors are automatically retried 2 times by default, with a short exponential backoff. Connection errors (for example, due to a network connectivity problem), 408 Request Timeout, 409 Conflict, 429 Rate Limit, and >=500 Internal errors are all retried by default.

You can use the option to configure or disable retry settings:

   


  
    
    




    
        
             
             
        
    
    

By default requests time out after 10 minutes. You can configure this with a option, which accepts a float or an object:

   


  
    
    



  
       




    
        
             
             
        
    
    

On timeout, an is thrown.

Note that requests that time out are retried twice by default.

We use the standard library module.

You can enable logging by setting the environment variable to .

$info

Or to for more verbose logging.

In an API response, a field may be explicitly , or missing entirely; in either case, its value is in this library. You can differentiate the two cases with :

   
      
    
  
    

The "raw" Response object can be accessed by prefixing to any HTTP method call, e.g.,

   

  
  
    
         
         
    
    



    

These methods return an object. This is a legacy class as we're changing it slightly in the next major version.

For the sync client this will mostly be the same with the exception of & will be methods instead of properties. In the async client, all methods will be async.

A migration script will be provided & the migration in general should be smooth.

The above interface eagerly reads the full response body when you make the request, which may not always be what you want.

To stream the response body, use instead, which requires a context manager and only reads the response body once you call , , , , , or . In the async client, these are async methods.

As such, methods return a different object, and the async client returns an object.

 
    
        
             
             
        
    
    
  
    

       
        

The context manager is required so that the response will reliably be closed.

This library is typed for convenient access to the documented API.

If you need to access undocumented endpoints, params, or response properties, the library can still be used.

Undocumented endpoints

To make requests to undocumented endpoints, you can make requests using , , and other http verbs. Options on the client will be respected (such as retries) will be respected when making this request.

 

  
    
    
     



Undocumented request params

If you want to explicitly send an extra param, you can do so with the , , and request options.

Undocumented response properties

To access undocumented response properties, you can access the extra fields like . You can also get all the extra fields on the Pydantic model as a dict with .

You can directly override the httpx client to customize it for your use case, including:

  • Support for proxies
  • Custom transports
  • Additional advanced functionality
 
    

  
    
    
    
        
        
    

You can also customize the client on a per-request basis by using :



By default the library closes underlying HTTP connections whenever the client is garbage collected. You can manually close the client using the method if desired, or with a context manager that closes when exiting.

   

   
  
  


To use this library with Azure OpenAI, use the class instead of the class.

[!importANT] The Azure API shape differs from the core API shape which means that the static types for responses / params won't always be correct.

   


  
    
    
    
    


  
      
    
        
             
             
        
    


In addition to the options provided in the base client, the following options are provided:

  • (or the environment variable)
  • (or the environment variable)
  • (or the environment variable)

An example of using the client with Microsoft Entra ID (formerly known as Azure Active Directory) can be found here.

This package generally follows SemVer conventions, though certain backwards-incompatible changes may be released as minor versions:

  1. Changes that only affect static types, without breaking runtime behavior.
  2. Changes to library internals which are technically public but not intended or documented for external use. (Please open a GitHub issue to let us know if you are relying on such internals).
  3. Changes that we do not expect to impact the vast majority of users in practice.

We take backwards-compatibility seriously and work hard to ensure you can rely on a smooth upgrade experience.

We are keen for your feedback; please open an issue with questions, bugs, or suggestions.

If you've upgraded to the latest version but aren't seeing any new features you were expecting then your python environment is likely still using an older version.

You can determine the version that is being used at runtime with:

 

Python 3.8 or higher.

    以上就是本篇文章【OpenAI Python API library】的全部内容了,欢迎阅览 ! 文章地址:http://ww.kub2b.com/news/19052.html
     栏目首页      相关文章      动态      同类文章      热门文章      网站地图      返回首页 企库往资讯移动站 http://ww.kub2b.com/mobile/ , 查看更多   
最新文章
光威复材2024年下降逾15%,连续两年发生下滑
3月31日晚,(300699.SZ)发布2024年财报,实现营收24.5亿元,同比下降2.69%;归母净利润7.41亿元,同比下降15.12%;扣非净利润6.6
看完超人气游戏改编的《我的世界大电影》,我整个人都方了
观影《我的世界大电影》,感觉自己真的方了。毕竟,已经领略过风靡全球的沙盒游戏《我的世界》中那方块的世界,还有游戏带给人的
手机大脑手机阅读「手机大脑」
为什么只要醒着我们就离不开手机,为什么疫情中的我们更容易自投罗网?为什么比尔·盖茨不让小孩用手机,乔布斯不让孩子碰iPad?
远洋集团(03377):拟3.22亿元出售北京盛永置业投资23%股权
智通财经APP讯,远洋集团(03377)发布公告,于2025年4月11日,卖方(公司全资附属公司北京银港房地产开发有限公司)拟向买方(日照钢
600375,停牌,退市风险解除!
*ST汉马(600375)即将去星摘帽。4月16日晚间,该公司公告,公司股票将于2025年4月17日(星期四)开市起停牌一天,并于2025年4月
300万像素手写滑盖三星G618行货大跌530三星滑盖手机「300万像素手写滑盖三星G618行货大跌530」
  【7月15日太平洋电脑网上海站】今天,三星奥运手机G618行货从2288元跌至新低1758元。530元的降幅对于这款三星众多奥运手机中
最新手机续航TOP10排行榜:小米14垫底,Mate60和iPhone15落榜,第一名让人很意外手机续航排行「最新手机续航TOP10排行榜:小米14垫底,Mate60和iPhone15落榜,第一名让人
随着科技的进步,手机已经成为了我们生活中不可或缺的一部分。而手机续航能力也成为用户选择新机的重要考量因素之一。特别是对于
“好房子”新规激发楼市活力 北京3月新旧房成交量齐增
每经记者:陈梦妤    每经编辑:魏文艺“今年第一季度,我们所有项目均超额完成销售任务,完成率均达100%以上。这一成绩主要
智能手机:重塑现代人生活方式的双刃剑现代手机「智能手机:重塑现代人生活方式的双刃剑」
随着科技的飞速发展,智能手机已经成为现代人生活中不可或缺的一部分。它为我们带来了便捷的信息获取、高效的社交方式以及
10块钱的VR跟7000元的到底有啥区别?部手机「10块钱的VR跟7000元的到底有啥区别?」
步入VR元年,VR的关注度甚至乎呈直线上升,但是还有很多VR小白根本不知道VR为何物。VR频道特设《小白玩VR》系列文章,没看过的,