init()
The init()
function initializes the Gentrace SDK with your API credentials and configuration options. This function must be called early in your application setup to configure the SDK globally before using any other Gentrace functionality.
Basic usage
- TypeScript
- Python
typescript
import { init } from 'gentrace';// Basic initialization with API keyinit({apiKey: 'your-gentrace-api-key'});// Or using environment variableinit({apiKey: process.env.GENTRACE_API_KEY});
python
from gentrace import init# Basic initialization with API keyinit(api_key="your-gentrace-api-key")# Or using environment variableimport osfrom gentrace import initinit(api_key=os.environ["GENTRACE_API_KEY"])
Overview
The init()
function:
- Configures authentication with your Gentrace API key
- Sets up global client instances for making API requests
- Establishes connection settings like base URL, timeouts, and retry behavior
- Enables SDK functionality by making other Gentrace functions available
Parameters
The parameters and client options described in this section are automatically generated by the Stainless API SDK generation platform.
- TypeScript
- Python
Function Signature
typescript
function init(options: ClientOptions = {}): void
ClientOptions
typescript
interface ClientOptions {apiKey?: string;baseURL?: string | null;timeout?: number;maxRetries?: number;defaultHeaders?: HeadersLike;defaultQuery?: Record<string, string | undefined>;logLevel?: LogLevel;logger?: Logger;fetchOptions?: RequestInit;fetch?: Fetch;}
Parameters
apiKey
(string, optional): Your Gentrace API key. If not provided, the SDK will attempt to use theGENTRACE_API_KEY
environment variablebaseURL
(string, optional): Override the default base URL for the API. Defaults toGENTRACE_BASE_URL
environment variable orhttps://gentrace.ai/api
. This is particularly useful for self-hosted Gentrace instances (e.g.,http://self-hosted-gentrace.example.com/api
)timeout
(number, optional): Maximum time in milliseconds to wait for a response from the server before timing out a single requestmaxRetries
(number, optional): Maximum number of times to retry a request in case of temporary failure. Default:2
defaultHeaders
(object, optional): Default headers to include with every request to the APIdefaultQuery
(object, optional): Default query parameters to include with every request to the APIlogLevel
(LogLevel, optional): Set the log level. Defaults toGENTRACE_LOG
environment variable or'warn'
logger
(Logger, optional): Custom logger instance. Defaults toglobalThis.console
fetchOptions
(RequestInit, optional): Additional options to be passed tofetch
callsfetch
(Fetch, optional): Customfetch
function implementation
Function Signature
python
def init(*,api_key: Optional[str] = None,base_url: Optional[str] = None,**kwargs: Any) -> None
Parameters
api_key
(str, optional): Your Gentrace API key. If not provided, the SDK will attempt to use theGENTRACE_API_KEY
environment variablebase_url
(str, optional): Override the default base URL for the API. Defaults toGENTRACE_BASE_URL
environment variable orhttps://gentrace.ai/api
. This is particularly useful for self-hosted Gentrace instances (e.g.,http://self-hosted-gentrace.example.com/api
)kwargs
(Any): Additional keyword arguments passed to the underlying client constructors
Additional Options (via kwargs)
timeout
(float | Timeout, optional): Maximum time to wait for a response from the servermax_retries
(int, optional): Maximum number of times to retry a request in case of temporary failure. Default:2
default_headers
(Mapping[str, str], optional): Default headers to include with every request to the APIdefault_query
(Mapping[str, object], optional): Default query parameters to include with every request to the APIhttp_client
(httpx.Client, optional): Custom HTTP client instance for making requests
Advanced configuration
Custom base URL and timeout
- TypeScript
- Python
typescript
import { init } from 'gentrace';init({apiKey: process.env.GENTRACE_API_KEY,baseURL: 'https://your-custom-domain.com/api',timeout: 30000, // 30 secondsmaxRetries: 5});
python
from gentrace import initimport osinit(api_key=os.environ["GENTRACE_API_KEY"],base_url="https://your-custom-domain.com/api",timeout=30.0, # 30 secondsmax_retries=5)
Custom headers and logging
- TypeScript
- Python
typescript
import { init } from 'gentrace';init({apiKey: process.env.GENTRACE_API_KEY,defaultHeaders: {'X-Custom-Header': 'your-value','User-Agent': 'MyApp/1.0.0'},logLevel: 'debug',logger: console // or your custom logger});
python
from gentrace import initimport osinit(api_key=os.environ["GENTRACE_API_KEY"],default_headers={"X-Custom-Header": "your-value","User-Agent": "MyApp/1.0.0"})
Environment variables
Instead of passing configuration options directly to init()
, you can use environment variables:
GENTRACE_API_KEY
: Your Gentrace API keyGENTRACE_BASE_URL
: Custom base URL for the API (useful for self-hosted instances)GENTRACE_LOG
(TypeScript only): Log level setting
- TypeScript
- Python
bash
# Set environment variablesexport GENTRACE_API_KEY="your-gentrace-api-key"export GENTRACE_BASE_URL="https://your-custom-domain.com/api"export GENTRACE_LOG="debug"
typescript
import { init } from 'gentrace';// Initialize without parameters - uses environment variablesinit();
bash
# Set environment variablesexport GENTRACE_API_KEY="your-gentrace-api-key"export GENTRACE_BASE_URL="https://your-custom-domain.com/api"
python
from gentrace import init# Initialize without parameters - uses environment variablesinit()
Error handling
The init()
function will throw an error if required configuration is missing:
- TypeScript
- Python
typescript
import { init } from 'gentrace';try {init({// Missing apiKey - will throw error if GENTRACE_API_KEY env var not set});} catch (error) {console.error('Failed to initialize Gentrace:', error.message);}
python
from gentrace import init, GentraceErrortry:init()# Missing api_key - will throw error if GENTRACE_API_KEY env var not setexcept GentraceError as e:print(f"Failed to initialize Gentrace: {e}")
Best practices
1. Initialize early
Call init()
as early as possible in your application, before using any other Gentrace functionality:
- TypeScript
- Python
typescript
// At the top of your main application fileimport { init } from 'gentrace';// Initialize firstinit({apiKey: process.env.GENTRACE_API_KEY});// Then import and use other Gentrace functionsimport { experiment, evalOnce } from 'gentrace';
python
# At the top of your main application filefrom gentrace import initimport os# Initialize firstinit(api_key=os.environ["GENTRACE_API_KEY"])# Then use other Gentrace functionsfrom gentrace import experiment, eval
2. Use environment variables
Store sensitive configuration like API keys in environment variables rather than hardcoding them:
bash
# .env fileGENTRACE_API_KEY=your-gentrace-api-keyGENTRACE_BASE_URL=https://gentrace.ai/api
Requirements
- API Key: A valid Gentrace API key is required
- Network Access: The SDK needs to communicate with the Gentrace API
- Environment: Node.js 16+ (TypeScript) or Python 3.8+ (Python)
Related functions
experiment()
- Create testing contexts for grouping evaluationsinteraction()
- Instrument AI functions for tracingevalDataset()
/eval_dataset()
- Run tests against datasetseval()
/evalOnce()
- Run individual test cases