Skip to main content

Utilities for Coze coding client runtime context and helpers.

Project description

coze-coding-utils

Python utilities for the Coze coding client. Provides a simple runtime Context object and an async-task subsystem.

Installation

pip install coze-coding-utils

Modules

runtime_ctx

from coze_coding_utils.runtime_ctx.context import Context

ctx = Context(run_id="r", space_id="s", project_id="p", method="fetchData")
print(ctx.run_id, ctx.method)

async_tasks

Per-process async task runtime backed by PostgreSQL (single table, JSONB payload, partial indexes). Public API:

from coze_coding_utils.async_tasks import (
    AsyncTaskRuntime,        # construct one per process
    AsyncTask,               # SQLAlchemy ORM (single PK on task_id)
    AsyncTaskStatus,         # pending / running / completed / failed / timeout
    AsyncTaskBase,           # DeclarativeBase if caller needs to drive DDL
    AsyncTaskStorageError,   # raised on DB init/query failure (caller turns into 503)
    config,                  # env-overridable constants module
)

runtime = AsyncTaskRuntime(
    session_factory=get_session,   # Callable[[], sqlalchemy.orm.Session]
    engine=get_engine(),           # sqlalchemy.engine.Engine
    graph=async_graph,             # any object with .ainvoke(payload, config=...)
    checkpointer=checkpointer,     # any LangGraph-compatible checkpointer
)

# Lifespan / FastAPI usage:
async with lifespan(...):
    await runtime.submit(payload={...}, biz_context={"x-user-id": "u1"}, deadline_sec=600)
    row = await runtime.get(task_id)
    ...
    await runtime.shutdown()

The runtime is intentionally framework-agnostic:

  • No FastAPI dependency — caller maps AsyncTaskStorageError to HTTP 503 themselves.
  • No LangGraph dependency in [project.dependencies] — the runtime only calls graph.ainvoke(payload, config=run_config) and holds the checkpointer reference for resume scenarios.

Caller contracts (pre-conditions)

The runtime makes three assumptions about the caller's environment. Violating any one will silently break checkpoint cleanup or task lifecycle:

  1. Checkpointer compatible with PG. Construct the LangGraph with a checkpointer that writes to the schema configured by COZE_ASYNC_TASK_CHECKPOINT_SCHEMA (default memory), tables checkpoints / checkpoint_writes. langgraph-checkpoint-postgres works out of the box.
  2. thread_id == task_id. The runtime fixes {"configurable": {"thread_id": task_id}} when calling graph.ainvoke. The memory_cleanup_once scan deletes orphan checkpoint rows by joining on this equality. Don't override thread_id in your graph.
  3. Session schema access. The injected session_factory must produce sessions with read+write privileges on COZE_ASYNC_TASK_CHECKPOINT_SCHEMA schema (so cleanup can DELETE orphan rows).

Environment variables

All prefixed with COZE_ASYNC_TASK_. Override only when there's a specific ops reason.

Var Default Meaning
HEARTBEAT_INTERVAL_SEC 30 Per-task heartbeat write frequency
HEARTBEAT_FAIL_THRESHOLD 3 Consecutive failures → task self-aborts
ORPHAN_TIMEOUT_SEC 300 Running → failed after this many seconds of silent heartbeat
MAX_CLAIM_COUNT 3 max claim attempts before a row is left for scans to reap
DEFAULT_DEADLINE_SEC 86400 24h wall-clock cap; override per task via deadline_sec
CLEANUP_INTERVAL_SEC 21600 memory cleanup loop period
ORPHAN_SCAN_INTERVAL_SEC 60 orphan scan period
DEADLINE_SCAN_INTERVAL_SEC 60 deadline scan period
MAX_CONCURRENT_PER_INSTANCE 50 in-process concurrency semaphore
SCAN_BATCH_LIMIT 500 rows per orphan/deadline scan tick
MEMORY_CLEANUP_BATCH 200 rows per memory.checkpoints cleanup sub-batch
MEMORY_CLEANUP_MAX_ITERS 50 max batches per cleanup tick before deferring
RECURSION_LIMIT 100 LangGraph runtime recursion ceiling
CHECKPOINT_SCHEMA memory PG schema for LangGraph checkpoint tables
TASK_RETENTION_DAYS 7 terminal-status rows older than this are DELETEd
TASK_CLEANUP_INTERVAL_SEC 3600 task_cleanup_loop tick period
TASK_CLEANUP_BATCH 500 max rows DELETEd per task_cleanup tick

The runtime lazily issues CREATE TABLE IF NOT EXISTS on the first submit / get, so a fresh deployment needs no manual DDL.

Python Version

Requires Python 3.10+.

License

MIT

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

coze_coding_utils-0.2.8.tar.gz (71.2 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

coze_coding_utils-0.2.8-py3-none-any.whl (89.6 kB view details)

Uploaded Python 3

File details

Details for the file coze_coding_utils-0.2.8.tar.gz.

File metadata

  • Download URL: coze_coding_utils-0.2.8.tar.gz
  • Upload date:
  • Size: 71.2 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.9.6

File hashes

Hashes for coze_coding_utils-0.2.8.tar.gz
Algorithm Hash digest
SHA256 3aadf17975be046c5bde18732cb6a0cb956ff6124746af3fefe214787fb2618b
MD5 58be2bbf0f3b140f168e5d215c3bec6a
BLAKE2b-256 5f18241ed27c827d0edc18765ad0e62d2922e2787c63dec3dbc0a37c0dd747ea

See more details on using hashes here.

File details

Details for the file coze_coding_utils-0.2.8-py3-none-any.whl.

File metadata

File hashes

Hashes for coze_coding_utils-0.2.8-py3-none-any.whl
Algorithm Hash digest
SHA256 6e49bf2bdc2f2b85c1a37c7eaa4f1d80b843638ba691da15a7e3e982225e6f09
MD5 8f9487628ea84548adbcb17ae42d7013
BLAKE2b-256 44d33dd67badde9219c0ccccbab5625ab24b3a76e3f1ca9bc9c0caf5d447af27

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page