Python API
App 구성은 motif.agent.app에서, 실행과 호출 및 송출 API는 motif.agent.sdk에서 가져옵니다.
실행 시작하기
App.run / App.arun
from motif.agent.app import App
app.run(entry, /, *, run_id=None, principal=DEFAULT_PRINCIPAL, **kwargs) -> Any
await app.arun(entry, /, *, run_id=None, principal=DEFAULT_PRINCIPAL, **kwargs) -> Any
| 파라미터 | 타입 | 필수 여부 / 기본값 | 의미 |
entry | str | Callable[..., Awaitable[Any]] | 필수 | 등록된 에이전트 이름(예: "answer") 또는 첫 인수로 Context를 받는 비동기 함수. |
run_id | str | None | None | 생략하면 ID를 생성합니다. "request-42"처럼 지정할 경우 해당 런타임에서 사용 가능한 ID여야 합니다. |
principal | PrincipalContext | 로컬 기본 주체 | SECURE에서는 인증된 요청 신원을 명시적으로 전달해야 합니다. |
**kwargs | Any | 엔트리에 따라 다름 | 엔트리 함수에 그대로 전달할 입력. 예를 들어 topic="refunds". |
엔트리 함수의 값을 반환합니다. 등록되지 않은 이름이나 중첩 App 실행에는 SdkError가 발생합니다. 이벤트 루프에서는 await app.arun(...)을 사용하세요. 첫 런타임 접근 전에 모델, 에이전트, 검사를 등록합니다.
Runtime.run
from motif.agent.sdk import Runtime
async with runtime.run("request-42", closing_seconds=30.0) as ctx:
result = await ctx.release({"answer": "refunds"})
| 파라미터 | 타입 | 필수 여부 / 기본값 | 의미 |
external_id | str | 필수 | 호출자가 정한 실행 ID(예: "request-42"). 활성 또는 일시 중단 상태인 ID는 RunIdActive를 일으킬 수 있습니다. |
principal | PrincipalContext | 로컬 기본 주체 | SECURE에서는 인증된 요청 신원을 명시적으로 전달해야 합니다. |
closing_seconds | float | 30.0 | 실행 종료 시 진행 중인 작업의 완료를 기다리는 시간(초). |
비동기 컨텍스트 관리자가 Context를 제공합니다. 종료 중인 런타임에서는 새 실행에 RuntimeClosed가 발생합니다. await runtime.aclose(drain_seconds=None)은 즉시 종료합니다. 진행 중인 실행을 기다리려면 0 이상의 유한한 초 단위를 전달합니다. App.aclose도 같은 키워드를 받습니다.
생성 API 선택하기
| 생성 API | 선택 기준 | 설정 |
App.development | 데코레이터로 로컬 App을 구성합니다. | App |
Runtime.development | 모델 함수, 등록 도구, 검증기, 어댑터를 직접 전달합니다. | Runtime |
App.secure | 인증된 요청에 서명된 정책 번들과 영속 효과 저널을 적용합니다. | SECURE |
Runtime.local | 정책, 보안, 확장 옵션을 직접 지정합니다. | Runtime.local |
호출, 검증, 송출
Context.model / Context.invoke
await ctx.model(name: str, value: Any) -> Any
await ctx.invoke(kind: OperationKind, resource: str, action: str, value: Any) -> Any
| 파라미터 | 타입 | 필수 여부 / 기본값 | 의미 |
name | str | 필수 | 등록된 모델 이름(예: "local"). 작업 종류는 MODEL_CALL, 액션은 "complete"입니다. |
kind | OperationKind | 필수 | invoke에 전달할 작업 종류. TOOL_CALL은 call로, 결과 송출은 release로 처리합니다. |
resource / action | str | 필수 | 등록한 경로의 리소스와 액션. 예를 들어 "catalog"와 "lookup". |
value | Any | 필수 | 어댑터 입력 형식에 맞는 JSON 호환 값(예: {"topic": "refunds"}). |
활성 컨텍스트에서 호출합니다. 두 메서드는 어댑터의 JSON 응답을 디코딩해 반환합니다. 경로가 없거나 권한이 거부되면 MediationDenied가, invoke에 TOOL_CALL을 넘기면 SdkError가 발생합니다.
| OperationKind 멤버 | 값 | 용도 |
INVOKE | invoke | 범용 관리 호출 경로. |
MODEL_CALL | model_call | 모델 경로. model이 이 종류를 사용합니다. |
TOOL_CALL | tool_call | 저널을 사용하는 도구 경로. call 또는 등록 도구를 사용합니다. |
STATE_WRITE | state_write | 등록된 상태 쓰기 경로. |
RELEASE | release | 송출 권한 판정. 후보를 평가할 때는 ctx.release를 사용합니다. |
Context.call / Context.retry
await ctx.call(resource: str, action: str, value: Any, *, effect_id: str) -> EffectOutcome
await ctx.retry(resource: str, action: str, value: Any, *, effect_id: str) -> EffectOutcome
| 파라미터 | 타입 | 필수 여부 / 기본값 | 의미 |
resource / action | str | 필수 | 등록된 도구 경로 구성 요소(예: "ticket", "create"). |
value | Any | 필수 | JSON 페이로드(예: {"ticket_id": "T-42"}). 재시도할 때 최초 경로와 페이로드를 유지합니다. |
effect_id | str | 필수 | "ticket-T-42"처럼 업무 작업을 식별하는 고정 키. 직접 만드는 ID는 비울 수 없으며 #와 예약 접두사 r:, g:, c:를 피합니다. 재시도에는 기록된 ID를 사용합니다. |
EffectOutcome에는 state, effect_id, 응답 바이트인 result, 원인인 cause가 들어갑니다. 응답을 사용하기 전에 succeeded를 확인하세요. call에는 새 키가 필요합니다. 충돌하거나 재시도가 거부되면 EffectIdConflict가 발생합니다. 복구 조건을 참고하세요.
Context.verify / Context.release
await ctx.verify(dimension_id: str, value: Any, evidence: Sequence[Any] = (),
*, verifier_id: str | None = None) -> Verdict
await ctx.release(value: Any, evidence: Sequence[Any] = ()) -> ReleaseResult
| 파라미터 | 타입 | 필수 여부 / 기본값 | 의미 |
dimension_id | str | verify에서 필수 | 등록된 차원 이름(예: "answer.present"). |
value | Any | 필수 | JSON 호환 후보 결과. 예를 들어 {"answer": "refunds"}을 전달합니다. |
evidence | Sequence[Any] | () | 검증에 사용할 JSON 호환 값. 예를 들어 [{"id": "policy-1", "text": "30 days"}]을 전달합니다. 명시적으로 검증한 뒤 송출할 때는 같은 근거를 사용합니다. |
verifier_id | str | None | None | 생략하면 해당 차원의 사용 가능한 검증기를 사용합니다. 하나를 고르려면 "nonempty"처럼 등록된 ID를 지정합니다. |
verify는 종합 Verdict를 반환하고 검증 Receipt를 기록합니다. 차원이나 검증기를 찾을 수 없으면 SdkError가 발생합니다. release는 활성 정책을 적용하며, 값이 보류된 경우에도 ReleaseResult를 반환합니다.
OutputGate
from motif.agent.sdk import OutputGate
OutputGate(*, verifiers=(), require=None, revisable=(), human_review=(),
mode=GateMode.ENFORCE, audit=None, normalize=None, runtime=None)
gate.check(value, *, evidence=(), run_id=None, principal=DEFAULT_PRINCIPAL) -> GateResult
await gate.acheck(value, *, evidence=(), run_id=None, principal=DEFAULT_PRINCIPAL) -> GateResult
| 파라미터 | 타입 | 필수 여부 / 기본값 | 의미 |
verifiers | Sequence[Verifier] | () | 등록할 검증기 객체(예: [answer_present]). |
require | Iterable[str] | None | None | 기본적으로 전달한 검증기의 모든 차원이 필수입니다. 이름을 나열해 일부만 선택할 수 있습니다. |
revisable / human_review | Iterable[str] | () | 게이트 정책에서 수정 요청 또는 사람 검토로 이어질 수 있는 차원. |
mode | GateMode | GateMode.ENFORCE | ENFORCE는 판정을 적용합니다. 개발 전용 REPORT는 검증이 미충족이어도 송출할 수 있으며 원래 판정을 기록합니다. Enum 멤버를 사용하세요. |
audit | AuditSink | None | None | 독립 게이트의 선택 감사 싱크. |
normalize | Callable[[Any], Any] | None | None | 검사 전에 후보 결과와 각각의 근거를 JSON 호환 값으로 변환합니다. |
runtime | Runtime | None | None | 기존 런타임의 정책과 검증기를 사용합니다. 독립 게이트용 정책, 모드, 감사 설정을 함께 지정할 수 없습니다. |
두 검사 메서드에 value를 전달하고 필요에 따라 위의 evidence, run_id, principal을 지정합니다. 이벤트 루프 안에서 check를 호출하면 SdkError가 발생합니다. 비동기 코드에서는 acheck를 사용하세요.
VerifiedStream.for_context
from motif.agent.sdk import VerifiedStream
VerifiedStream.for_context(sink, context, *, chunk_size=4096,
max_buffer_bytes=1_048_576) -> VerifiedStream
await stream.feed(chunk: bytes) -> None
await stream.finish() -> StreamOutcome
활성 Context와 비동기 write, close, abort를 구현한 StreamSink를 전달합니다. 크기 설정은 모두 양의 바이트 수입니다. UTF-8 입력에는 버퍼 한도가 적용되며, 출력 청크 경계에서 문자를 자르지 않습니다. StreamOutcome에는 released와 reason이 있습니다. 스트림 송출과 실패를 참고하세요.
모델, 에이전트, 검사, 도구 등록하기
App.model / App.agent
app.model(name: str, function: JsonFunction) -> None
@app.agent(requires=(), description=None, calls=None, calls_agents=None, delegates_to=None)
async def answer(ctx: Context, topic: str) -> ReleaseResult: ...
| 파라미터 | 타입 / 기본값 | 의미 |
name / function | str / 비동기 함수, 필수 | 비어 있지 않은 고유 경로 이름(예: "local"). 함수는 디코딩된 JSON 값 하나를 받아 JSON 호환 데이터를 반환합니다. 잘못된 입력이나 중복 등록은 SdkError를 일으킵니다. |
requires | Iterable[str] = () | 개발 모드에서 필수로 적용할 송출 차원(예: ["answer.present"]). SECURE에서는 활성 번들이 요구사항을 결정합니다. |
calls | Iterable[Route] | None = None | App에서는 경로 튜플과 등록 도구 객체를 받습니다. 빈 목록은 모든 경로를 차단하고, None은 모듈이나 호출자의 범위를 상속합니다. |
calls_agents / delegates_to | Iterable[AgentRef] | None = None | 실행 내 호출 또는 자식 실행에 허용할 에이전트 ID나 데코레이터를 적용한 에이전트. 빈 목록은 대상이 없음을, None은 관계를 선언하지 않음을 뜻합니다. |
description | str | None = None | 매니페스트와 개발 도구에 표시할 설명. |
App에 자동 등록하려면 @app.agent를 사용합니다. 런타임을 직접 구성할 때는 motif.agent.sdk의 @agent를 사용하세요. 래핑된 에이전트도 비동기 함수입니다.
App.check / verifier
@app.check(dimension, *, verifier_id=None, version="1", description=None,
needs_evidence=False)
@verifier(dimension, *, verifier_id=None, version="1", description=None,
mediated=None, needs_evidence=False, uses_evidence=True)
| 파라미터 | 타입 / 기본값 | 의미 |
dimension | str, 필수 | 정책이 요구하는 이름(예: "answer.present"). |
verifier_id / version | str | None = None / str = "1" | ID는 기본적으로 함수 이름이며, version은 검증기 버전을 식별합니다. |
needs_evidence | bool = False | 외부 근거가 필요한 검사를 선언합니다. 근거가 없으면 UNKNOWN 판정을 내립니다. |
mediated / uses_evidence | bool | None = None / bool = True | SDK 검증기 전용. None은 콜백 시그니처로 호출 형태를 추론합니다. 첨부 근거와 무관한 검사는 uses_evidence=False로 선언합니다. |
description | str | None = None | 검사 설명. |
@app.check는 동기 또는 비동기 함수에 디코딩한 후보 값과 근거 목록을 전달합니다. 불리언, 진단 코드 문자열, Verdict 또는 VerificationResult를 반환하세요. SDK 데코레이터는 스냅샷을 받고 VerificationResult를 반환하는 함수를 사용합니다. 중재 호출을 사용하는 SDK 검증기는 검증 호출 인터페이스를 첫 인수로 받습니다.
@app.tool(name="ticket.create", key="ticket_id", key_scope="global")
async def create_ticket(ticket_id: str) -> dict: ...
from motif.agent.sdk import register
register(resource, action, *, key=None, key_scope=None, encode=None,
decode=None, recovery=None, description=None)
| 파라미터 | 타입 / 기본값 | 의미 |
name / resource / action | str. App의 name 기본값은 None. | SECURE에서는 변경되지 않는 "resource.action"을 지정해야 합니다. SDK register는 두 구성 요소가 모두 필수입니다. |
key | KeySource | None = None | "ticket_id"처럼 매개변수 이름을 쓰거나, 바인딩된 인수를 문자열 또는 정수로 변환하는 함수를 전달합니다. |
key_scope | KeyScope | None = None | 키를 지정하면 기본 범위는 "run"입니다. SECURE에서는 키를 지정하거나 "explicit", "call" 중 하나를 선택해야 합니다. |
encode / decode | Callable[[Any], Any] | None = None | 도구 JSON 결과에 적용할 선택 변환 함수입니다. encode로 결과를 준비하고 decode로 호출자가 사용할 값으로 변환합니다. |
recovery | RecoveryMode | None = None | 프로바이더의 복구 계약을 선언합니다. |
description | str | None = None | 개발 도구에 표시할 설명. |
| 키 범위 리터럴 | 효과 식별 방식 |
"run" | 같은 실행에서 키가 같으면 같은 효과로 식별합니다. |
"global" | 파생 키를 실행 간에 공유합니다. 필요한 경우 키에 업무상 격리 범위를 포함하세요. |
"explicit" | 호출자가 효과 ID를 직접 넘겨야 합니다. key는 생략합니다. |
"call" | 호출마다 별도의 효과를 생성합니다. key는 생략합니다. |
두 데코레이터는 비동기 도구를 Registered 객체로 감쌉니다. App은 경로를 바로 등록합니다. SDK의 register를 사용하면 런타임 생성 시 registered=[...]로 객체를 전달합니다. Context를 받는 재사용 Python 단계에는 SDK @block을 사용하세요.
결과와 HTTP 상태 매핑
ReleaseResult에는 decision, reason, diagnostics와 선택적인 content, unenforced가 있습니다. value는 콘텐츠를 JSON으로 디코딩합니다. GateResult는 released, judged, enforced, run_id도 제공합니다.
ReleaseResult.to_response()와 FastAPI의 release_response는 기본적으로 release에 HTTP 200, human_review에 202, block, abstain, revise에 422를 반환합니다. status_map으로 결정별 상태를 바꿀 수 있습니다. 예외에는 별도 매핑을 적용합니다.
런타임 설정
모드, 용량 제한, 정책 적용 범위, 선택 의존성은 설정에서 확인할 수 있습니다.
확장 인터페이스
Adapter와 Verifier로 관리 대상 실행과 검증을 확장합니다. 요청 메타데이터는 Operation, 검증기 입력은 Snapshot으로 다룹니다.
AuditSink, AsyncAuditSink, EventObserver는 기록과 관측에 사용합니다. 공급자와 프레임워크는 통합 인터페이스로 연결합니다.
ExecutionBackend와 ExecutionRequest는 별도의 실행 경계를 정의합니다. NativeBackend는 등록된 에이전트를 로컬에서 실행합니다. JournaledBackend는 RunStore에 실행 상태도 기록합니다. 백엔드별 기능을 쓰기 전에 BackendCapability를 확인하세요.
v0.1에서 업그레이드하기
SDK 진입점은 motif.agent.sdk, 운영 구성 API는 motif.agent.app에서 가져옵니다. motif.agent.sdk.runtime이나 motif.agent.ext.otel에서 직접 가져오던 코드는 경로를 바꾸세요. OpenTelemetry 통합 모듈은 motif.agent.ext.integrations.otel에 있습니다.
SECURE 실행에는 명시적인 주체를 전달합니다. 감사 실패 시 HTTP 503을 받아 재시도하던 클라이언트는 502 effect_unaudited를 처리하고 효과의 확실성을 확인하도록 바꿉니다. 경로가 없는 공급자 호출 녹화는 Replayer(legacy_route=...)로 재생할 경로를 지정해야 합니다. 그 밖의 호환성 변경은 변경 기록에 있습니다.
Python API
Use motif.agent.app for app composition and motif.agent.sdk for run, call and release APIs.
Start a run
App.run / App.arun
from motif.agent.app import App
app.run(entry, /, *, run_id=None, principal=DEFAULT_PRINCIPAL, **kwargs) -> Any
await app.arun(entry, /, *, run_id=None, principal=DEFAULT_PRINCIPAL, **kwargs) -> Any
| Parameter | Type | Required / default | Meaning |
entry | str | Callable[..., Awaitable[Any]] | Yes | Registered agent name, e.g. "answer", or an async callable that takes Context first. |
run_id | str | None | None | Omit to generate an ID. An explicit ID such as "request-42" must be available in the runtime. |
principal | PrincipalContext | Local principal | Required explicitly in SECURE. Use the authenticated request identity. |
**kwargs | Any | Depends on entry | Inputs forwarded to the entry, e.g. topic="refunds". |
Returns whatever the entry returns. Unknown names and nested App runs raise SdkError. In an event loop use await app.arun(...). Register models, agents and checks before the first runtime access.
Runtime.run
from motif.agent.sdk import Runtime
async with runtime.run("request-42", closing_seconds=30.0) as ctx:
result = await ctx.release({"answer": "refunds"})
| Parameter | Type | Required / default | Meaning |
external_id | str | Yes | Caller-chosen run ID, e.g. "request-42". Active or suspended IDs can raise RunIdActive. |
principal | PrincipalContext | Local principal | Required explicitly in SECURE. Use the authenticated request identity. |
closing_seconds | float | 30.0 | Time allowed for leased work to finish at run exit, in seconds. |
The async context manager yields Context. A runtime that is closing rejects new runs with RuntimeClosed. await runtime.aclose(drain_seconds=None) closes immediately. Pass a finite non-negative number of seconds to drain first. App.aclose takes the same keyword.
Choose a constructor
| Constructor | Choose when | Configuration |
App.development | Compose a local app with decorators. | App |
Runtime.development | Supply model functions, registered tools, verifiers and adapters directly. | Runtime |
App.secure | Serve authenticated requests with a signed policy bundle and durable state for effects. | SECURE |
Runtime.local | Assemble a runtime with explicit policy, security and extension options. | Runtime.local |
Call, verify and release
Context.model / Context.invoke
await ctx.model(name: str, value: Any) -> Any
await ctx.invoke(kind: OperationKind, resource: str, action: str, value: Any) -> Any
| Parameter | Type | Required / default | Meaning |
name | str | Yes | Registered model name, e.g. "local". This selects MODEL_CALL with action "complete". |
kind | OperationKind | Yes | Explicit kind for invoke. Use call for TOOL_CALL and release to evaluate output. |
resource / action | str | Yes | Exact registered route components, e.g. "catalog" and "lookup". |
value | Any | Yes | JSON-compatible adapter input, e.g. {"topic": "refunds"}. Match that adapter’s input shape. |
Use an active context. Both methods return the adapter’s decoded JSON. A missing route or authorization denial raises MediationDenied. Passing TOOL_CALL to invoke raises SdkError.
| OperationKind member | Value | Use |
INVOKE | invoke | Generic managed route. |
MODEL_CALL | model_call | Model route. model uses this kind. |
TOOL_CALL | tool_call | Journaled tool route. Use call or a registered tool. |
STATE_WRITE | state_write | Registered state-write route. |
RELEASE | release | Release authorization. Use ctx.release to evaluate a candidate. |
Context.call / Context.retry
await ctx.call(resource: str, action: str, value: Any, *, effect_id: str) -> EffectOutcome
await ctx.retry(resource: str, action: str, value: Any, *, effect_id: str) -> EffectOutcome
| Parameter | Type | Required / default | Meaning |
resource / action | str | Yes | Exact components of a registered tool route, e.g. "ticket" and "create". |
value | Any | Yes | JSON payload, e.g. {"ticket_id": "T-42"}. Keep the same route and payload for retry. |
effect_id | str | Yes | Stable business key such as "ticket-T-42". Keep it non-empty and avoid # and reserved r:, g: or c: prefixes when creating your own ID. For retry, reuse the recorded ID. |
EffectOutcome includes state, effect_id, optional response bytes in result and an optional cause. Check succeeded before consuming the response. call needs a new key. A conflict or refused retry raises EffectIdConflict. See recovery eligibility.
Context.verify / Context.release
await ctx.verify(dimension_id: str, value: Any, evidence: Sequence[Any] = (),
*, verifier_id: str | None = None) -> Verdict
await ctx.release(value: Any, evidence: Sequence[Any] = ()) -> ReleaseResult
| Parameter | Type | Required / default | Meaning |
dimension_id | str | Yes for verify | Registered dimension, e.g. "answer.present". |
value | Any | Yes | JSON-compatible candidate, e.g. {"answer": "refunds"}. |
evidence | Sequence[Any] | () | JSON-compatible supporting values, e.g. [{"id": "policy-1", "text": "30 days"}]. Supply the same evidence for explicit verification and release. |
verifier_id | str | None | None | Omit to use available verifiers for the dimension. Provide a registered ID such as "nonempty" to select one. |
verify returns a combined Verdict and records verifier receipts. An unknown dimension or verifier raises SdkError. release applies the active policy and returns a ReleaseResult, including when policy withholds the value.
OutputGate
from motif.agent.sdk import OutputGate
OutputGate(*, verifiers=(), require=None, revisable=(), human_review=(),
mode=GateMode.ENFORCE, audit=None, normalize=None, runtime=None)
gate.check(value, *, evidence=(), run_id=None, principal=DEFAULT_PRINCIPAL) -> GateResult
await gate.acheck(value, *, evidence=(), run_id=None, principal=DEFAULT_PRINCIPAL) -> GateResult
| Parameter | Type | Required / default | Meaning |
verifiers | Sequence[Verifier] | () | Registered verifier objects, e.g. [answer_present]. |
require | Iterable[str] | None | None | Require all supplied verifier dimensions by default. Select a subset by name. |
revisable / human_review | Iterable[str] | () | Dimensions that may trigger revision or human review under the gate policy. |
mode | GateMode | GateMode.ENFORCE | ENFORCE applies the judgement. Development-only REPORT can deliver verification shortfalls and records the underlying judgement. Use enum members. |
audit | AuditSink | None | None | Optional audit sink for a standalone gate. |
normalize | Callable[[Any], Any] | None | None | Convert the candidate and each evidence item to JSON-compatible values before checking. |
runtime | Runtime | None | None | Use an existing runtime’s policy and verifiers. Provide no standalone policy, mode or audit overrides. |
For both check methods, supply value and optional evidence, run_id and principal as above. check raises SdkError inside a running event loop. In async code use acheck.
VerifiedStream.for_context
from motif.agent.sdk import VerifiedStream
VerifiedStream.for_context(sink, context, *, chunk_size=4096,
max_buffer_bytes=1_048_576) -> VerifiedStream
await stream.feed(chunk: bytes) -> None
await stream.finish() -> StreamOutcome
Supply an active Context and a StreamSink with async write, close and abort. Both size settings are positive byte counts. The buffer cap applies to UTF-8 input. The output chunk size preserves whole characters. StreamOutcome provides released and reason. See stream delivery and failure.
Register models, agents, checks and tools
App.model / App.agent
app.model(name: str, function: JsonFunction) -> None
@app.agent(requires=(), description=None, calls=None, calls_agents=None, delegates_to=None)
async def answer(ctx: Context, topic: str) -> ReleaseResult: ...
| Parameter | Type / default | Meaning |
name / function | str / async callable, required | Unique non-empty route name, e.g. "local". The function accepts one decoded JSON value and returns JSON-compatible data. Invalid or duplicate registrations raise SdkError. |
requires | Iterable[str] = () | Required release dimensions in development, e.g. ["answer.present"]. The active bundle defines requirements in SECURE. |
calls | Iterable[Route] | None = None | In App, accepts route tuples and registered tool objects. An empty iterable allows no routes. None inherits module/caller scope if present. |
calls_agents / delegates_to | Iterable[AgentRef] | None = None | Allow named agent IDs or decorated agents for in-run calls or child runs. Empty means none. None leaves the edge undeclared. |
description | str | None = None | Metadata for manifests and tooling. |
Use @app.agent for automatic App registration, or @agent from motif.agent.sdk with explicit runtime composition. The wrapped agent remains async.
App.check / verifier
@app.check(dimension, *, verifier_id=None, version="1", description=None,
needs_evidence=False)
@verifier(dimension, *, verifier_id=None, version="1", description=None,
mediated=None, needs_evidence=False, uses_evidence=True)
| Parameter | Type / default | Meaning |
dimension | str, required | Name the policy requires, e.g. "answer.present". |
verifier_id / version | str | None = None / str = "1" | ID defaults to the function name. Version identifies the verifier revision. |
needs_evidence | bool = False | Declare checks that need supplied evidence. Without evidence such a verifier yields UNKNOWN. |
mediated / uses_evidence | bool | None = None / bool = True | SDK verifier only. None infers the callback shape. Set uses_evidence=False for a check independent of attached evidence. |
description | str | None = None | Metadata for the check. |
@app.check passes the decoded candidate and a list of decoded evidence to a sync or async function. Return a boolean, diagnostic code string, Verdict or VerificationResult. The SDK decorator expects a function on snapshots returning VerificationResult. A mediated SDK verifier also takes the verification-call interface as its first argument.
@app.tool(name="ticket.create", key="ticket_id", key_scope="global")
async def create_ticket(ticket_id: str) -> dict: ...
from motif.agent.sdk import register
register(resource, action, *, key=None, key_scope=None, encode=None,
decode=None, recovery=None, description=None)
| Parameter | Type / default | Meaning |
name / resource / action | str. App name defaults to None. | Assign a stable "resource.action" in SECURE. SDK register always requires the two non-empty components. |
key | KeySource | None = None | Parameter name such as "ticket_id" or a callable mapping bound arguments to a string or integer. |
key_scope | KeyScope | None = None | With a key, default scope is "run". For SECURE, supply a key or choose "explicit" or "call". |
encode / decode | Callable[[Any], Any] | None = None | Optional conversion around the tool’s JSON result. encode prepares the result and decode converts the invoked result for the caller. |
recovery | RecoveryMode | None = None | Declares the provider’s recovery contract. |
description | str | None = None | Metadata for tooling. |
| Key scope literal | Effect identity |
"run" | Same key identifies the same effect within a run. |
"global" | The same derived key can identify an effect across runs. Include business isolation in the key where needed. |
"explicit" | Require the caller to supply an explicit effect ID. Omit key. |
"call" | Every call is a distinct effect. Omit key. |
Both decorators wrap an async tool in a Registered object. App registers the route immediately. With SDK register, pass the wrapper in registered=[...] when building the runtime. Use SDK @block for reusable Python steps called with a context.
Results and HTTP mapping
ReleaseResult contains decision, reason, diagnostics and optional content and unenforced. value decodes content as JSON. GateResult also exposes released, judged, enforced and run_id.
ReleaseResult.to_response() and FastAPI’s release_response default to HTTP 200 for release, 202 for human_review and 422 for block, abstain and revise. Pass a status_map to override individual decisions. Exceptions use a separate mapping.
Runtime settings
See Configuration for posture, limits, policy scope and optional dependencies.
Extension interfaces
Adapter and Verifier extend managed execution and verification. Use Operation for request metadata and Snapshot for verifier input.
AuditSink, AsyncAuditSink and EventObserver cover writes and observation. Connect a provider or framework through the integration interfaces.
ExecutionBackend and ExecutionRequest define a separate run boundary. NativeBackend executes registered agents locally. JournaledBackend also records run state in a RunStore. Check BackendCapability before using backend-specific features.
Upgrade from v0.1
Import SDK entry points from motif.agent.sdk and production assembly from motif.agent.app. If you imported directly from a module such as motif.agent.sdk.runtime or motif.agent.ext.otel, update the path. The OpenTelemetry integration is now at motif.agent.ext.integrations.otel.
Pass an explicit principal to SECURE runs. Update clients that retried HTTP 503 after an audit failure to handle 502 effect_unaudited and inspect effect certainty. For applications that record provider calls, route-less recordings require Replayer(legacy_route=...). See the change log for other compatibility changes.