Skip to content

Integrations and domain reference

Kaggle HTTP integration with explicit authentication and bounded downloads.

(c) Mike Casale 2026. Licensed under the MIT License.

KaggleSettings

Bases: BaseSettings

Credentials read only when constructing a worker adapter.

A KAGGLE_API_TOKEN access token is preferred. The legacy KAGGLE_USERNAME and KAGGLE_KEY pair remains supported.

Source code in agent_k/kaggle.py
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
class KaggleSettings(BaseSettings):
    """Credentials read only when constructing a worker adapter.

    A ``KAGGLE_API_TOKEN`` access token is preferred. The legacy
    ``KAGGLE_USERNAME`` and ``KAGGLE_KEY`` pair remains supported.
    """

    model_config = SettingsConfigDict(env_prefix="KAGGLE_", extra="ignore", populate_by_name=True)
    api_token: SecretStr | None = None
    username: str | None = None
    api_key: SecretStr | None = Field(
        default=None, validation_alias=AliasChoices("KAGGLE_KEY", "KAGGLE_API_KEY")
    )
    base_url: str = "https://www.kaggle.com/api/v1"
    timeout: int = Field(default=60, ge=1)
    max_retries: int = Field(default=3, ge=0, le=10)
    max_download_bytes: int = Field(default=20_000_000_000, ge=1)
    max_listing_pages: int = Field(default=10, ge=1, le=100)

    @model_validator(mode="after")
    def validate_credentials(self) -> Self:
        """Require one complete credential form before any request is attempted."""
        if self.api_token is None and (self.username is None or self.api_key is None):
            raise ValueError(
                "Set KAGGLE_API_TOKEN, or both KAGGLE_USERNAME and KAGGLE_KEY, for Kaggle access"
            )
        return self

validate_credentials

validate_credentials() -> Self

Require one complete credential form before any request is attempted.

Source code in agent_k/kaggle.py
71
72
73
74
75
76
77
78
@model_validator(mode="after")
def validate_credentials(self) -> Self:
    """Require one complete credential form before any request is attempted."""
    if self.api_token is None and (self.username is None or self.api_key is None):
        raise ValueError(
            "Set KAGGLE_API_TOKEN, or both KAGGLE_USERNAME and KAGGLE_KEY, for Kaggle access"
        )
    return self

KaggleAuth

Bases: Auth

Attach Kaggle credentials only to requests addressed to the Kaggle API host.

Downloads redirect to signed object-storage URLs. Scoping credentials by host keeps them out of those requests, including after a followed redirect.

Source code in agent_k/kaggle.py
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
class KaggleAuth(httpx.Auth):
    """Attach Kaggle credentials only to requests addressed to the Kaggle API host.

    Downloads redirect to signed object-storage URLs. Scoping credentials by host
    keeps them out of those requests, including after a followed redirect.
    """

    def __init__(self, settings: KaggleSettings) -> None:
        self._host = urlparse(settings.base_url).hostname
        if settings.api_token is not None:
            self._header = f"Bearer {settings.api_token.get_secret_value()}"
        else:
            assert settings.username is not None and settings.api_key is not None
            pair = f"{settings.username}:{settings.api_key.get_secret_value()}"
            self._header = f"Basic {base64.b64encode(pair.encode()).decode()}"

    def auth_flow(self, request: httpx.Request) -> Generator[httpx.Request, httpx.Response]:
        """Authorize a request when, and only when, it targets the Kaggle API host."""
        if request.url.host == self._host:
            request.headers["Authorization"] = self._header
        yield request

auth_flow

auth_flow(request: Request) -> Generator[Request, Response]

Authorize a request when, and only when, it targets the Kaggle API host.

Source code in agent_k/kaggle.py
 97
 98
 99
100
101
def auth_flow(self, request: httpx.Request) -> Generator[httpx.Request, httpx.Response]:
    """Authorize a request when, and only when, it targets the Kaggle API host."""
    if request.url.host == self._host:
        request.headers["Authorization"] = self._header
    yield request

KaggleAdapter dataclass

Mission-scoped adapter using an injected HTTP client.

The caller owns and closes the client. Non-idempotent submission requests are never retried automatically; an uncertain receipt requires reconciliation.

Source code in agent_k/kaggle.py
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
@dataclass
class KaggleAdapter:
    """Mission-scoped adapter using an injected HTTP client.

    The caller owns and closes the client. Non-idempotent submission requests are
    never retried automatically; an uncertain receipt requires reconciliation.
    """

    config: KaggleSettings
    client: httpx.AsyncClient
    _auth: KaggleAuth = field(init=False, repr=False)

    def __post_init__(self) -> None:
        self._auth = KaggleAuth(self.config)

    @property
    def platform_name(self) -> str:
        """Return the external platform identifier."""
        return "kaggle"

    async def authenticate(self) -> bool:
        """Check credentials and fail immediately on rejected authentication."""
        response = await self._request("GET", "/competitions/list")
        if response.status_code in {401, 403}:
            raise AuthenticationError("kaggle")
        response.raise_for_status()
        return True

    async def search_competitions(
        self,
        categories: list[str] | None = None,
        keywords: list[str] | None = None,
        min_prize: int | None = None,
        active_only: bool = True,
    ) -> AsyncIterator[Competition]:
        """Yield supported competitions matching explicit discovery criteria.

        Listing pages are read until one is empty, repeats earlier results, or the
        configured page limit is reached. Entries with unsupported metrics or
        malformed metadata are skipped rather than guessed.
        """
        seen: set[str] = set()
        for page in range(1, self.config.max_listing_pages + 1):
            response = await self._request("GET", "/competitions/list", params={"page": str(page)})
            response.raise_for_status()
            items = _listing_items(response, "competitions")
            fresh = 0
            for item in items:
                try:
                    competition = _parse_competition(_CompetitionPayload.model_validate(item))
                except ValueError:
                    continue
                if competition.id in seen:
                    continue
                seen.add(competition.id)
                fresh += 1
                if active_only and not competition.is_active:
                    continue
                if categories and competition.competition_type.value not in categories:
                    continue
                if min_prize is not None and (competition.prize_pool or 0) < min_prize:
                    continue
                if keywords and not any(
                    word.lower() in competition.title.lower() for word in keywords
                ):
                    continue
                yield competition
            if not items or not fresh:
                return

    async def get_competition(self, competition_id: str) -> Competition:
        """Fetch exact metadata; unsupported or unknown metrics fail closed."""
        slug = validate_slug(competition_id)
        response = await self._request("GET", "/competitions/list", params={"search": slug})
        response.raise_for_status()
        for item in _listing_items(response, "competitions"):
            try:
                payload = _CompetitionPayload.model_validate(item)
                matches = validate_slug(payload.ref) == slug
            except ValueError:
                # Unrelated malformed search results must not hide the requested entry.
                continue
            if matches:
                return _parse_competition(payload)
        raise CompetitionNotFoundError(slug)

    async def get_competition_by_url(self, url: str) -> Competition:
        """Resolve an exact Kaggle competition URL."""
        return await self.get_competition(validate_slug(url))

    async def get_leaderboard(
        self,
        competition_id: str,
        *,
        limit: int = 100,
    ) -> list[LeaderboardEntry]:
        """Read leaderboard values without inventing missing scores or ranks."""
        slug = validate_slug(competition_id)
        response = await self._request("GET", f"/competitions/{slug}/leaderboard/download")
        self._check_rules(response, slug)
        response.raise_for_status()
        content = response.content
        if zipfile.is_zipfile(io.BytesIO(content)):
            with zipfile.ZipFile(io.BytesIO(content)) as archive:
                names = [name for name in archive.namelist() if name.endswith(".csv")]
                if len(names) != 1:
                    raise ValueError("Leaderboard archive must contain exactly one CSV")
                info = archive.getinfo(names[0])
                if info.file_size > 50_000_000:
                    raise ValueError("Leaderboard archive exceeds size limit")
                content = archive.read(info)
        rows = csv.DictReader(io.StringIO(content.decode("utf-8-sig")))
        entries: list[LeaderboardEntry] = []
        for row in rows:
            if len(entries) >= limit:
                break
            try:
                entries.append(_LeaderboardRow.model_validate(row).to_entry())
            except ValidationError:
                # Teams without a parseable public score are omitted, never estimated.
                continue
        return entries

    async def download_data(self, competition_id: str, destination: str) -> list[str]:
        """Download files beneath a private destination using atomic replacement."""
        slug = validate_slug(competition_id)
        root = Path(destination).resolve()
        root.mkdir(parents=True, exist_ok=True, mode=0o700)
        response = await self._request("GET", f"/competitions/data/list/{slug}")
        self._check_rules(response, slug)
        response.raise_for_status()
        raw = response.json()
        listing = _FileListing.model_validate({"files": raw} if isinstance(raw, list) else raw)
        downloaded: list[str] = []
        total_bytes = 0
        limit = self.config.max_download_bytes
        for item in listing.files:
            path = (root / item.name).resolve()
            if not path.is_relative_to(root) or path == root or Path(item.name).is_absolute():
                raise ValueError("Download name escapes dataset directory")
            path.parent.mkdir(parents=True, exist_ok=True, mode=0o700)
            url = f"{self.config.base_url}/competitions/data/download/{slug}/{quote(item.name)}"
            total_bytes += await self._download(url, path, budget=limit - total_bytes)
            downloaded.append(str(path))
        return downloaded

    async def submit(
        self,
        competition_id: str,
        file_path: str,
        message: str = "",
    ) -> Submission:
        """Upload one explicitly authorized submission, without automatic retries."""
        slug = validate_slug(competition_id)
        path = Path(file_path)
        response = await self._request(
            "POST",
            "/competitions/submission-url",
            fields={
                "competitionName": slug,
                "contentLength": str(path.stat().st_size),
                "lastModifiedEpochSeconds": str(int(path.stat().st_mtime)),
                "fileName": path.name,
            },
        )
        response.raise_for_status()
        upload = _UploadPayload.model_validate(response.json())
        parsed = urlparse(upload.create_url)
        if parsed.scheme != "https" or parsed.hostname != "storage.googleapis.com":
            raise SubmissionError(slug, "Untrusted submission upload endpoint")
        uploaded = await self.client.put(
            upload.create_url,
            content=path.read_bytes(),
            auth=httpx.Auth(),
            timeout=self.config.timeout,
        )
        uploaded.raise_for_status()
        receipt = await self._request(
            "POST",
            f"/competitions/submissions/submit/{slug}",
            fields={
                "competitionName": slug,
                "blobFileTokens": upload.token,
                "submissionDescription": message,
            },
        )
        receipt.raise_for_status()
        reference = _SubmissionReceipt.model_validate(receipt.json())
        return Submission(id=str(reference.ref), competition_id=slug, file_name=path.name)

    async def get_submission_status(self, competition_id: str, submission_id: str) -> Submission:
        """Return only scores actually reported by Kaggle."""
        slug = validate_slug(competition_id)
        response = await self._request("GET", f"/competitions/submissions/list/{slug}")
        response.raise_for_status()
        for raw in _listing_items(response, "submissions"):
            item = _SubmissionPayload.model_validate(raw)
            if str(item.ref) != submission_id:
                continue
            status: Literal["pending", "complete", "error"] = "pending"
            if item.errorDescription:
                status = "error"
            elif item.hasPublicScore:
                status = "complete"
            return Submission(
                id=submission_id,
                competition_id=slug,
                file_name=item.fileName,
                status=status,
                public_score=item.publicScore,
                private_score=item.privateScore,
                error_message=item.errorDescription,
            )
        raise SubmissionError(slug, "Submission receipt not found", submission_id=submission_id)

    async def _download(self, url: str, path: Path, *, budget: int) -> int:
        """Stream one file to ``path`` atomically, retrying interrupted transfers.

        Args:
            url: Kaggle download URL; redirects to signed storage are followed.
            path: Final destination, replaced only after a complete transfer.
            budget: Remaining bytes permitted for this dataset download.

        Returns:
            The number of bytes written for this file.

        Raises:
            ValueError: The file would exceed the remaining byte budget.
            httpx.HTTPError: The transfer still fails after the configured retries.
        """
        temporary = path.with_suffix(path.suffix + ".partial")
        attempts = self.config.max_retries + 1
        for attempt in range(attempts):
            written = 0
            try:
                async with self.client.stream(
                    "GET",
                    url,
                    auth=self._auth,
                    timeout=self.config.timeout,
                    follow_redirects=True,
                ) as stream:
                    if stream.status_code in _RETRYABLE_STATUSES and attempt + 1 < attempts:
                        await asyncio.sleep(_retry_delay(stream, attempt))
                        continue
                    stream.raise_for_status()
                    with temporary.open("xb") as handle:
                        temporary.chmod(0o600)
                        async for chunk in stream.aiter_bytes():
                            written += len(chunk)
                            if written > budget:
                                raise ValueError("Download exceeds configured byte limit")
                            handle.write(chunk)
                temporary.replace(path)
                return written
            except httpx.TransportError:
                if attempt + 1 == attempts:
                    raise
                await asyncio.sleep(min(2**attempt, 30))
            finally:
                temporary.unlink(missing_ok=True)
        raise RuntimeError("Download retry loop terminated without a result")

    async def _request(
        self,
        method: str,
        path: str,
        *,
        fields: dict[str, str] | None = None,
        params: dict[str, str] | None = None,
    ) -> httpx.Response:
        attempts = self.config.max_retries + 1 if method == "GET" else 1
        for attempt in range(attempts):
            try:
                response = await self.client.request(
                    method,
                    self.config.base_url + path,
                    auth=self._auth,
                    params=params,
                    files={key: (None, value) for key, value in fields.items()} if fields else None,
                    timeout=self.config.timeout,
                )
            except httpx.TransportError:
                if attempt + 1 == attempts:
                    raise
                await asyncio.sleep(min(2**attempt, 30))
                continue
            if response.status_code not in _RETRYABLE_STATUSES:
                return response
            if attempt + 1 == attempts:
                if response.status_code == 429:
                    raise RateLimitError("kaggle", "Kaggle rate limit exhausted")
                return response
            await asyncio.sleep(_retry_delay(response, attempt))
        raise RuntimeError("HTTP retry loop terminated without a response")

    @staticmethod
    def _check_rules(response: httpx.Response, slug: str) -> None:
        if response.status_code == 403 and "rules" in response.text.lower():
            raise CompetitionRulesNotAcceptedError(slug)

platform_name property

platform_name: str

Return the external platform identifier.

authenticate async

authenticate() -> bool

Check credentials and fail immediately on rejected authentication.

Source code in agent_k/kaggle.py
182
183
184
185
186
187
188
async def authenticate(self) -> bool:
    """Check credentials and fail immediately on rejected authentication."""
    response = await self._request("GET", "/competitions/list")
    if response.status_code in {401, 403}:
        raise AuthenticationError("kaggle")
    response.raise_for_status()
    return True

search_competitions async

search_competitions(
    categories: list[str] | None = None,
    keywords: list[str] | None = None,
    min_prize: int | None = None,
    active_only: bool = True,
) -> AsyncIterator[Competition]

Yield supported competitions matching explicit discovery criteria.

Listing pages are read until one is empty, repeats earlier results, or the configured page limit is reached. Entries with unsupported metrics or malformed metadata are skipped rather than guessed.

Source code in agent_k/kaggle.py
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
async def search_competitions(
    self,
    categories: list[str] | None = None,
    keywords: list[str] | None = None,
    min_prize: int | None = None,
    active_only: bool = True,
) -> AsyncIterator[Competition]:
    """Yield supported competitions matching explicit discovery criteria.

    Listing pages are read until one is empty, repeats earlier results, or the
    configured page limit is reached. Entries with unsupported metrics or
    malformed metadata are skipped rather than guessed.
    """
    seen: set[str] = set()
    for page in range(1, self.config.max_listing_pages + 1):
        response = await self._request("GET", "/competitions/list", params={"page": str(page)})
        response.raise_for_status()
        items = _listing_items(response, "competitions")
        fresh = 0
        for item in items:
            try:
                competition = _parse_competition(_CompetitionPayload.model_validate(item))
            except ValueError:
                continue
            if competition.id in seen:
                continue
            seen.add(competition.id)
            fresh += 1
            if active_only and not competition.is_active:
                continue
            if categories and competition.competition_type.value not in categories:
                continue
            if min_prize is not None and (competition.prize_pool or 0) < min_prize:
                continue
            if keywords and not any(
                word.lower() in competition.title.lower() for word in keywords
            ):
                continue
            yield competition
        if not items or not fresh:
            return

get_competition async

get_competition(competition_id: str) -> Competition

Fetch exact metadata; unsupported or unknown metrics fail closed.

Source code in agent_k/kaggle.py
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
async def get_competition(self, competition_id: str) -> Competition:
    """Fetch exact metadata; unsupported or unknown metrics fail closed."""
    slug = validate_slug(competition_id)
    response = await self._request("GET", "/competitions/list", params={"search": slug})
    response.raise_for_status()
    for item in _listing_items(response, "competitions"):
        try:
            payload = _CompetitionPayload.model_validate(item)
            matches = validate_slug(payload.ref) == slug
        except ValueError:
            # Unrelated malformed search results must not hide the requested entry.
            continue
        if matches:
            return _parse_competition(payload)
    raise CompetitionNotFoundError(slug)

get_competition_by_url async

get_competition_by_url(url: str) -> Competition

Resolve an exact Kaggle competition URL.

Source code in agent_k/kaggle.py
248
249
250
async def get_competition_by_url(self, url: str) -> Competition:
    """Resolve an exact Kaggle competition URL."""
    return await self.get_competition(validate_slug(url))

get_leaderboard async

get_leaderboard(
    competition_id: str, *, limit: int = 100
) -> list[LeaderboardEntry]

Read leaderboard values without inventing missing scores or ranks.

Source code in agent_k/kaggle.py
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
async def get_leaderboard(
    self,
    competition_id: str,
    *,
    limit: int = 100,
) -> list[LeaderboardEntry]:
    """Read leaderboard values without inventing missing scores or ranks."""
    slug = validate_slug(competition_id)
    response = await self._request("GET", f"/competitions/{slug}/leaderboard/download")
    self._check_rules(response, slug)
    response.raise_for_status()
    content = response.content
    if zipfile.is_zipfile(io.BytesIO(content)):
        with zipfile.ZipFile(io.BytesIO(content)) as archive:
            names = [name for name in archive.namelist() if name.endswith(".csv")]
            if len(names) != 1:
                raise ValueError("Leaderboard archive must contain exactly one CSV")
            info = archive.getinfo(names[0])
            if info.file_size > 50_000_000:
                raise ValueError("Leaderboard archive exceeds size limit")
            content = archive.read(info)
    rows = csv.DictReader(io.StringIO(content.decode("utf-8-sig")))
    entries: list[LeaderboardEntry] = []
    for row in rows:
        if len(entries) >= limit:
            break
        try:
            entries.append(_LeaderboardRow.model_validate(row).to_entry())
        except ValidationError:
            # Teams without a parseable public score are omitted, never estimated.
            continue
    return entries

download_data async

download_data(
    competition_id: str, destination: str
) -> list[str]

Download files beneath a private destination using atomic replacement.

Source code in agent_k/kaggle.py
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
async def download_data(self, competition_id: str, destination: str) -> list[str]:
    """Download files beneath a private destination using atomic replacement."""
    slug = validate_slug(competition_id)
    root = Path(destination).resolve()
    root.mkdir(parents=True, exist_ok=True, mode=0o700)
    response = await self._request("GET", f"/competitions/data/list/{slug}")
    self._check_rules(response, slug)
    response.raise_for_status()
    raw = response.json()
    listing = _FileListing.model_validate({"files": raw} if isinstance(raw, list) else raw)
    downloaded: list[str] = []
    total_bytes = 0
    limit = self.config.max_download_bytes
    for item in listing.files:
        path = (root / item.name).resolve()
        if not path.is_relative_to(root) or path == root or Path(item.name).is_absolute():
            raise ValueError("Download name escapes dataset directory")
        path.parent.mkdir(parents=True, exist_ok=True, mode=0o700)
        url = f"{self.config.base_url}/competitions/data/download/{slug}/{quote(item.name)}"
        total_bytes += await self._download(url, path, budget=limit - total_bytes)
        downloaded.append(str(path))
    return downloaded

submit async

submit(
    competition_id: str, file_path: str, message: str = ""
) -> Submission

Upload one explicitly authorized submission, without automatic retries.

Source code in agent_k/kaggle.py
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
async def submit(
    self,
    competition_id: str,
    file_path: str,
    message: str = "",
) -> Submission:
    """Upload one explicitly authorized submission, without automatic retries."""
    slug = validate_slug(competition_id)
    path = Path(file_path)
    response = await self._request(
        "POST",
        "/competitions/submission-url",
        fields={
            "competitionName": slug,
            "contentLength": str(path.stat().st_size),
            "lastModifiedEpochSeconds": str(int(path.stat().st_mtime)),
            "fileName": path.name,
        },
    )
    response.raise_for_status()
    upload = _UploadPayload.model_validate(response.json())
    parsed = urlparse(upload.create_url)
    if parsed.scheme != "https" or parsed.hostname != "storage.googleapis.com":
        raise SubmissionError(slug, "Untrusted submission upload endpoint")
    uploaded = await self.client.put(
        upload.create_url,
        content=path.read_bytes(),
        auth=httpx.Auth(),
        timeout=self.config.timeout,
    )
    uploaded.raise_for_status()
    receipt = await self._request(
        "POST",
        f"/competitions/submissions/submit/{slug}",
        fields={
            "competitionName": slug,
            "blobFileTokens": upload.token,
            "submissionDescription": message,
        },
    )
    receipt.raise_for_status()
    reference = _SubmissionReceipt.model_validate(receipt.json())
    return Submission(id=str(reference.ref), competition_id=slug, file_name=path.name)

get_submission_status async

get_submission_status(
    competition_id: str, submission_id: str
) -> Submission

Return only scores actually reported by Kaggle.

Source code in agent_k/kaggle.py
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
async def get_submission_status(self, competition_id: str, submission_id: str) -> Submission:
    """Return only scores actually reported by Kaggle."""
    slug = validate_slug(competition_id)
    response = await self._request("GET", f"/competitions/submissions/list/{slug}")
    response.raise_for_status()
    for raw in _listing_items(response, "submissions"):
        item = _SubmissionPayload.model_validate(raw)
        if str(item.ref) != submission_id:
            continue
        status: Literal["pending", "complete", "error"] = "pending"
        if item.errorDescription:
            status = "error"
        elif item.hasPublicScore:
            status = "complete"
        return Submission(
            id=submission_id,
            competition_id=slug,
            file_name=item.fileName,
            status=status,
            public_score=item.publicScore,
            private_score=item.privateScore,
            error_message=item.errorDescription,
        )
    raise SubmissionError(slug, "Submission receipt not found", submission_id=submission_id)

validate_slug

validate_slug(value: str) -> str

Accept a competition slug or canonical Kaggle URL, rejecting other paths.

Source code in agent_k/kaggle.py
480
481
482
483
484
485
486
487
488
489
490
491
492
def validate_slug(value: str) -> str:
    """Accept a competition slug or canonical Kaggle URL, rejecting other paths."""
    if "://" in value:
        parsed = urlparse(value)
        if parsed.scheme != "https" or parsed.hostname not in {"kaggle.com", "www.kaggle.com"}:
            raise ValueError("Expected a Kaggle competition URL")
        match = re.fullmatch(r"/competitions/([A-Za-z0-9-]+)/?", parsed.path)
        if match is None:
            raise ValueError("Invalid Kaggle competition URL")
        value = match.group(1)
    if not re.fullmatch(r"[A-Za-z0-9-]{1,100}", value):
        raise ValueError("Invalid competition slug")
    return value

parse_metric

parse_metric(value: str) -> EvaluationMetric

Normalize known metric names without an accuracy fallback.

Source code in agent_k/kaggle.py
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
def parse_metric(value: str) -> EvaluationMetric:
    """Normalize known metric names without an accuracy fallback."""
    key = re.sub(r"[^a-z0-9]", "", value.lower())
    aliases = {
        "accuracy": EvaluationMetric.ACCURACY,
        "categorizationaccuracy": EvaluationMetric.ACCURACY,
        "auc": EvaluationMetric.AUC,
        "rocauc": EvaluationMetric.AUC,
        "logloss": EvaluationMetric.LOG_LOSS,
        "logarithmicloss": EvaluationMetric.LOG_LOSS,
        "f1": EvaluationMetric.F1,
        "f1score": EvaluationMetric.F1,
        "rmse": EvaluationMetric.RMSE,
        "rootmeansquarederror": EvaluationMetric.RMSE,
        "mae": EvaluationMetric.MAE,
        "meanabsoluteerror": EvaluationMetric.MAE,
        "rmsle": EvaluationMetric.RMSLE,
        "rootmeansquaredlogarithmicerror": EvaluationMetric.RMSLE,
    }
    if key not in aliases:
        raise ValueError(f"Unsupported competition metric: {value}")
    return aliases[key]

Model resolution for AGENT-K agents, performed only at execution time.

(c) Mike Casale 2026. Licensed under the MIT License.

create_devstral_model

create_devstral_model(
    model_id: str = DEVSTRAL_MODEL_ID,
    base_url: str | None = None,
) -> OpenAIChatModel

Create a Devstral model served by a local OpenAI-compatible LM Studio server.

Parameters:

Name Type Description Default
model_id str

Model identifier exposed by the local server.

DEVSTRAL_MODEL_ID
base_url str | None

Explicit server URL; the configured DEVSTRAL_BASE_URL otherwise.

None

Returns:

Type Description
OpenAIChatModel

A chat model bound to the local server. The configured API key is sent only

OpenAIChatModel

to the configured server, never to an explicitly supplied URL.

Source code in agent_k/providers.py
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
def create_devstral_model(
    model_id: str = DEVSTRAL_MODEL_ID,
    base_url: str | None = None,
) -> OpenAIChatModel:
    """Create a Devstral model served by a local OpenAI-compatible LM Studio server.

    Args:
        model_id: Model identifier exposed by the local server.
        base_url: Explicit server URL; the configured ``DEVSTRAL_BASE_URL`` otherwise.

    Returns:
        A chat model bound to the local server. The configured API key is sent only
        to the configured server, never to an explicitly supplied URL.
    """
    configured_url = os.getenv("DEVSTRAL_BASE_URL", DEVSTRAL_BASE_URL)
    url = base_url or configured_url
    key = os.getenv("DEVSTRAL_API_KEY", "not-required") if url == configured_url else "not-required"
    return OpenAIChatModel(model_id, provider=OpenAIProvider(base_url=url, api_key=key))

create_openrouter_model

create_openrouter_model(model_id: str) -> OpenAIChatModel

Create a model routed through OpenRouter's OpenAI-compatible API.

Source code in agent_k/providers.py
59
60
61
def create_openrouter_model(model_id: str) -> OpenAIChatModel:
    """Create a model routed through OpenRouter's OpenAI-compatible API."""
    return OpenAIChatModel(model_id, provider=OpenRouterProvider())

get_model

get_model(model_spec: str) -> Model | str

Resolve one model specification.

Parameters:

Name Type Description Default
model_spec str

devstral:local, devstral:<url>, devstral:<model-id>, openrouter:<model-id>, or any standard Pydantic AI model string.

required

Returns:

Type Description
Model | str

A constructed model for AGENT-K provider prefixes, or the unchanged string

Model | str

for Pydantic AI's own provider resolution.

Source code in agent_k/providers.py
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
def get_model(model_spec: str) -> Model | str:
    """Resolve one model specification.

    Args:
        model_spec: ``devstral:local``, ``devstral:<url>``, ``devstral:<model-id>``,
            ``openrouter:<model-id>``, or any standard Pydantic AI model string.

    Returns:
        A constructed model for AGENT-K provider prefixes, or the unchanged string
        for Pydantic AI's own provider resolution.
    """
    if model_spec.startswith(_DEVSTRAL_PREFIX):
        suffix = model_spec.removeprefix(_DEVSTRAL_PREFIX)
        if suffix == "local":
            return create_devstral_model()
        if suffix.startswith("http"):
            return create_devstral_model(base_url=suffix)
        return create_devstral_model(model_id=suffix)
    if model_spec.startswith(_OPENROUTER_PREFIX):
        return create_openrouter_model(model_spec.removeprefix(_OPENROUTER_PREFIX))
    return model_spec

resolve_model

resolve_model(primary: str, *fallbacks: str) -> Model | str

Resolve an ordered model chain that fails over on provider API errors.

Parameters:

Name Type Description Default
primary str

Preferred model specification.

required
*fallbacks str

Specifications tried in order when the preceding model's provider rejects or cannot serve a request.

()

Returns:

Type Description
Model | str

The single resolved model, or a FallbackModel over the distinct chain.

Raises:

Type Description
ValueError

The primary specification is empty.

Failover covers provider API failures only. Output validation and tool retries stay with the model that produced the response.

Source code in agent_k/providers.py
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
def resolve_model(primary: str, *fallbacks: str) -> Model | str:
    """Resolve an ordered model chain that fails over on provider API errors.

    Args:
        primary: Preferred model specification.
        *fallbacks: Specifications tried in order when the preceding model's
            provider rejects or cannot serve a request.

    Returns:
        The single resolved model, or a ``FallbackModel`` over the distinct chain.

    Raises:
        ValueError: The primary specification is empty.

    Failover covers provider API failures only. Output validation and tool retries
    stay with the model that produced the response.
    """
    if not primary:
        raise ValueError("A primary model specification is required")
    chain = tuple(dict.fromkeys((primary, *(spec for spec in fallbacks if spec))))
    if len(chain) == 1:
        return get_model(primary)
    return FallbackModel(*(get_model(spec) for spec in chain))

is_devstral_model

is_devstral_model(model_spec: str) -> bool

Check if a model specification refers to Devstral.

Source code in agent_k/providers.py
112
113
114
def is_devstral_model(model_spec: str) -> bool:
    """Check if a model specification refers to Devstral."""
    return model_spec.startswith(_DEVSTRAL_PREFIX)

Search tool helpers for AGENT-K agents.

(c) Mike Casale 2026. Licensed under the MIT License.

build_kaggle_search_query

build_kaggle_search_query(query: str) -> str

Build a Kaggle-scoped web search query.

Source code in agent_k/search.py
29
30
31
def build_kaggle_search_query(query: str) -> str:
    """Build a Kaggle-scoped web search query."""
    return f"site:kaggle.com {query}".strip()

build_scholarly_query

build_scholarly_query(
    topic: str, source: str = "all"
) -> str

Build a web search query for academic sources.

Source code in agent_k/search.py
34
35
36
37
38
39
40
41
42
43
def build_scholarly_query(
    topic: str,
    source: str = "all",
) -> str:
    """Build a web search query for academic sources."""
    if source == "arxiv":
        return f"site:arxiv.org {topic}".strip()
    if source == "paperswithcode":
        return f"site:paperswithcode.com {topic}".strip()
    return f"site:arxiv.org OR site:paperswithcode.com {topic}".strip()

create_web_search_tool

create_web_search_tool(
    *,
    search_context_size: Literal[
        "low", "medium", "high"
    ] = "medium",
    user_location: WebSearchUserLocation | None = None,
    blocked_domains: list[str] | None = None,
    allowed_domains: list[str] | None = None,
    max_uses: int | None = None,
) -> WebSearchTool

Create a WebSearchTool with explicit configuration.

Source code in agent_k/search.py
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
def create_web_search_tool(
    *,
    search_context_size: Literal["low", "medium", "high"] = "medium",
    user_location: WebSearchUserLocation | None = None,
    blocked_domains: list[str] | None = None,
    allowed_domains: list[str] | None = None,
    max_uses: int | None = None,
) -> WebSearchTool:
    """Create a WebSearchTool with explicit configuration."""
    return WebSearchTool(
        search_context_size=search_context_size,
        user_location=user_location,
        blocked_domains=blocked_domains,
        allowed_domains=allowed_domains,
        max_uses=max_uses,
    )
prepare_web_search(
    ctx: RunContext[Any],
) -> WebSearchTool | None

Prepare WebSearchTool dynamically based on RunContext.

Source code in agent_k/search.py
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
async def prepare_web_search(
    ctx: RunContext[Any],
) -> WebSearchTool | None:
    """Prepare WebSearchTool dynamically based on RunContext."""
    if ctx.model.system not in {"anthropic", "openai", "google", "groq"}:
        return None
    if OpenAIChatModel is not None and isinstance(ctx.model, OpenAIChatModel):
        return None
    if getattr(ctx.deps, "offline_mode", False):
        return None

    user_location = _coerce_user_location(getattr(ctx.deps, "user_location", None))
    blocked_domains = getattr(ctx.deps, "blocked_domains", None)
    allowed_domains = getattr(ctx.deps, "allowed_domains", None)
    max_uses = getattr(ctx.deps, "search_budget", None)

    return create_web_search_tool(
        user_location=user_location,
        blocked_domains=blocked_domains,
        allowed_domains=allowed_domains,
        max_uses=max_uses,
    )

create_web_fetch_tool

create_web_fetch_tool(
    *,
    allowed_domains: list[str] | None = None,
    blocked_domains: list[str] | None = None,
    max_uses: int | None = None,
    enable_citations: bool = True,
    max_content_tokens: int | None = None,
) -> WebFetchTool

Create a WebFetchTool with explicit configuration.

Source code in agent_k/search.py
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
def create_web_fetch_tool(
    *,
    allowed_domains: list[str] | None = None,
    blocked_domains: list[str] | None = None,
    max_uses: int | None = None,
    enable_citations: bool = True,
    max_content_tokens: int | None = None,
) -> WebFetchTool:
    """Create a WebFetchTool with explicit configuration."""
    return WebFetchTool(
        allowed_domains=allowed_domains,
        blocked_domains=blocked_domains,
        max_uses=max_uses,
        enable_citations=enable_citations,
        max_content_tokens=max_content_tokens,
    )

prepare_web_fetch async

prepare_web_fetch(
    ctx: RunContext[Any],
) -> WebFetchTool | None

Prepare WebFetchTool dynamically based on RunContext.

Source code in agent_k/search.py
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
async def prepare_web_fetch(
    ctx: RunContext[Any],
) -> WebFetchTool | None:
    """Prepare WebFetchTool dynamically based on RunContext."""
    if ctx.model.system not in {"anthropic", "google"}:
        return None
    if getattr(ctx.deps, "offline_mode", False):
        return None

    allowed_domains = getattr(ctx.deps, "allowed_domains", None)
    blocked_domains = getattr(ctx.deps, "blocked_domains", None)
    max_uses = getattr(ctx.deps, "fetch_budget", None)

    return create_web_fetch_tool(
        allowed_domains=allowed_domains, blocked_domains=blocked_domains, max_uses=max_uses
    )

Public Pydantic AI tools for mission-scoped, durable memory records.

(c) Mike Casale 2026. Licensed under the MIT License.

MemoryDeps dataclass

Directory owned by the current mission process.

Source code in agent_k/memory.py
21
22
23
24
25
@dataclass
class MemoryDeps:
    """Directory owned by the current mission process."""

    memory_root: Path

read_memory

read_memory(ctx: RunContext[MemoryDeps], name: str) -> str

Read an existing mission note.

Parameters:

Name Type Description Default
ctx RunContext[MemoryDeps]

Current mission dependencies.

required
name str

A simple note identifier using letters, numbers, or hyphens.

required
Source code in agent_k/memory.py
31
32
33
34
35
36
37
38
39
@memory_toolset.tool
def read_memory(ctx: RunContext[MemoryDeps], name: str) -> str:
    """Read an existing mission note.

    Args:
        ctx: Current mission dependencies.
        name: A simple note identifier using letters, numbers, or hyphens.
    """
    return _note_path(ctx.deps.memory_root, name).read_text(encoding="utf-8")

write_memory

write_memory(
    ctx: RunContext[MemoryDeps], name: str, content: str
) -> str

Atomically write a bounded mission note.

Parameters:

Name Type Description Default
ctx RunContext[MemoryDeps]

Current mission dependencies.

required
name str

A simple note identifier using letters, numbers, or hyphens.

required
content str

Evidence or reasoning to retain for this mission.

required
Source code in agent_k/memory.py
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
@memory_toolset.tool
def write_memory(ctx: RunContext[MemoryDeps], name: str, content: str) -> str:
    """Atomically write a bounded mission note.

    Args:
        ctx: Current mission dependencies.
        name: A simple note identifier using letters, numbers, or hyphens.
        content: Evidence or reasoning to retain for this mission.
    """
    if len(content.encode("utf-8")) > 65536:
        raise ValueError("Memory notes are limited to 64 KiB")
    path = _note_path(ctx.deps.memory_root, name)
    path.parent.mkdir(parents=True, exist_ok=True, mode=0o700)
    temporary = path.with_name(f".{path.name}.{uuid.uuid4().hex}.tmp")
    descriptor = os.open(temporary, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
    with os.fdopen(descriptor, "w", encoding="utf-8") as handle:
        handle.write(content)
        handle.flush()
        os.fsync(handle.fileno())
    temporary.replace(path)
    return name

Protocol definitions for platform adapters.

(c) Mike Casale 2026. Licensed under the MIT License.

PlatformAdapter

Bases: Protocol

Protocol for platform adapters.

Platform adapters provide the interface between AGENT-K and competition platforms (e.g., Kaggle, DrivenData). Implementations must be async-first and handle authentication, rate limiting, and error recovery internally.

Example Implementation

class KaggleAdapter: ... async def search_competitions( ... self, categories: list[str], **kwargs ... ) -> AsyncIterator[Competition]: ... async for comp in self._api.list_competitions(): ... yield Competition.model_validate(comp)

Source code in agent_k/interfaces.py
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
@runtime_checkable
class PlatformAdapter(Protocol):
    """Protocol for platform adapters.

    Platform adapters provide the interface between AGENT-K and competition
    platforms (e.g., Kaggle, DrivenData). Implementations must be async-first
    and handle authentication, rate limiting, and error recovery internally.

    Example Implementation:
        >>> class KaggleAdapter:
        ...     async def search_competitions(
        ...         self, categories: list[str], **kwargs
        ...     ) -> AsyncIterator[Competition]:
        ...         async for comp in self._api.list_competitions():
        ...             yield Competition.model_validate(comp)
    """

    @property
    @abstractmethod
    def platform_name(self) -> str:
        """Unique identifier for the platform."""
        ...

    @abstractmethod
    async def authenticate(self) -> bool:
        """Authenticate with the platform.

        Returns:
            True if authentication successful.

        Raises:
            AuthenticationError: If authentication fails.
        """
        ...

    @abstractmethod
    def search_competitions(
        self,
        categories: list[str] | None = None,
        keywords: list[str] | None = None,
        min_prize: int | None = None,
        active_only: bool = True,
    ) -> AsyncIterator[Competition]:
        """Search for competitions matching criteria.

        Args:
            categories: Filter by competition categories.
            keywords: Keywords to search in title/description.
            min_prize: Minimum prize pool filter.
            active_only: Only return active competitions.

        Yields:
            Competition entities matching criteria.
        """
        ...

    @abstractmethod
    async def get_competition(self, competition_id: str) -> Competition:
        """Get detailed competition information.

        Args:
            competition_id: Unique competition identifier.

        Returns:
            Full Competition entity.

        Raises:
            CompetitionNotFoundError: If competition doesn't exist.
        """
        ...

    @abstractmethod
    async def get_leaderboard(
        self, competition_id: str, *, limit: int = 100
    ) -> list[LeaderboardEntry]:
        """Get competition leaderboard.

        Args:
            competition_id: Target competition.
            limit: Maximum entries to return.

        Returns:
            List of leaderboard entries sorted by rank.
        """
        ...

    @abstractmethod
    async def submit(self, competition_id: str, file_path: str, message: str = "") -> Submission:
        """Submit solution to competition.

        Args:
            competition_id: Target competition.
            file_path: Path to submission file.
            message: Optional submission message.

        Returns:
            Submission entity with initial status.

        Raises:
            SubmissionError: If submission fails.
            DeadlinePassedError: If competition has ended.
        """
        ...

    @abstractmethod
    async def get_submission_status(self, competition_id: str, submission_id: str) -> Submission:
        """Get status of a submission.

        Args:
            competition_id: Competition containing submission.
            submission_id: Submission to check.

        Returns:
            Updated Submission entity.
        """
        ...

    @abstractmethod
    async def download_data(self, competition_id: str, destination: str) -> list[str]:
        """Download competition data files.

        Args:
            competition_id: Target competition.
            destination: Directory to download files to.

        Returns:
            List of downloaded file paths.
        """
        ...

platform_name abstractmethod property

platform_name: str

Unique identifier for the platform.

authenticate abstractmethod async

authenticate() -> bool

Authenticate with the platform.

Returns:

Type Description
bool

True if authentication successful.

Raises:

Type Description
AuthenticationError

If authentication fails.

Source code in agent_k/interfaces.py
43
44
45
46
47
48
49
50
51
52
53
@abstractmethod
async def authenticate(self) -> bool:
    """Authenticate with the platform.

    Returns:
        True if authentication successful.

    Raises:
        AuthenticationError: If authentication fails.
    """
    ...

search_competitions abstractmethod

search_competitions(
    categories: list[str] | None = None,
    keywords: list[str] | None = None,
    min_prize: int | None = None,
    active_only: bool = True,
) -> AsyncIterator[Competition]

Search for competitions matching criteria.

Parameters:

Name Type Description Default
categories list[str] | None

Filter by competition categories.

None
keywords list[str] | None

Keywords to search in title/description.

None
min_prize int | None

Minimum prize pool filter.

None
active_only bool

Only return active competitions.

True

Yields:

Type Description
AsyncIterator[Competition]

Competition entities matching criteria.

Source code in agent_k/interfaces.py
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
@abstractmethod
def search_competitions(
    self,
    categories: list[str] | None = None,
    keywords: list[str] | None = None,
    min_prize: int | None = None,
    active_only: bool = True,
) -> AsyncIterator[Competition]:
    """Search for competitions matching criteria.

    Args:
        categories: Filter by competition categories.
        keywords: Keywords to search in title/description.
        min_prize: Minimum prize pool filter.
        active_only: Only return active competitions.

    Yields:
        Competition entities matching criteria.
    """
    ...

get_competition abstractmethod async

get_competition(competition_id: str) -> Competition

Get detailed competition information.

Parameters:

Name Type Description Default
competition_id str

Unique competition identifier.

required

Returns:

Type Description
Competition

Full Competition entity.

Raises:

Type Description
CompetitionNotFoundError

If competition doesn't exist.

Source code in agent_k/interfaces.py
76
77
78
79
80
81
82
83
84
85
86
87
88
89
@abstractmethod
async def get_competition(self, competition_id: str) -> Competition:
    """Get detailed competition information.

    Args:
        competition_id: Unique competition identifier.

    Returns:
        Full Competition entity.

    Raises:
        CompetitionNotFoundError: If competition doesn't exist.
    """
    ...

get_leaderboard abstractmethod async

get_leaderboard(
    competition_id: str, *, limit: int = 100
) -> list[LeaderboardEntry]

Get competition leaderboard.

Parameters:

Name Type Description Default
competition_id str

Target competition.

required
limit int

Maximum entries to return.

100

Returns:

Type Description
list[LeaderboardEntry]

List of leaderboard entries sorted by rank.

Source code in agent_k/interfaces.py
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
@abstractmethod
async def get_leaderboard(
    self, competition_id: str, *, limit: int = 100
) -> list[LeaderboardEntry]:
    """Get competition leaderboard.

    Args:
        competition_id: Target competition.
        limit: Maximum entries to return.

    Returns:
        List of leaderboard entries sorted by rank.
    """
    ...

submit abstractmethod async

submit(
    competition_id: str, file_path: str, message: str = ""
) -> Submission

Submit solution to competition.

Parameters:

Name Type Description Default
competition_id str

Target competition.

required
file_path str

Path to submission file.

required
message str

Optional submission message.

''

Returns:

Type Description
Submission

Submission entity with initial status.

Raises:

Type Description
SubmissionError

If submission fails.

DeadlinePassedError

If competition has ended.

Source code in agent_k/interfaces.py
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
@abstractmethod
async def submit(self, competition_id: str, file_path: str, message: str = "") -> Submission:
    """Submit solution to competition.

    Args:
        competition_id: Target competition.
        file_path: Path to submission file.
        message: Optional submission message.

    Returns:
        Submission entity with initial status.

    Raises:
        SubmissionError: If submission fails.
        DeadlinePassedError: If competition has ended.
    """
    ...

get_submission_status abstractmethod async

get_submission_status(
    competition_id: str, submission_id: str
) -> Submission

Get status of a submission.

Parameters:

Name Type Description Default
competition_id str

Competition containing submission.

required
submission_id str

Submission to check.

required

Returns:

Type Description
Submission

Updated Submission entity.

Source code in agent_k/interfaces.py
124
125
126
127
128
129
130
131
132
133
134
135
@abstractmethod
async def get_submission_status(self, competition_id: str, submission_id: str) -> Submission:
    """Get status of a submission.

    Args:
        competition_id: Competition containing submission.
        submission_id: Submission to check.

    Returns:
        Updated Submission entity.
    """
    ...

download_data abstractmethod async

download_data(
    competition_id: str, destination: str
) -> list[str]

Download competition data files.

Parameters:

Name Type Description Default
competition_id str

Target competition.

required
destination str

Directory to download files to.

required

Returns:

Type Description
list[str]

List of downloaded file paths.

Source code in agent_k/interfaces.py
137
138
139
140
141
142
143
144
145
146
147
148
@abstractmethod
async def download_data(self, competition_id: str, destination: str) -> list[str]:
    """Download competition data files.

    Args:
        competition_id: Target competition.
        destination: Directory to download files to.

    Returns:
        List of downloaded file paths.
    """
    ...

Core domain models for AGENT-K.

(c) Mike Casale 2026. Licensed under the MIT License.

CompetitionType

Bases: StrEnum

Type of Kaggle competition.

Source code in agent_k/models.py
33
34
35
36
37
38
39
40
class CompetitionType(StrEnum):
    """Type of Kaggle competition."""

    FEATURED = "featured"
    RESEARCH = "research"
    GETTING_STARTED = "getting_started"
    PLAYGROUND = "playground"
    COMMUNITY = "community"

SubjectDomain

Bases: StrEnum

Subject domains for competition classification.

Source code in agent_k/models.py
43
44
45
46
47
48
49
50
51
52
53
54
class SubjectDomain(StrEnum):
    """Subject domains for competition classification."""

    FINANCE = "finance"
    MEDICAL = "medical"
    WEATHER = "weather"
    COMPUTER_VISION = "computer_vision"
    NLP = "nlp"
    TABULAR = "tabular"
    TIME_SERIES = "time_series"
    AUDIO = "audio"
    GEOSPATIAL = "geospatial"

EvaluationMetric

Bases: StrEnum

Standard evaluation metrics for competitions.

Source code in agent_k/models.py
57
58
59
60
61
62
63
64
65
66
67
68
69
class EvaluationMetric(StrEnum):
    """Standard evaluation metrics for competitions."""

    # Classification
    ACCURACY = "accuracy"
    AUC = "auc"
    LOG_LOSS = "logLoss"
    F1 = "f1"

    # Regression
    RMSE = "rmse"
    MAE = "mae"
    RMSLE = "rmsle"

Competition

Bases: BaseModel

Kaggle competition entity.

Represents a competition with all metadata required for evaluation and participation decisions.

Source code in agent_k/models.py
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
class Competition(BaseModel):
    """Kaggle competition entity.

    Represents a competition with all metadata required for evaluation
    and participation decisions.
    """

    model_config = ConfigDict(frozen=True, str_strip_whitespace=True, validate_default=True)
    schema_version: str = Field(default=SCHEMA_VERSION, description="Schema version")
    id: CompetitionId = Field(
        ...,
        min_length=1,
        max_length=100,
        pattern=r"^[a-zA-Z0-9-]+$",
        description="Unique competition identifier (slug)",
    )
    title: str = Field(..., min_length=1, max_length=500, description="Competition display title")
    description: str | None = Field(
        default=None, max_length=10000, description="Competition description"
    )
    competition_type: CompetitionType = Field(..., description="Category of competition")
    metric: EvaluationMetric = Field(..., description="Primary evaluation metric")
    metric_direction: MetricDirection = Field(
        default="maximize", description="Whether higher or lower metric values are better"
    )
    deadline: datetime = Field(..., description="Competition submission deadline (UTC)")
    prize_pool: int | None = Field(default=None, ge=0, description="Total prize pool in USD")
    max_team_size: int = Field(default=1, ge=1, le=100, description="Maximum allowed team size")
    max_daily_submissions: int = Field(default=5, ge=1, description="Maximum submissions per day")
    tags: frozenset[str] = Field(
        default_factory=frozenset, description="Competition tags/categories"
    )
    url: str | None = Field(default=None, description="Full URL to competition page")

    @field_validator("deadline")
    @classmethod
    def validate_deadline_timezone(cls, v: datetime) -> datetime:
        """Ensure deadline has timezone information."""
        if v.tzinfo is None:
            raise ValueError("deadline must be timezone-aware")
        return v

    @computed_field  # type: ignore[prop-decorator]
    @property
    def is_active(self) -> bool:
        """Whether competition is still accepting submissions."""
        return datetime.now(UTC) < self.deadline

    @computed_field  # type: ignore[prop-decorator]
    @property
    def days_remaining(self) -> int:
        """Days until deadline (negative if passed)."""
        delta = self.deadline - datetime.now(UTC)
        return delta.days

is_active property

is_active: bool

Whether competition is still accepting submissions.

days_remaining property

days_remaining: int

Days until deadline (negative if passed).

validate_deadline_timezone classmethod

validate_deadline_timezone(v: datetime) -> datetime

Ensure deadline has timezone information.

Source code in agent_k/models.py
106
107
108
109
110
111
112
@field_validator("deadline")
@classmethod
def validate_deadline_timezone(cls, v: datetime) -> datetime:
    """Ensure deadline has timezone information."""
    if v.tzinfo is None:
        raise ValueError("deadline must be timezone-aware")
    return v

LeaderboardEntry

Bases: BaseModel

Entry in competition leaderboard.

Source code in agent_k/models.py
128
129
130
131
132
133
134
135
136
137
class LeaderboardEntry(BaseModel):
    """Entry in competition leaderboard."""

    model_config = ConfigDict(frozen=True)
    schema_version: str = Field(default=SCHEMA_VERSION, description="Schema version")
    rank: int = Field(..., ge=1, description="Position on leaderboard")
    team_name: str = Field(..., min_length=1, description="Team name")
    score: float = Field(..., description="Public leaderboard score")
    entries: int = Field(default=1, ge=1, description="Number of submissions")
    last_submission: datetime | None = Field(default=None, description="Last submission time")

Submission

Bases: BaseModel

Competition submission entity.

Source code in agent_k/models.py
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
class Submission(BaseModel):
    """Competition submission entity."""

    model_config = ConfigDict(frozen=True)
    schema_version: str = Field(default=SCHEMA_VERSION, description="Schema version")
    id: str = Field(..., description="Unique submission identifier")
    competition_id: CompetitionId = Field(..., description="Target competition")
    file_name: str = Field(..., description="Submission file name")
    submitted_at: datetime = Field(
        default_factory=lambda: datetime.now(UTC), description="Submission timestamp"
    )
    public_score: float | None = Field(
        default=None, description="Public leaderboard score (if evaluated)"
    )
    private_score: float | None = Field(
        default=None, description="Private leaderboard score (after competition ends)"
    )
    status: str = Field(
        default="pending", pattern=r"^(pending|complete|error)$", description="Submission status"
    )
    error_message: str | None = Field(default=None, description="Error message if failed")

MissionCriteria

Bases: BaseModel

Criteria constraining mission execution.

Source code in agent_k/models.py
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
class MissionCriteria(BaseModel):
    """Criteria constraining mission execution."""

    model_config = ConfigDict(
        frozen=True,
        alias_generator=to_camel,
        populate_by_name=True,
        extra="forbid",
    )
    schema_version: str = Field(default=SCHEMA_VERSION, description="Schema version")
    target_competition_types: frozenset[CompetitionType] = Field(
        default=frozenset({CompetitionType.FEATURED, CompetitionType.RESEARCH}),
        description="Target competition types",
    )
    min_prize_pool: int | None = Field(default=None, ge=0, description="Minimum prize pool")
    max_team_size: int | None = Field(default=None, ge=1, description="Maximum team size")
    min_days_remaining: int = Field(default=7, ge=1, description="Minimum days remaining")
    target_domains: frozenset[str] = Field(default_factory=frozenset, description="Target domains")
    exclude_domains: frozenset[str] = Field(
        default_factory=frozenset, description="Excluded domains"
    )
    max_evolution_rounds: int = Field(
        default=100, ge=1, le=MAX_MISSION_EVOLUTION_ROUNDS, description="Max evolution rounds"
    )
    min_improvements_required: int = Field(
        default=0,
        ge=0,
        description="Minimum number of fitness improvements required before submission",
    )
    target_leaderboard_percentile: float = Field(
        default=0.10, ge=0.0, le=1.0, description="Target top N percentile on leaderboard"
    )
    evolution_models: tuple[str, ...] = Field(
        default_factory=tuple, description="Ordered model specs to rotate during evolution"
    )
    enable_kumo: bool = True
    allow_submission: bool = False
    min_evolution_iterations: int = Field(default=1, ge=1, le=200)
    use_openevolve: bool = Field(default=True, description="Deprecated; OpenEvolve is always used")

    @model_validator(mode="after")
    def validate_domains_disjoint(self) -> Self:
        """Ensure target and exclude domains don't overlap."""
        overlap = self.target_domains & self.exclude_domains
        if overlap:
            raise ValueError(f"Domains cannot be both targeted and excluded: {overlap}")
        if self.min_evolution_iterations > self.max_evolution_rounds:
            raise ValueError("Minimum evolution iterations exceed the maximum")
        if self.min_improvements_required > self.max_evolution_rounds:
            raise ValueError("Minimum improvements exceed the available iterations")
        return self

validate_domains_disjoint

validate_domains_disjoint() -> Self

Ensure target and exclude domains don't overlap.

Source code in agent_k/models.py
203
204
205
206
207
208
209
210
211
212
213
@model_validator(mode="after")
def validate_domains_disjoint(self) -> Self:
    """Ensure target and exclude domains don't overlap."""
    overlap = self.target_domains & self.exclude_domains
    if overlap:
        raise ValueError(f"Domains cannot be both targeted and excluded: {overlap}")
    if self.min_evolution_iterations > self.max_evolution_rounds:
        raise ValueError("Minimum evolution iterations exceed the maximum")
    if self.min_improvements_required > self.max_evolution_rounds:
        raise ValueError("Minimum improvements exceed the available iterations")
    return self

Shared lightweight domain types used by API and worker modules.

(c) Mike Casale 2026. Licensed under the MIT License.

Exception hierarchy for AGENT-K system.

(c) Mike Casale 2026. Licensed under the MIT License.

AgentKError

Bases: Exception

Base exception for all AGENT-K errors.

All exceptions in the system inherit from this class, enabling catch-all handling at application boundaries.

Source code in agent_k/exceptions.py
43
44
45
46
47
48
49
50
51
52
53
54
55
class AgentKError(Exception):
    """Base exception for all AGENT-K errors.

    All exceptions in the system inherit from this class, enabling
    catch-all handling at application boundaries.
    """

    def __init__(
        self, message: str, *, context: dict[str, Any] | None = None, recoverable: bool = True
    ) -> None:
        self.context = context or {}
        self.recoverable = recoverable
        super().__init__(message)

AgentError

Bases: AgentKError

Base exception for agent-related errors.

Source code in agent_k/exceptions.py
58
59
class AgentError(AgentKError):
    """Base exception for agent-related errors."""

AgentExecutionError

Bases: AgentError

Raised when agent execution fails.

Source code in agent_k/exceptions.py
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
class AgentExecutionError(AgentError):
    """Raised when agent execution fails."""

    def __init__(
        self,
        agent_name: str,
        message: str,
        *,
        cause: Exception | None = None,
        context: dict[str, Any] | None = None,
    ) -> None:
        self.agent_name = agent_name
        self.cause = cause
        ctx = context or {}
        ctx["agent_name"] = agent_name
        if cause:
            ctx["cause_type"] = type(cause).__name__
        super().__init__(f"[{agent_name}] {message}", context=ctx)

ToolExecutionError

Bases: AgentError

Raised when a tool execution fails.

Source code in agent_k/exceptions.py
82
83
84
85
86
87
88
89
90
91
class ToolExecutionError(AgentError):
    """Raised when a tool execution fails."""

    def __init__(self, tool_name: str, message: str, *, args: dict[str, Any] | None = None) -> None:
        self.tool_name = tool_name
        self.tool_args = args or {}
        super().__init__(
            f"Tool {tool_name} failed: {message}",
            context={"tool_name": tool_name, "args": self.tool_args},
        )

OutputValidationError

Bases: AgentError

Raised when agent output fails validation.

Source code in agent_k/exceptions.py
 94
 95
 96
 97
 98
 99
100
101
102
103
class OutputValidationError(AgentError):
    """Raised when agent output fails validation."""

    def __init__(self, agent_name: str, validation_errors: list[str]) -> None:
        self.agent_name = agent_name
        self.validation_errors = validation_errors
        super().__init__(
            f"[{agent_name}] Output validation failed: {validation_errors}",
            context={"validation_errors": validation_errors},
        )

AdapterError

Bases: AgentKError

Base exception for adapter-related errors.

Source code in agent_k/exceptions.py
106
107
class AdapterError(AgentKError):
    """Base exception for adapter-related errors."""

PlatformConnectionError

Bases: AdapterError

Raised when connection to platform fails.

Source code in agent_k/exceptions.py
110
111
112
113
114
115
116
117
class PlatformConnectionError(AdapterError):
    """Raised when connection to platform fails."""

    def __init__(self, platform: str, message: str) -> None:
        self.platform = platform
        super().__init__(
            f"[{platform}] Connection failed: {message}", context={"platform": platform}
        )

AuthenticationError

Bases: AdapterError

Raised when platform authentication fails.

Source code in agent_k/exceptions.py
120
121
122
123
124
125
126
127
class AuthenticationError(AdapterError):
    """Raised when platform authentication fails."""

    def __init__(self, platform: str, message: str = "Authentication failed") -> None:
        self.platform = platform
        super().__init__(
            f"[{platform}] {message}", context={"platform": platform}, recoverable=False
        )

RateLimitError

Bases: AdapterError

Raised when platform rate limit is exceeded.

Source code in agent_k/exceptions.py
130
131
132
133
134
135
136
137
138
class RateLimitError(AdapterError):
    """Raised when platform rate limit is exceeded."""

    def __init__(self, platform: str, message: str, *, retry_after: int | None = None) -> None:
        self.platform = platform
        self.retry_after = retry_after
        super().__init__(
            f"[{platform}] {message}", context={"platform": platform, "retry_after": retry_after}
        )

CompetitionError

Bases: AgentKError

Base exception for competition-related errors.

Source code in agent_k/exceptions.py
141
142
class CompetitionError(AgentKError):
    """Base exception for competition-related errors."""

CompetitionNotFoundError

Bases: CompetitionError

Raised when competition does not exist.

Source code in agent_k/exceptions.py
145
146
147
148
149
150
151
152
153
154
class CompetitionNotFoundError(CompetitionError):
    """Raised when competition does not exist."""

    def __init__(self, competition_id: str) -> None:
        self.competition_id = competition_id
        super().__init__(
            f"Competition not found: {competition_id}",
            context={"competition_id": competition_id},
            recoverable=False,
        )

CompetitionRulesNotAcceptedError

Bases: CompetitionError

Raised when competition rules have not been accepted.

Source code in agent_k/exceptions.py
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
class CompetitionRulesNotAcceptedError(CompetitionError):
    """Raised when competition rules have not been accepted."""

    def __init__(self, competition_id: str) -> None:
        self.competition_id = competition_id
        rules_url = f"https://www.kaggle.com/competitions/{competition_id}/rules"
        message = (
            f"Competition rules not accepted for {competition_id}. "
            f"Open {rules_url} and accept the rules before downloading data."
        )
        super().__init__(
            message,
            context={"competition_id": competition_id, "rules_url": rules_url},
            recoverable=False,
        )

SubmissionError

Bases: CompetitionError

Raised when submission fails.

Source code in agent_k/exceptions.py
174
175
176
177
178
179
180
181
182
183
184
185
class SubmissionError(CompetitionError):
    """Raised when submission fails."""

    def __init__(
        self, competition_id: str, message: str, *, submission_id: str | None = None
    ) -> None:
        self.competition_id = competition_id
        self.submission_id = submission_id
        super().__init__(
            f"Submission to {competition_id} failed: {message}",
            context={"competition_id": competition_id, "submission_id": submission_id},
        )

DeadlinePassedError

Bases: CompetitionError

Raised when competition deadline has passed.

Source code in agent_k/exceptions.py
188
189
190
191
192
193
194
195
196
197
198
class DeadlinePassedError(CompetitionError):
    """Raised when competition deadline has passed."""

    def __init__(self, competition_id: str, deadline: str) -> None:
        self.competition_id = competition_id
        self.deadline = deadline
        super().__init__(
            f"Competition {competition_id} deadline passed: {deadline}",
            context={"competition_id": competition_id, "deadline": deadline},
            recoverable=False,
        )

EvolutionError

Bases: AgentKError

Base exception for evolution-related errors.

Source code in agent_k/exceptions.py
201
202
class EvolutionError(AgentKError):
    """Base exception for evolution-related errors."""

ConvergenceError

Bases: EvolutionError

Raised when evolution fails to converge within limits.

Source code in agent_k/exceptions.py
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
class ConvergenceError(EvolutionError):
    """Raised when evolution fails to converge within limits."""

    def __init__(self, generations_completed: int, best_fitness: float, reason: str) -> None:
        self.generations_completed = generations_completed
        self.best_fitness = best_fitness
        self.reason = reason
        super().__init__(
            f"Evolution did not converge after {generations_completed} generations: {reason}",
            context={
                "generations_completed": generations_completed,
                "best_fitness": best_fitness,
                "reason": reason,
            },
        )

PopulationExtinctError

Bases: EvolutionError

Raised when all population members fail fitness evaluation.

Source code in agent_k/exceptions.py
222
223
224
225
226
227
228
229
230
231
232
class PopulationExtinctError(EvolutionError):
    """Raised when all population members fail fitness evaluation."""

    def __init__(self, generation: int, last_error: str) -> None:
        self.generation = generation
        self.last_error = last_error
        super().__init__(
            f"Population extinct at generation {generation}: {last_error}",
            context={"generation": generation, "last_error": last_error},
            recoverable=False,
        )

FitnessEvaluationError

Bases: EvolutionError

Raised when fitness evaluation fails.

Source code in agent_k/exceptions.py
235
236
237
238
239
240
241
242
243
244
245
246
class FitnessEvaluationError(EvolutionError):
    """Raised when fitness evaluation fails."""

    def __init__(
        self, solution_id: str, message: str, *, execution_error: str | None = None
    ) -> None:
        self.solution_id = solution_id
        self.execution_error = execution_error
        super().__init__(
            f"Fitness evaluation failed for {solution_id}: {message}",
            context={"solution_id": solution_id, "execution_error": execution_error},
        )

MemoryError

Bases: AgentKError

Base exception for memory-related errors.

Source code in agent_k/exceptions.py
249
250
class MemoryError(AgentKError):
    """Base exception for memory-related errors."""

CheckpointError

Bases: MemoryError

Raised when checkpoint operations fail.

Source code in agent_k/exceptions.py
253
254
255
256
257
258
259
260
261
262
class CheckpointError(MemoryError):
    """Raised when checkpoint operations fail."""

    def __init__(self, checkpoint_name: str, operation: str, message: str) -> None:
        self.checkpoint_name = checkpoint_name
        self.operation = operation
        super().__init__(
            f"Checkpoint {operation} failed for {checkpoint_name}: {message}",
            context={"checkpoint_name": checkpoint_name, "operation": operation},
        )

MemoryCapacityError

Bases: MemoryError

Raised when memory capacity is exceeded.

Source code in agent_k/exceptions.py
265
266
267
268
269
270
271
272
273
274
class MemoryCapacityError(MemoryError):
    """Raised when memory capacity is exceeded."""

    def __init__(self, current_size: int, max_size: int) -> None:
        self.current_size = current_size
        self.max_size = max_size
        super().__init__(
            f"Memory capacity exceeded: {current_size} / {max_size} bytes",
            context={"current_size": current_size, "max_size": max_size},
        )

GraphError

Bases: AgentKError

Base exception for graph-related errors.

Source code in agent_k/exceptions.py
277
278
class GraphError(AgentKError):
    """Base exception for graph-related errors."""

StateTransitionError

Bases: GraphError

Raised when state transition is invalid.

Source code in agent_k/exceptions.py
281
282
283
284
285
286
287
288
289
290
291
class StateTransitionError(GraphError):
    """Raised when state transition is invalid."""

    def __init__(self, from_state: str, to_state: str, reason: str) -> None:
        self.from_state = from_state
        self.to_state = to_state
        self.reason = reason
        super().__init__(
            f"Invalid transition from {from_state} to {to_state}: {reason}",
            context={"from_state": from_state, "to_state": to_state, "reason": reason},
        )

PhaseTimeoutError

Bases: GraphError

Raised when a phase exceeds its timeout.

Source code in agent_k/exceptions.py
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
class PhaseTimeoutError(GraphError):
    """Raised when a phase exceeds its timeout."""

    def __init__(self, phase: str, timeout_seconds: int, elapsed_seconds: float) -> None:
        self.phase = phase
        self.timeout_seconds = timeout_seconds
        self.elapsed_seconds = elapsed_seconds
        super().__init__(
            f"Phase {phase} timed out after {elapsed_seconds:.1f}s (limit: {timeout_seconds}s)",
            context={
                "phase": phase,
                "timeout_seconds": timeout_seconds,
                "elapsed_seconds": elapsed_seconds,
            },
        )

classify_error

classify_error(
    exc: Exception,
) -> tuple[ErrorCategory, RecoveryStrategy]

Classify errors into recovery categories and strategies.

Source code in agent_k/exceptions.py
311
312
313
314
315
316
317
318
319
320
321
def classify_error(exc: Exception) -> tuple[ErrorCategory, RecoveryStrategy]:
    """Classify errors into recovery categories and strategies."""
    if isinstance(exc, RateLimitError):
        return "recoverable", "retry"
    if isinstance(exc, AuthenticationError):
        return "fatal", "abort"
    if isinstance(exc, CompetitionNotFoundError):
        return "fatal", "abort"
    if isinstance(exc, AgentKError):
        return ("recoverable", "retry") if exc.recoverable else ("fatal", "abort")
    return "transient", "retry"

Version information for the AGENT-K package.

(c) Mike Casale 2026. Licensed under the MIT License.