Open-source, secure environment with real-world tools for enterprise-grade agents.
Python agentaiai-agentai-agentscode-interpretercopilotdevelopmentdevtoolsgptgpt-4javascriptllmnextjsopenaipythonreactsoftwaretypescript
refactor(sdk): resolve template config through a bound-opts class hook (#1721)
devin-ai-integration[bot]2be6c12f797f
diff --git a/.changeset/template-bound-connection-opts.md b/.changeset/template-bound-connection-opts.mdnew file mode 100644index 000000000..19ba9880b--- /dev/null+++ b/.changeset/template-bound-connection-opts.md@@ -0,0 +1,6 @@+---+'e2b': patch+'@e2b/python-sdk': patch+---++Internal refactor: the template API operations resolve their connection config through a class-level hook, so a `TemplateBase` subclass can carry bound connection options. No behavior change — `Template` / `AsyncTemplate` keep reading config from per-call options and environment variables. In the Python SDK the terminal template operations (`build`, `build_in_background`, `get_build_status`, `exists`, `alias_exists`, `assign_tags`, `remove_tags`, `get_tags`) became `classmethod`s, with signatures unchanged for callers.diff --git a/packages/js-sdk/src/template/index.ts b/packages/js-sdk/src/template/index.tsindex 8cbb8f2b9..36a16f886 100644--- a/packages/js-sdk/src/template/index.ts+++ b/packages/js-sdk/src/template/index.ts@@ -55,6 +55,34 @@ import {export class TemplateBaseimplements TemplateFromImage, TemplateBuilder, TemplateFinal{+ /**+ * Connection options bound to this class, used as defaults for every+ * operation that talks to the API. Undefined here, so the config comes from+ * per-call options and environment variables; per-client subclasses bind+ * their own options.+ *+ * @internal+ * @hidden+ * @hide+ */+ protected static readonly boundOpts?: Omit<ConnectionOpts, 'signal'>++ /**+ * Layer per-call options over the options bound to the class. Per-call+ * options explicitly set to `undefined` don't clear the bound ones.+ *+ * @internal+ * @hidden+ * @hide+ */+ protected static resolveOpts<T extends ConnectionOpts>(opts?: T): T {+ const perCallOpts = Object.fromEntries(+ Object.entries(opts ?? {}).filter(([, value]) => value !== undefined)+ )++ return { ...this.boundOpts, ...perCallOpts } as T+ }+private defaultBaseImage: string = 'e2bdev/base'private baseImage: string | undefined = this.defaultBaseImageprivate baseTemplate: string | undefined = undefined@@ -158,32 +186,34 @@ export class TemplateBaseoptions)+ const buildOpts = this.resolveOpts(buildOptions)+try {- buildOptions.onBuildLogs?.(new LogEntryStart(new Date(), 'Build started'))+ buildOpts.onBuildLogs?.(new LogEntryStart(new Date(), 'Build started'))const baseTemplate = template as TemplateBase- const config = new ConnectionConfig(buildOptions)+ const config = new ConnectionConfig(buildOpts)const client = new ApiClient(config)- const data = await baseTemplate.build(client, config, name, buildOptions)+ const data = await baseTemplate.build(client, config, name, buildOpts)- buildOptions.onBuildLogs?.(+ buildOpts.onBuildLogs?.(new LogEntry(new Date(), 'info', 'Waiting for logs...'))await waitForBuildFinish(client, {templateID: data.templateId,buildID: data.buildId,- onBuildLogs: buildOptions.onBuildLogs,+ onBuildLogs: buildOpts.onBuildLogs,logsRefreshFrequency: baseTemplate.logsRefreshFrequency,stackTraces: baseTemplate.stackTraces,- signal: buildOptions.signal,+ signal: buildOpts.signal,requestTimeoutMs: config.requestTimeoutMs,})return data} finally {- buildOptions.onBuildLogs?.(new LogEntryEnd(new Date(), 'Build finished'))+ buildOpts.onBuildLogs?.(new LogEntryEnd(new Date(), 'Build finished'))}}@@ -240,10 +270,11 @@ export class TemplateBaseoptions)- const config = new ConnectionConfig(buildOptions)+ const buildOpts = this.resolveOpts(buildOptions)+ const config = new ConnectionConfig(buildOpts)const client = new ApiClient(config)- return (template as TemplateBase).build(client, config, name, buildOptions)+ return (template as TemplateBase).build(client, config, name, buildOpts)}/**@@ -261,7 +292,7 @@ export class TemplateBasedata: Pick<BuildInfo, 'templateId' | 'buildId'>,options?: GetBuildStatusOptions): Promise<TemplateBuildStatusResponse> {- const config = new ConnectionConfig(options)+ const config = new ConnectionConfig(this.resolveOpts(options))const client = new ApiClient(config)return await getBuildStatus(@@ -294,7 +325,7 @@ export class TemplateBasename: string,options?: ConnectionOpts): Promise<boolean> {- return TemplateBase.aliasExists(name, options)+ return this.aliasExists(name, options)}/**@@ -317,7 +348,7 @@ export class TemplateBasealias: string,options?: ConnectionOpts): Promise<boolean> {- const config = new ConnectionConfig(options)+ const config = new ConnectionConfig(this.resolveOpts(options))const client = new ApiClient(config)return checkAliasExists(@@ -349,7 +380,7 @@ export class TemplateBasetags: string | string[],options?: ConnectionOpts): Promise<TemplateTagInfo> {- const config = new ConnectionConfig(options)+ const config = new ConnectionConfig(this.resolveOpts(options))const client = new ApiClient(config)const normalizedTags = Array.isArray(tags) ? tags : [tags]return assignTags(@@ -380,7 +411,7 @@ export class TemplateBasetags: string | string[],options?: ConnectionOpts): Promise<void> {- const config = new ConnectionConfig(options)+ const config = new ConnectionConfig(this.resolveOpts(options))const client = new ApiClient(config)const normalizedTags = Array.isArray(tags) ? tags : [tags]return removeTags(@@ -409,7 +440,7 @@ export class TemplateBasetemplateId: string,options?: ConnectionOpts): Promise<TemplateTag[]> {- const config = new ConnectionConfig(options)+ const config = new ConnectionConfig(this.resolveOpts(options))const client = new ApiClient(config)return getTemplateTags(client,@@ -1275,14 +1306,23 @@ export function Template(options?: TemplateOptions): TemplateFromImage {return new TemplateBase(options)}-Template.build = TemplateBase.build-Template.buildInBackground = TemplateBase.buildInBackground-Template.getBuildStatus = TemplateBase.getBuildStatus-Template.exists = TemplateBase.exists-Template.aliasExists = TemplateBase.aliasExists-Template.assignTags = TemplateBase.assignTags-Template.removeTags = TemplateBase.removeTags-Template.getTags = TemplateBase.getTags+/**+ * The statics resolve their connection options off `this`, so they are bound to+ * `TemplateBase` (which carries no bound options) when re-exposed as plain+ * properties of the `Template` factory function.+ */+function boundToBase<T extends (...args: never[]) => unknown>(fn: T): T {+ return fn.bind(TemplateBase) as T+}++Template.build = boundToBase(TemplateBase.build)+Template.buildInBackground = boundToBase(TemplateBase.buildInBackground)+Template.getBuildStatus = boundToBase(TemplateBase.getBuildStatus)+Template.exists = boundToBase(TemplateBase.exists)+Template.aliasExists = boundToBase(TemplateBase.aliasExists)+Template.assignTags = boundToBase(TemplateBase.assignTags)+Template.removeTags = boundToBase(TemplateBase.removeTags)+Template.getTags = boundToBase(TemplateBase.getTags)Template.toJSON = TemplateBase.toJSONTemplate.toDockerfile = TemplateBase.toDockerfilediff --git a/packages/js-sdk/tests/template/boundOpts.test.ts b/packages/js-sdk/tests/template/boundOpts.test.tsnew file mode 100644index 000000000..855fb2d8b--- /dev/null+++ b/packages/js-sdk/tests/template/boundOpts.test.ts@@ -0,0 +1,165 @@+import { afterAll, afterEach, beforeAll, expect, test } from 'vitest'++import { http, HttpResponse } from 'msw'+import { setupServer } from 'msw/node'++import { BuildOptions, Template, TemplateBase } from '../../src'+import { apiUrl, TEST_API_KEY } from '../setup'++const BOUND_API_KEY = `e2b_${'1'.repeat(40)}`+const BOUND_DOMAIN = 'bound.example.com'++/** Stands in for the per-client `client.Template` — same statics, bound config. */+class BoundTemplate extends TemplateBase {+ protected static readonly boundOpts = {+ apiKey: BOUND_API_KEY,+ domain: BOUND_DOMAIN,+ }+}++const requests: { url: string; apiKey: string | null }[] = []++function recordRequest(request: Request) {+ requests.push({+ url: request.url,+ apiKey: request.headers.get('X-API-KEY'),+ })+}++function boundApiUrl(path: string): string {+ return `https://api.${BOUND_DOMAIN}${path}`+}++const templateTags = [+ {+ tag: 'v1.0',+ buildID: '00000000-0000-0000-0000-000000000000',+ createdAt: '2024-01-15T10:30:00Z',+ },+]++const handlers = [apiUrl, boundApiUrl].flatMap((url) => [+ http.get(url('/templates/:templateID/tags'), ({ request }) => {+ recordRequest(request)+ return HttpResponse.json(templateTags)+ }),+ http.get(url('/templates/aliases/:alias'), ({ request }) => {+ recordRequest(request)+ return HttpResponse.json({ aliases: [], templateID: 'template-id' })+ }),+ http.post(url('/templates/tags'), async ({ request }) => {+ recordRequest(request)+ return HttpResponse.json({+ buildID: '00000000-0000-0000-0000-000000000000',+ tags: ['production'],+ })+ }),+ http.delete(url('/templates/tags'), async ({ request }) => {+ recordRequest(request)+ return new HttpResponse(null, { status: 204 })+ }),+ http.post(url('/v3/templates'), async ({ request }) => {+ recordRequest(request)+ return HttpResponse.json({+ templateID: 'template-id',+ buildID: '00000000-0000-0000-0000-000000000000',+ tags: [],+ })+ }),+ http.post(+ url('/v2/templates/:templateID/builds/:buildID'),+ async ({ request }) => {+ recordRequest(request)+ return HttpResponse.json({}, { status: 202 })+ }+ ),+])++const server = setupServer(...handlers)++beforeAll(() => server.listen({ onUnhandledRequest: 'error' }))+afterAll(() => server.close())+afterEach(() => {+ requests.length = 0+ server.resetHandlers()+})++test('top-level statics resolve config from per-call options', async () => {+ await Template.getTags('my-template-id', { apiKey: TEST_API_KEY })+ await Template.exists('my-template', { apiKey: TEST_API_KEY })+ await Template.assignTags('my-template:v1.0', 'production', {+ apiKey: TEST_API_KEY,+ })+ await Template.removeTags('my-template', 'production', {+ apiKey: TEST_API_KEY,+ })+ await Template.buildInBackground(Template().fromBaseImage(), 'my-template', {+ apiKey: TEST_API_KEY,+ })++ expect(requests.length).toBe(6)+ for (const request of requests) {+ expect(request.apiKey).toBe(TEST_API_KEY)+ expect(request.url).toContain(`api.${process.env.E2B_DOMAIN || 'e2b.app'}`)+ }+})++test('subclass bound options are used as defaults', async () => {+ await BoundTemplate.getTags('my-template-id')+ await BoundTemplate.exists('my-template')+ await BoundTemplate.aliasExists('my-template')+ await BoundTemplate.assignTags('my-template:v1.0', 'production')+ await BoundTemplate.removeTags('my-template', 'production')+ await BoundTemplate.buildInBackground(+ Template().fromBaseImage(),+ 'my-template'+ )++ expect(requests.length).toBe(7)+ for (const request of requests) {+ expect(request.apiKey).toBe(BOUND_API_KEY)+ expect(request.url).toContain(`api.${BOUND_DOMAIN}`)+ }+})++test('per-call options override bound options', async () => {+ await BoundTemplate.getTags('my-template-id', { apiKey: TEST_API_KEY })++ expect(requests).toEqual([+ {+ url: boundApiUrl('/templates/my-template-id/tags'),+ apiKey: TEST_API_KEY,+ },+ ])+})++test('undefined per-call options do not clear bound options', async () => {+ await BoundTemplate.getTags('my-template-id', { apiKey: undefined })++ expect(requests[0].apiKey).toBe(BOUND_API_KEY)+})++test('build options carry the bound options into the build', async () => {+ class ProbeTemplate extends TemplateBase {+ protected static readonly boundOpts = {+ apiKey: BOUND_API_KEY,+ requestTimeoutMs: 1234,+ }++ static probeBuildOpts(options?: BuildOptions) {+ return this.resolveOpts(options)+ }+ }++ // The whole merged object is handed to the build, so file uploads and the+ // build-log polling see the bound request timeout too.+ expect(ProbeTemplate.probeBuildOpts({ tags: ['v1.0'] })).toEqual({+ apiKey: BOUND_API_KEY,+ requestTimeoutMs: 1234,+ tags: ['v1.0'],+ })+ expect(ProbeTemplate.probeBuildOpts({ requestTimeoutMs: 42 })).toEqual({+ apiKey: BOUND_API_KEY,+ requestTimeoutMs: 42,+ })+})diff --git a/packages/python-sdk/e2b/template/main.py b/packages/python-sdk/e2b/template/main.pyindex d984f64ef..ab970c598 100644--- a/packages/python-sdk/e2b/template/main.py+++ b/packages/python-sdk/e2b/template/main.py@@ -3,7 +3,9 @@ import shlexfrom typing import Dict, List, Optional, Union, Literalfrom pathlib import Path+from typing_extensions import Unpack+from e2b.connection_config import ApiParamsfrom e2b.exceptions import BuildException, InvalidArgumentExceptionfrom e2b.template.consts import RESOLVE_SYMLINKSfrom e2b.template.dockerfile_parser import parse_dockerfile@@ -756,6 +758,26 @@ class TemplateBase:_logs_refresh_frequency = 0.2+ _bound_api_params: ApiParams = {}+ """API parameters bound to this class, used as defaults for every operation+ that talks to the API. Empty here, so the config comes from per-call+ parameters and environment variables; per-client subclasses bind their own.++ :meta private:+ """++ @classmethod+ def _resolve_api_params(cls, **opts: Unpack[ApiParams]) -> ApiParams:+ """+ Layer per-call API parameters over the parameters bound to the class.+ Per-call parameters explicitly set to `None` don't clear the bound ones.++ :meta private:+ """+ per_call_opts = {key: value for key, value in opts.items() if value is not None}++ return {**cls._bound_api_params, **per_call_opts}+def __init__(self,file_context_path: Optional[Union[str, Path]] = None,diff --git a/packages/python-sdk/e2b/template_async/main.py b/packages/python-sdk/e2b/template_async/main.pyindex 5c0a2c050..250d8aea3 100644--- a/packages/python-sdk/e2b/template_async/main.py+++ b/packages/python-sdk/e2b/template_async/main.py@@ -188,8 +188,9 @@ class AsyncTemplate(TemplateBase):tags=response_tags,)- @staticmethod+ @classmethodasync def build(+ cls,template: TemplateClass,name: Optional[str] = None,*,@@ -242,12 +243,13 @@ class AsyncTemplate(TemplateBase):))- config = ConnectionConfig(**opts)+ api_params = cls._resolve_api_params(**opts)+ config = ConnectionConfig(**api_params)api_client = get_api_client(config,)- data = await AsyncTemplate._build(+ data = await cls._build(api_client,template,name,@@ -258,7 +260,7 @@ class AsyncTemplate(TemplateBase):on_build_logs=on_build_logs,# Only honor an explicitly set request_timeout for uploads;# otherwise upload_file applies its 1-hour default.- request_timeout=opts.get("request_timeout"),+ request_timeout=api_params.get("request_timeout"),)if on_build_logs:@@ -275,7 +277,7 @@ class AsyncTemplate(TemplateBase):data.template_id,data.build_id,on_build_logs,- logs_refresh_frequency=TemplateBase._logs_refresh_frequency,+ logs_refresh_frequency=cls._logs_refresh_frequency,stack_traces=template._template._stack_traces,)@@ -289,8 +291,9 @@ class AsyncTemplate(TemplateBase):))- @staticmethod+ @classmethodasync def build_in_background(+ cls,template: TemplateClass,name: Optional[str] = None,*,@@ -334,12 +337,13 @@ class AsyncTemplate(TemplateBase):"""name = normalize_build_arguments(name, alias)- config = ConnectionConfig(**opts)+ api_params = cls._resolve_api_params(**opts)+ config = ConnectionConfig(**api_params)api_client = get_api_client(config,)- return await AsyncTemplate._build(+ return await cls._build(api_client,template,name,@@ -350,11 +354,12 @@ class AsyncTemplate(TemplateBase):on_build_logs=on_build_logs,# Only honor an explicitly set request_timeout for uploads;# otherwise upload_file applies its 1-hour default.- request_timeout=opts.get("request_timeout"),+ request_timeout=api_params.get("request_timeout"),)- @staticmethod+ @classmethodasync def get_build_status(+ cls,build_info: BuildInfo,logs_offset: int = 0,**opts: Unpack[ApiParams],@@ -374,7 +379,7 @@ class AsyncTemplate(TemplateBase):status = await AsyncTemplate.get_build_status(build_info, logs_offset=0)```"""- config = ConnectionConfig(**opts)+ config = ConnectionConfig(**cls._resolve_api_params(**opts))api_client = get_api_client(config,)@@ -385,8 +390,9 @@ class AsyncTemplate(TemplateBase):logs_offset,)- @staticmethod+ @classmethodasync def exists(+ cls,name: str,**opts: Unpack[ApiParams],) -> bool:@@ -406,10 +412,11 @@ class AsyncTemplate(TemplateBase):```"""- return await AsyncTemplate.alias_exists(name, **opts)+ return await cls.alias_exists(name, **opts)- @staticmethod+ @classmethodasync def alias_exists(+ cls,alias: str,**opts: Unpack[ApiParams],) -> bool:@@ -430,15 +437,16 @@ class AsyncTemplate(TemplateBase):print('Template exists!')```"""- config = ConnectionConfig(**opts)+ config = ConnectionConfig(**cls._resolve_api_params(**opts))api_client = get_api_client(config,)return await check_alias_exists(api_client, alias)- @staticmethod+ @classmethodasync def assign_tags(+ cls,target_name: str,tags: Union[str, List[str]],**opts: Unpack[ApiParams],@@ -461,7 +469,7 @@ class AsyncTemplate(TemplateBase):result = await AsyncTemplate.assign_tags('my-template:v1.0', ['production', 'stable'])```"""- config = ConnectionConfig(**opts)+ config = ConnectionConfig(**cls._resolve_api_params(**opts))api_client = get_api_client(config,)@@ -469,8 +477,9 @@ class AsyncTemplate(TemplateBase):normalized_tags = [tags] if isinstance(tags, str) else tagsreturn await assign_tags(api_client, target_name, normalized_tags)- @staticmethod+ @classmethodasync def remove_tags(+ cls,name: str,tags: Union[str, List[str]],**opts: Unpack[ApiParams],@@ -492,7 +501,7 @@ class AsyncTemplate(TemplateBase):await AsyncTemplate.remove_tags('my-template', ['production', 'stable'])```"""- config = ConnectionConfig(**opts)+ config = ConnectionConfig(**cls._resolve_api_params(**opts))api_client = get_api_client(config,)@@ -500,8 +509,9 @@ class AsyncTemplate(TemplateBase):normalized_tags = [tags] if isinstance(tags, str) else tagsawait remove_tags(api_client, name, normalized_tags)- @staticmethod+ @classmethodasync def get_tags(+ cls,template_id: str,**opts: Unpack[ApiParams],) -> List[TemplateTag]:@@ -520,7 +530,7 @@ class AsyncTemplate(TemplateBase):print(f"Tag: {tag.tag}, Build: {tag.build_id}, Created: {tag.created_at}")```"""- config = ConnectionConfig(**opts)+ config = ConnectionConfig(**cls._resolve_api_params(**opts))api_client = get_api_client(config,)diff --git a/packages/python-sdk/e2b/template_sync/main.py b/packages/python-sdk/e2b/template_sync/main.pyindex e86d3e7e9..9d397b41b 100644--- a/packages/python-sdk/e2b/template_sync/main.py+++ b/packages/python-sdk/e2b/template_sync/main.py@@ -188,8 +188,9 @@ class Template(TemplateBase):tags=response_tags,)- @staticmethod+ @classmethoddef build(+ cls,template: TemplateClass,name: Optional[str] = None,*,@@ -242,12 +243,14 @@ class Template(TemplateBase):))- config = ConnectionConfig(**opts)+ api_params = cls._resolve_api_params(**opts)++ config = ConnectionConfig(**api_params)api_client = get_api_client(config,)- data = Template._build(+ data = cls._build(api_client,template,name,@@ -258,7 +261,7 @@ class Template(TemplateBase):on_build_logs=on_build_logs,# Only honor an explicitly set request_timeout for uploads;# otherwise upload_file applies its 1-hour default.- request_timeout=opts.get("request_timeout"),+ request_timeout=api_params.get("request_timeout"),)if on_build_logs:@@ -275,7 +278,7 @@ class Template(TemplateBase):data.template_id,data.build_id,on_build_logs,- logs_refresh_frequency=TemplateBase._logs_refresh_frequency,+ logs_refresh_frequency=cls._logs_refresh_frequency,stack_traces=template._template._stack_traces,)@@ -289,8 +292,9 @@ class Template(TemplateBase):))- @staticmethod+ @classmethoddef build_in_background(+ cls,template: TemplateClass,name: Optional[str] = None,*,@@ -334,12 +338,13 @@ class Template(TemplateBase):"""name = normalize_build_arguments(name, alias)- config = ConnectionConfig(**opts)+ api_params = cls._resolve_api_params(**opts)+ config = ConnectionConfig(**api_params)api_client = get_api_client(config,)- return Template._build(+ return cls._build(api_client,template,name,@@ -350,11 +355,12 @@ class Template(TemplateBase):on_build_logs=on_build_logs,# Only honor an explicitly set request_timeout for uploads;# otherwise upload_file applies its 1-hour default.- request_timeout=opts.get("request_timeout"),+ request_timeout=api_params.get("request_timeout"),)- @staticmethod+ @classmethoddef get_build_status(+ cls,build_info: BuildInfo,logs_offset: int = 0,**opts: Unpack[ApiParams],@@ -374,7 +380,7 @@ class Template(TemplateBase):status = Template.get_build_status(build_info, logs_offset=0)```"""- config = ConnectionConfig(**opts)+ config = ConnectionConfig(**cls._resolve_api_params(**opts))api_client = get_api_client(config,)@@ -386,8 +392,9 @@ class Template(TemplateBase):logs_offset,)- @staticmethod+ @classmethoddef exists(+ cls,name: str,**opts: Unpack[ApiParams],) -> bool:@@ -407,10 +414,11 @@ class Template(TemplateBase):```"""- return Template.alias_exists(name, **opts)+ return cls.alias_exists(name, **opts)- @staticmethod+ @classmethoddef alias_exists(+ cls,alias: str,**opts: Unpack[ApiParams],) -> bool:@@ -431,15 +439,16 @@ class Template(TemplateBase):print('Template exists!')```"""- config = ConnectionConfig(**opts)+ config = ConnectionConfig(**cls._resolve_api_params(**opts))api_client = get_api_client(config,)return check_alias_exists(api_client, alias)- @staticmethod+ @classmethoddef assign_tags(+ cls,target_name: str,tags: Union[str, List[str]],**opts: Unpack[ApiParams],@@ -462,7 +471,7 @@ class Template(TemplateBase):result = Template.assign_tags('my-template:v1.0', ['production', 'stable'])```"""- config = ConnectionConfig(**opts)+ config = ConnectionConfig(**cls._resolve_api_params(**opts))api_client = get_api_client(config,)@@ -470,8 +479,9 @@ class Template(TemplateBase):normalized_tags = [tags] if isinstance(tags, str) else tagsreturn assign_tags(api_client, target_name, normalized_tags)- @staticmethod+ @classmethoddef remove_tags(+ cls,name: str,tags: Union[str, List[str]],**opts: Unpack[ApiParams],@@ -493,7 +503,7 @@ class Template(TemplateBase):Template.remove_tags('my-template', ['production', 'stable'])```"""- config = ConnectionConfig(**opts)+ config = ConnectionConfig(**cls._resolve_api_params(**opts))api_client = get_api_client(config,)@@ -501,8 +511,9 @@ class Template(TemplateBase):normalized_tags = [tags] if isinstance(tags, str) else tagsremove_tags(api_client, name, normalized_tags)- @staticmethod+ @classmethoddef get_tags(+ cls,template_id: str,**opts: Unpack[ApiParams],) -> List[TemplateTag]:@@ -521,7 +532,7 @@ class Template(TemplateBase):print(f"Tag: {tag.tag}, Build: {tag.build_id}, Created: {tag.created_at}")```"""- config = ConnectionConfig(**opts)+ config = ConnectionConfig(**cls._resolve_api_params(**opts))api_client = get_api_client(config,)diff --git a/packages/python-sdk/tests/async/template_async/test_bound_api_params.py b/packages/python-sdk/tests/async/template_async/test_bound_api_params.pynew file mode 100644index 000000000..a6d521947--- /dev/null+++ b/packages/python-sdk/tests/async/template_async/test_bound_api_params.py@@ -0,0 +1,169 @@+from unittest.mock import AsyncMock++import pytest++import e2b.template_async.main as template_async_main+from e2b import AsyncTemplate, Template, TemplateTagInfo+from e2b.connection_config import ApiParams+from e2b.template.types import BuildInfo++BOUND_API_KEY = "e2b_" + "1" * 40+BOUND_DOMAIN = "bound.example.com"+PER_CALL_DOMAIN = "per-call.example.com"+++class BoundAsyncTemplate(AsyncTemplate):+ """Stands in for the per-client ``client.Template`` — same statics, bound config."""++ _bound_api_params: ApiParams = {+ "api_key": BOUND_API_KEY,+ "domain": BOUND_DOMAIN,+ }+++def configs(monkeypatch):+ """Capture the connection config each terminal operation resolves."""+ captured = []++ def fake_get_api_client(config, *args, **kwargs):+ captured.append(config)+ return None++ monkeypatch.delenv("E2B_API_URL", raising=False)+ monkeypatch.setattr(template_async_main, "get_api_client", fake_get_api_client)+ monkeypatch.setattr(+ template_async_main, "check_alias_exists", AsyncMock(return_value=True)+ )+ monkeypatch.setattr(+ template_async_main, "get_template_tags", AsyncMock(return_value=[])+ )+ monkeypatch.setattr(+ template_async_main,+ "assign_tags",+ AsyncMock(+ return_value=TemplateTagInfo(build_id="build-id", tags=["production"])+ ),+ )+ monkeypatch.setattr(+ template_async_main, "remove_tags", AsyncMock(return_value=None)+ )++ return captured+++async def test_top_level_template_uses_per_call_params(configs, test_api_key):+ await AsyncTemplate.exists(+ "my-template", api_key=test_api_key, domain=PER_CALL_DOMAIN+ )+ await AsyncTemplate.get_tags(+ "my-template", api_key=test_api_key, domain=PER_CALL_DOMAIN+ )+ await AsyncTemplate.assign_tags(+ "my-template:v1.0",+ "production",+ api_key=test_api_key,+ domain=PER_CALL_DOMAIN,+ )+ await AsyncTemplate.remove_tags(+ "my-template", "production", api_key=test_api_key, domain=PER_CALL_DOMAIN+ )++ assert len(configs) == 4+ for config in configs:+ assert config.api_key == test_api_key+ assert config.domain == PER_CALL_DOMAIN+++async def test_top_level_template_falls_back_to_env(configs, monkeypatch, test_api_key):+ monkeypatch.setenv("E2B_API_KEY", test_api_key)+ monkeypatch.setenv("E2B_DOMAIN", "env.example.com")++ await AsyncTemplate.exists("my-template")++ assert configs[0].api_key == test_api_key+ assert configs[0].domain == "env.example.com"+++async def test_bound_params_are_defaults(configs):+ await BoundAsyncTemplate.exists("my-template")+ await BoundAsyncTemplate.alias_exists("my-template")+ await BoundAsyncTemplate.get_tags("my-template")+ await BoundAsyncTemplate.assign_tags("my-template:v1.0", "production")+ await BoundAsyncTemplate.remove_tags("my-template", "production")++ assert len(configs) == 5+ for config in configs:+ assert config.api_key == BOUND_API_KEY+ assert config.domain == BOUND_DOMAIN+++async def test_per_call_params_override_bound_params(configs, test_api_key):+ await BoundAsyncTemplate.exists(+ "my-template", api_key=test_api_key, domain=PER_CALL_DOMAIN+ )++ assert configs[0].api_key == test_api_key+ assert configs[0].domain == PER_CALL_DOMAIN+++async def test_none_per_call_params_keep_bound_params(configs):+ await BoundAsyncTemplate.exists("my-template", api_key=None, domain=None)++ assert configs[0].api_key == BOUND_API_KEY+ assert configs[0].domain == BOUND_DOMAIN+++async def test_build_resolves_build_impl_and_config_off_cls(configs, monkeypatch):+ build_info = BuildInfo(+ template_id="template-id",+ build_id="build-id",+ alias="my-template",+ name="my-template",+ tags=[],+ )+ mock_build = AsyncMock(return_value=build_info)+ monkeypatch.setattr(BoundAsyncTemplate, "_build", staticmethod(mock_build))++ assert (+ await BoundAsyncTemplate.build_in_background(+ Template().from_base_image(), "my-template"+ )+ is build_info+ )++ mock_build.assert_awaited_once()+ assert configs[0].api_key == BOUND_API_KEY+ assert configs[0].domain == BOUND_DOMAIN+++async def test_bound_request_timeout_reaches_the_build(configs, monkeypatch):+ class TimeoutAsyncTemplate(AsyncTemplate):+ _bound_api_params: ApiParams = {+ "api_key": BOUND_API_KEY,+ "request_timeout": 12.5,+ }++ mock_build = AsyncMock(+ return_value=BuildInfo(+ template_id="template-id",+ build_id="build-id",+ alias="my-template",+ name="my-template",+ tags=[],+ )+ )+ monkeypatch.setattr(TimeoutAsyncTemplate, "_build", staticmethod(mock_build))++ await TimeoutAsyncTemplate.build_in_background(+ Template().from_base_image(), "my-template"+ )++ assert mock_build.call_args.kwargs["request_timeout"] == 12.5diff --git a/packages/python-sdk/tests/sync/template_sync/test_bound_api_params.py b/packages/python-sdk/tests/sync/template_sync/test_bound_api_params.pynew file mode 100644index 000000000..1e4da0724--- /dev/null+++ b/packages/python-sdk/tests/sync/template_sync/test_bound_api_params.py@@ -0,0 +1,146 @@+from unittest.mock import Mock++import pytest++import e2b.template_sync.main as template_sync_main+from e2b import Template, TemplateTagInfo+from e2b.connection_config import ApiParams+from e2b.template.types import BuildInfo++BOUND_API_KEY = "e2b_" + "1" * 40+BOUND_DOMAIN = "bound.example.com"+PER_CALL_DOMAIN = "per-call.example.com"+++class BoundTemplate(Template):+ """Stands in for the per-client ``client.Template`` — same statics, bound config."""++ _bound_api_params: ApiParams = {+ "api_key": BOUND_API_KEY,+ "domain": BOUND_DOMAIN,+ }+++def configs(monkeypatch):+ """Capture the connection config each terminal operation resolves."""+ captured = []++ def fake_get_api_client(config, *args, **kwargs):+ captured.append(config)+ return None++ monkeypatch.delenv("E2B_API_URL", raising=False)+ monkeypatch.setattr(template_sync_main, "get_api_client", fake_get_api_client)+ monkeypatch.setattr(+ template_sync_main, "check_alias_exists", Mock(return_value=True)+ )+ monkeypatch.setattr(template_sync_main, "get_template_tags", Mock(return_value=[]))+ monkeypatch.setattr(+ template_sync_main,+ "assign_tags",+ Mock(return_value=TemplateTagInfo(build_id="build-id", tags=["production"])),+ )+ monkeypatch.setattr(template_sync_main, "remove_tags", Mock(return_value=None))++ return captured+++def test_top_level_template_uses_per_call_params(configs, test_api_key):+ Template.exists("my-template", api_key=test_api_key, domain=PER_CALL_DOMAIN)+ Template.get_tags("my-template", api_key=test_api_key, domain=PER_CALL_DOMAIN)+ Template.assign_tags(+ "my-template:v1.0",+ "production",+ api_key=test_api_key,+ domain=PER_CALL_DOMAIN,+ )+ Template.remove_tags(+ "my-template", "production", api_key=test_api_key, domain=PER_CALL_DOMAIN+ )++ assert len(configs) == 4+ for config in configs:+ assert config.api_key == test_api_key+ assert config.domain == PER_CALL_DOMAIN+++def test_top_level_template_falls_back_to_env(configs, monkeypatch, test_api_key):+ monkeypatch.setenv("E2B_API_KEY", test_api_key)+ monkeypatch.setenv("E2B_DOMAIN", "env.example.com")++ Template.exists("my-template")++ assert configs[0].api_key == test_api_key+ assert configs[0].domain == "env.example.com"+++def test_bound_params_are_defaults(configs):+ BoundTemplate.exists("my-template")+ BoundTemplate.alias_exists("my-template")+ BoundTemplate.get_tags("my-template")+ BoundTemplate.assign_tags("my-template:v1.0", "production")+ BoundTemplate.remove_tags("my-template", "production")++ assert len(configs) == 5+ for config in configs:+ assert config.api_key == BOUND_API_KEY+ assert config.domain == BOUND_DOMAIN+++def test_per_call_params_override_bound_params(configs, test_api_key):+ BoundTemplate.exists("my-template", api_key=test_api_key, domain=PER_CALL_DOMAIN)++ assert configs[0].api_key == test_api_key+ assert configs[0].domain == PER_CALL_DOMAIN+++def test_none_per_call_params_keep_bound_params(configs):+ BoundTemplate.exists("my-template", api_key=None, domain=None)++ assert configs[0].api_key == BOUND_API_KEY+ assert configs[0].domain == BOUND_DOMAIN+++def test_build_resolves_build_impl_and_config_off_cls(configs, monkeypatch):+ build_info = BuildInfo(+ template_id="template-id",+ build_id="build-id",+ alias="my-template",+ name="my-template",+ tags=[],+ )+ mock_build = Mock(return_value=build_info)+ monkeypatch.setattr(BoundTemplate, "_build", staticmethod(mock_build))++ assert (+ BoundTemplate.build_in_background(Template().from_base_image(), "my-template")+ is build_info+ )++ mock_build.assert_called_once()+ assert configs[0].api_key == BOUND_API_KEY+ assert configs[0].domain == BOUND_DOMAIN+++def test_bound_request_timeout_reaches_the_build(configs, monkeypatch):+ class TimeoutTemplate(Template):+ _bound_api_params: ApiParams = {+ "api_key": BOUND_API_KEY,+ "request_timeout": 12.5,+ }++ mock_build = Mock(+ return_value=BuildInfo(+ template_id="template-id",+ build_id="build-id",+ alias="my-template",+ name="my-template",+ tags=[],+ )+ )+ monkeypatch.setattr(TimeoutTemplate, "_build", staticmethod(mock_build))++ TimeoutTemplate.build_in_background(Template().from_base_image(), "my-template")++ assert mock_build.call_args.kwargs["request_timeout"] == 12.5