MCPcopy
hub / github.com/langroid/langroid / get_openai_client

Function get_openai_client

langroid/language_models/client_cache.py:74–152  ·  view source on GitHub ↗

Get or create a singleton OpenAI client with the given configuration. Args: api_key: OpenAI API key base_url: Optional base URL for API organization: Optional organization ID timeout: Request timeout default_headers: Optional default headers

(
    api_key: str,
    base_url: Optional[str] = None,
    organization: Optional[str] = None,
    timeout: Union[float, Timeout] = 120.0,
    default_headers: Optional[Dict[str, str]] = None,
    http_client: Optional[Any] = None,
    http_client_config: Optional[Dict[str, Any]] = None,
)

Source from the content-addressed store, hash-verified

72
73
74def get_openai_client(
75 api_key: str,
76 base_url: Optional[str] = None,
77 organization: Optional[str] = None,
78 timeout: Union[float, Timeout] = 120.0,
79 default_headers: Optional[Dict[str, str]] = None,
80 http_client: Optional[Any] = None,
81 http_client_config: Optional[Dict[str, Any]] = None,
82) -> OpenAI:
83 """
84 Get or create a singleton OpenAI client with the given configuration.
85
86 Args:
87 api_key: OpenAI API key
88 base_url: Optional base URL for API
89 organization: Optional organization ID
90 timeout: Request timeout
91 default_headers: Optional default headers
92 http_client: Optional httpx.Client instance
93 http_client_config: Optional config dict for creating httpx.Client
94
95 Returns:
96 OpenAI client instance
97 """
98 if isinstance(timeout, (int, float)):
99 timeout = Timeout(timeout)
100
101 # If http_client is provided directly, don't cache (complex object)
102 if http_client is not None:
103 client = OpenAI(
104 api_key=api_key,
105 base_url=base_url,
106 organization=organization,
107 timeout=timeout,
108 default_headers=default_headers,
109 http_client=http_client,
110 )
111 _all_clients.add(client)
112 return client
113
114 # If http_client_config is provided, create client from config and cache
115 created_http_client = None
116 if http_client_config is not None:
117 try:
118 from httpx import Client
119
120 created_http_client = Client(**http_client_config)
121 except ImportError:
122 raise ValueError(
123 "httpx is required to use http_client_config. "
124 "Install it with: pip install httpx"
125 )
126
127 cache_key = _get_cache_key(
128 "openai",
129 api_key=api_key,
130 base_url=base_url,
131 organization=organization,

Calls 4

_get_cache_keyFunction · 0.85
_get_cached_clientFunction · 0.85
_store_clientFunction · 0.85
addMethod · 0.45

Used in the wild real call sites across dependent graphs

searching dependent graphs…