Jump to content

Connect SuperML | Leeroopedia MCP: Equip your AI agents with best practices, code verification, and debugging knowledge. Powered by Leeroo — building Organizational Superintelligence. Contact us at founders@leeroo.com.

Implementation:Cohere ai Cohere python Package Init

From Leeroopedia
Revision as of 12:17, 16 February 2026 by Admin (talk | contribs) (Auto-imported from implementations/Cohere_ai_Cohere_python_Package_Init.md)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Knowledge Sources
Domains SDK, API_Client
Last Updated 2026-02-15 14:00 GMT

Overview

The cohere/__init__.py module is the main package entry point for the Cohere Python SDK, using a lazy import mechanism via __getattr__ and importlib.import_module to expose all public types, client classes, errors, and submodules without eagerly loading them at import time.

Description

This file is auto-generated by Fern from the Cohere API definition. It serves as the root namespace for import cohere, making all SDK symbols accessible as top-level attributes. Rather than importing every type and class upfront (which would slow down initial import), it defines a _dynamic_imports dictionary that maps attribute names to their source submodules. When a user accesses any attribute (e.g., cohere.Client), the __getattr__ function intercepts the lookup, finds the correct submodule in the dictionary, and lazily loads it via importlib.import_module.

The module also provides a typing.TYPE_CHECKING block that statically imports all types for IDE autocompletion and type checking tools, ensuring that developers get full IntelliSense support without incurring runtime import costs.

Key components of this module:

  • _dynamic_imports dictionary -- Maps ~300 symbol names to their source submodules (e.g., "Client": ".client", "AsyncClient": ".client", "ApiMeta": ".types").
  • __getattr__ function -- Intercepts attribute access on the module and dynamically imports the requested symbol from the correct submodule. If the module name matches f".{attr_name}", it returns the module itself (for subpackages like batches, connectors); otherwise, it extracts the attribute from the loaded module.
  • __dir__ function -- Returns a sorted list of all available lazy attributes, enabling tab-completion in interactive environments.
  • __all__ list -- Enumerates all public exports for from cohere import * usage.

Usage

This module is used implicitly whenever a user writes import cohere. It provides the single entry point for accessing all SDK functionality including client classes, type definitions, error classes, and subpackage namespaces. Users do not interact with this module directly beyond the standard import statement.

Code Reference

Source Location

Signature

# Lazy import mechanism
_dynamic_imports: typing.Dict[str, str] = {
    "Client": ".client",
    "AsyncClient": ".client",
    "ClientV2": ".client_v2",
    "AsyncClientV2": ".client_v2",
    "AwsClient": ".aws_client",
    "BedrockClient": ".bedrock_client",
    "BedrockClientV2": ".bedrock_client",
    "SagemakerClient": ".sagemaker_client",
    "SagemakerClientV2": ".sagemaker_client",
    "__version__": ".version",
    "batches": ".batches",
    "connectors": ".connectors",
    "datasets": ".datasets",
    "embed_jobs": ".embed_jobs",
    "finetuning": ".finetuning",
    "models": ".models",
    "v2": ".v2",
    # ... plus ~280 type mappings to ".types"
}

def __getattr__(attr_name: str) -> typing.Any:
    module_name = _dynamic_imports.get(attr_name)
    if module_name is None:
        raise AttributeError(...)
    module = import_module(module_name, __package__)
    if module_name == f".{attr_name}":
        return module
    else:
        return getattr(module, attr_name)

def __dir__():
    lazy_attrs = list(_dynamic_imports.keys())
    return sorted(lazy_attrs)

Import

import cohere

# All top-level symbols are accessible via lazy loading:
from cohere import Client, AsyncClient, ClientV2, AsyncClientV2

I/O Contract

Inputs

Name Type Required Description
attr_name str Yes The name of the attribute being accessed on the cohere module. Looked up in the _dynamic_imports dictionary to determine the source submodule.

Outputs

Name Type Description
(attribute) typing.Any The dynamically imported class, type, error, or submodule corresponding to the requested attribute name. For subpackages (e.g., batches, connectors), the module object itself is returned. For all other symbols, the specific attribute is extracted from the loaded module.

Key Exports

Category Examples Source Module
Client Classes Client, AsyncClient, ClientV2, AsyncClientV2 .client, .client_v2
Platform Clients AwsClient, BedrockClient, BedrockClientV2, SagemakerClient, SagemakerClientV2 .aws_client, .bedrock_client, .sagemaker_client
Type Definitions ApiMeta, ChatMessage, EmbedResponse, RerankResponse, etc. (~280 types) .types
Error Classes BadRequestError, UnauthorizedError, ForbiddenError, NotFoundError, InternalServerError, TooManyRequestsError, etc. .errors
Subpackages batches, connectors, datasets, embed_jobs, finetuning, models, v2 respective submodules
Version __version__ .version

Usage Examples

# Basic client instantiation via the lazy-loaded Client class
import cohere

client = cohere.Client(
    client_name="my-app",
    token="YOUR_API_TOKEN",
)

# Access type definitions directly from the top-level namespace
batch = cohere.Batch(
    name="my-batch",
    input_dataset_id="dataset-123",
    model="command",
)

# Use the async client
async_client = cohere.AsyncClient(
    client_name="my-app",
    token="YOUR_API_TOKEN",
)

# Access subpackages
from cohere.batches import Batch
from cohere.connectors import ConnectorsClient

# Check SDK version
print(cohere.__version__)

Related Pages

Page Connections

Double-click a node to navigate. Hold to expand connections.
Principle
Implementation
Heuristic
Environment