Skip to content

Make videos on the computer you already own. FreeVideo runs MiniMax H3 in as little as 8 GB of VRAM and 16 GB of RAM, and adapts its acceleration path to your hardware.

Agent interface: the answers to reading, cancelling and resuming a job carry the job under job

Bowen Xue866c02677df9
diff --git a/freevideo_engine/agent/client.py b/freevideo_engine/agent/client.py
index ca61ef3..aae0991 100644
--- a/freevideo_engine/agent/client.py
+++ b/freevideo_engine/agent/client.py
@@ -77,6 +77,11 @@ def origin(url):
return value.scheme, value.hostname.lower(), value.port or (443 if value.scheme == 'https' else 80)
+def one_job(answer):
+ """The job of a single-job answer, without the copy the server adds under 'job'."""
+ return {key: value for key, value in answer.items() if key != 'job'}
+
+
class LocalProxyHandler(urllib.request.ProxyHandler):
def proxy_open(self, req, proxy, type):
host = urllib.parse.urlsplit(req.full_url).hostname
@@ -246,8 +251,8 @@ class Client:
def job(self, identity, wait=0):
wait = max(0, min(25, wait))
- return self.request('GET', '/freevideo/agent/v1/jobs/' + identity, query={'wait': wait} if wait else None,
- timeout=max(self.timeout, wait + 5))
+ return one_job(self.request('GET', '/freevideo/agent/v1/jobs/' + identity, query={'wait': wait} if wait else None,
+ timeout=max(self.timeout, wait + 5)))
def jobs(self, status=None, project=None, kind=None, limit=None):
return self.get('/jobs', status=status, project=project, kind=kind, limit=limit)['jobs']
@@ -264,10 +269,10 @@ class Client:
return view
def cancel(self, identity):
- return self.post('/jobs/%s/cancel' % identity, {})
+ return one_job(self.post('/jobs/%s/cancel' % identity, {}))
def resume(self, identity, *, ref=None):
- return self.post('/jobs/%s/resume' % identity, {'ref': ref} if ref else {})
+ return one_job(self.post('/jobs/%s/resume' % identity, {'ref': ref} if ref else {}))
def asset(self, identity, target, *, thumbnail=False):
"""Retrieve a library file through authenticated HTTP only."""
diff --git a/freevideo_engine/agent/guide.py b/freevideo_engine/agent/guide.py
index b68f7dd..7f319c6 100644
--- a/freevideo_engine/agent/guide.py
+++ b/freevideo_engine/agent/guide.py
@@ -79,8 +79,9 @@ GUIDE = {
'agent_jobs': [
'GET /capabilities reads the studio cache with the same size/task/material query parameters. '
'status=computing includes retry_after_seconds; unknown plan estimates have seconds=null.',
- 'GET /jobs/{id}?wait=25 waits at most 25 seconds and returns poll_after_ms. Poll the same ID; '
- 'disconnecting a wait or SSE does not cancel generation.',
+ 'GET /jobs/{id}?wait=25 waits at most 25 seconds and returns poll_after_ms. Like POST /jobs, the answer '
+ 'has the job under job (its fields are also at the top level). Poll the same ID until job.status is '
+ 'succeeded, failed, cancelled or interrupted; disconnecting a wait or SSE does not cancel generation.',
'Jobs wait behind an active studio chain. GET /queue gives Agent/UI ownership and counts ahead, '
'without studio prompts. POST /jobs/{id}/cancel cancels only this job.',
'POST /jobs/{id}/resume continues failed, interrupted or cancelled generation; successful blocks stay. '
@@ -360,8 +361,8 @@ def connection_guide(root, base, lang=None, offers=None):
'# ref is a new name for every new request; the same ref again only repeats a submission whose answer was lost.',
'# job = call("POST", "/jobs", {"prompt": "USER_REQUEST", "seconds": 5, "aspect": "16:9", "label": "SHORT NAME",',
'# "ref": "A-NEW-NAME-FOR-THIS-REQUEST"})["job"]',
- '# job = call("GET", "/jobs/" + job["id"] + "?wait=25")',
- '# Poll the same ID until succeeded.',
+ '# while job["status"] not in ("succeeded", "failed", "cancelled", "interrupted"):',
+ '# job = call("GET", "/jobs/" + job["id"] + "?wait=25")["job"]',
'# Download base origin + job["result"]["video"]["url"] with the same Authorization header.',
'# The conversation inside FreeVideo (see below): each wait is its own command; when it returns, run the next one.',
'# box = call("GET", "/inbox?wait=50") # {"session": ..., "inbox": [what the user said], "again": true if nothing yet}',
diff --git a/freevideo_engine/agent/routes.py b/freevideo_engine/agent/routes.py
index b43a28f..92d5a33 100644
--- a/freevideo_engine/agent/routes.py
+++ b/freevideo_engine/agent/routes.py
@@ -245,6 +245,11 @@ def plan(port, value, jobs=None):
return result
+def job_answer(view):
+ """One job answers the way a submission does: the job is also under 'job'."""
+ return dict(view, job=view)
+
+
async def wait_for_job(jobs, row, seconds, *, clock=time.monotonic, sleep=asyncio.sleep):
if not math.isfinite(seconds) or seconds < 0:
raise chain_error('invalid_wait', 'wait must be a finite nonnegative number of seconds.',
@@ -1054,14 +1059,14 @@ def register():
@guarded
async def get_job(request):
row = await asyncio.to_thread(jobs.get, request.match_info['id'])
- return reply(await wait_for_job(jobs, row, float(request[query_key].get('wait', '0') or 0)))
+ return reply(job_answer(await wait_for_job(jobs, row, float(request[query_key].get('wait', '0') or 0))))
@routes.post(PREFIX + '/jobs/{id}/cancel')
@guarded
async def cancel(request):
def work():
return jobs.view(jobs.cancel(request.match_info['id']))
- return reply(await asyncio.to_thread(work))
+ return reply(job_answer(await asyncio.to_thread(work)))
@routes.post(PREFIX + '/jobs/{id}/resume')
@guarded
@@ -1070,7 +1075,7 @@ def register():
key=request.headers.get('Idempotency-Key'), value=await body(request), replay_result=True,
client=request.headers.get('X-FreeVideo-Client', '')[:80] or None)
await jobs.tick()
- return reply(await asyncio.to_thread(jobs.view, row))
+ return reply(job_answer(await asyncio.to_thread(jobs.view, row)))
@routes.get(PREFIX + '/jobs/{id}/events')
@guarded
diff --git a/freevideo_engine/agent/schema.py b/freevideo_engine/agent/schema.py
index 94d6dfa..518812e 100644
--- a/freevideo_engine/agent/schema.py
+++ b/freevideo_engine/agent/schema.py
@@ -1176,7 +1176,7 @@ def openapi():
elif suffix == '/jobs' and method == 'GET':
response_schema = obj({'jobs': {'type': 'array', 'items': {'$ref': '#/components/schemas/Job'}}})
elif suffix in ('/jobs/{id}', '/jobs/{id}/cancel', '/jobs/{id}/resume'):
- response_schema = {'$ref': '#/components/schemas/Job'}
+ response_schema = {'$ref': '#/components/schemas/JobAnswer'}
elif '/drama/{id}' in suffix and not suffix.endswith('/sheet') or suffix == '/drama' and method == 'POST':
response_schema = production_response()
elif suffix == '/confirmations':
@@ -1206,16 +1206,18 @@ def openapi():
if suffix == '/connect' and method == 'GET':
success['content']['text/plain'] = {'schema': {'type': 'string'}}
paths.setdefault(path, {})[method.lower()] = operation
+ job_view = {'type': 'object', 'properties': dict(id=JOB, kind=enum(KINDS),
+ status=enum(('waiting', 'queued', 'running', 'cancelling', 'succeeded', 'failed', 'cancelled', 'interrupted')),
+ chain_id=string(), last_heartbeat_at={'type': ['string', 'null']}, poll_after_ms={'type': ['integer', 'null']},
+ spec={'type': 'object'}, progress={'type': 'object'}, result={'type': 'object'},
+ error={'$ref': '#/components/schemas/Error'})}
return dict(openapi='3.1.0', info=dict(title='FreeVideo Agent API', version=str(API_VERSION)), paths=paths,
components=dict(securitySchemes={'bearer': {'type': 'http', 'scheme': 'bearer'},
'page': {'type': 'apiKey', 'in': 'cookie', 'name': 'freevideo_agent_page'}}, schemas={
'Session': session_view(), 'SessionEvent': session_event(stored=True),
- 'JobSpec': schemas()['job'], 'Batch': batch_schema(),
- 'Job': {'type': 'object', 'properties': dict(id=JOB, kind=enum(KINDS),
- status=enum(('waiting', 'queued', 'running', 'cancelling', 'succeeded', 'failed', 'cancelled', 'interrupted')),
- chain_id=string(), last_heartbeat_at={'type': ['string', 'null']}, poll_after_ms={'type': ['integer', 'null']},
- spec={'type': 'object'}, progress={'type': 'object'}, result={'type': 'object'},
- error={'$ref': '#/components/schemas/Error'})},
+ 'JobSpec': schemas()['job'], 'Batch': batch_schema(), 'Job': job_view,
+ # One job answers the way a submission does: the same job is also under 'job'.
+ 'JobAnswer': dict(job_view, properties=dict(job_view['properties'], job={'$ref': '#/components/schemas/Job'})),
'Submitted': obj(dict(job={'$ref': '#/components/schemas/Job'},
jobs={'type': 'array', 'items': {'$ref': '#/components/schemas/Job'}})),
'Error': obj(dict(code=enum(ERRORS),