Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 3 additions & 2 deletions backend/ai_system/agent/fork.py
Original file line number Diff line number Diff line change
Expand Up @@ -88,7 +88,7 @@ def executor(ctx, tools, remember_run):
declared={tool['function']['name'] for tool in tools}
mapping={c.name.replace('.','_'):c.name for c in registry.model_capabilities()}

async def execute(call,*,recover_only=False):
async def execute(call,*,recover_only=False,queued_at=None):
name=mapping.get(call['name'],call['name'])
args=call.get('args') or {}
key='fork-tool:'+CURRENT_TURN.get().thread_id+':'+call['_message_id']+':'+call['id']
Expand All @@ -114,7 +114,8 @@ async def perform():
capability=registry.get(name)
try:
with execution_scope(action_id=key):
result=await dispatch(ctx,ToolInvocation(name,key,args,capability.access if capability else 'write'),perform)
result=await dispatch(ctx,ToolInvocation(name,key,args,capability.access if capability else 'write'),
perform,queued_at=queued_at)
content=result.value if isinstance(result.value,(str,list)) else json.dumps(result.value,ensure_ascii=False)
return ToolMessage(content=content,tool_call_id=call['id'],name=call['name'],status='success' if result.status=='completed' else 'error')
except (ValueError,KeyError,FileNotFoundError) as exc:
Expand Down
87 changes: 65 additions & 22 deletions backend/ai_system/agent/loop.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,10 @@
"""The shared, durable model/tool loop for lead and child agents."""
import asyncio
import json
import logging
from dataclasses import dataclass, replace
from itertools import groupby
from time import monotonic
from uuid import uuid4
from contextvars import ContextVar
from weakref import WeakValueDictionary
Expand All @@ -13,6 +16,7 @@

MODEL_CALLBACKS=ContextVar('agent_model_callbacks',default=None)
_owners=WeakValueDictionary()
logger = logging.getLogger('ai_system.agent.tools')


class NoResearchProgress(RuntimeError):pass
Expand Down Expand Up @@ -47,17 +51,24 @@ def observed_messages(messages):
return messages


def skipped_calls(calls, reason):
return [ToolMessage(content=reason, tool_call_id=call['id'], name=call['name'],
status='error', additional_kwargs={'skipped': True}) for call in calls]


class AgentLoop:
def __init__(self, model, tools, system_prompt, *, ctx, context=None, prepare=None,
execute=None, finish=None):
self.model,self.tools,self.system_prompt=model,tools,system_prompt
self.ctx,self.context=ctx,context
self.prepare,self.execute,self.finish=prepare,execute,finish
self.tool_map={tool.name:tool for tool in tools if hasattr(tool,'name')}
self.parallel_tools = {name for name, tool in self.tool_map.items()
if (getattr(tool, 'metadata', None) or {}).get('access') == 'read'}

async def _execute(self, call, *, recover_only=False):
async def _execute(self, call, *, recover_only=False, queued_at=None):
if self.execute:
return await self.execute(call,recover_only=recover_only)
return await self.execute(call, recover_only=recover_only, queued_at=queued_at)
from .runtime import call_tool, recover_tool
tool=self.tool_map.get(call['name'])
native={**call,'id':call['_message_id']+':'+call['id']}
Expand All @@ -68,9 +79,32 @@ async def _execute(self, call, *, recover_only=False):
tool_call_id=call['id'],name=call['name'],status='error')
if tool is None:
return ToolMessage(content='未知工具:'+call['name'],tool_call_id=call['id'],name=call['name'],status='error')
result=await call_tool(self.ctx,native,lambda:tool.ainvoke(call['args']))
access = 'read' if call['name'] in self.parallel_tools else 'write'
result=await call_tool(self.ctx,native,lambda:tool.ainvoke(call['args']),access=access,queued_at=queued_at)
return result.model_copy(update={'tool_call_id':call['id']})

async def _run_batch(self, store, session, history, calls):
queued_at = monotonic()
try:
for parallel, group in groupby(calls, key=lambda call: call['name'] in self.parallel_tools):
if parallel:
# ToolGates admits four readers and advances waiting calls as slots free up.
async with asyncio.TaskGroup() as tasks:
pending = [tasks.create_task(self._execute(call, queued_at=queued_at)) for call in group]
results = [task.result() for task in pending]
store.append_messages(session, results)
history.extend(results)
continue
for call in group:
result = await self._execute(call, queued_at=queued_at)
if result.additional_kwargs.get('agent_stop'):
return call, result
store.append_message(session, result)
history.append(result)
finally:
logger.info('Tool batch session=%s message_id=%s calls=%d wall_seconds=%.6f',
session, calls[0]['_message_id'], len(calls), monotonic()-queued_at)

async def run(self, session, messages, *, on_resume=None, new_user_turn_id=None):
key=(str(self.ctx.research.root),session)
owner=_owners.get(key)
Expand All @@ -86,15 +120,22 @@ async def _run(self, session, messages, *, on_resume=None, new_user_turn_id=None
store=AgentStore(self.ctx.research.root)
history=store.messages(session)
resumed=bool(history)
if resumed and on_resume:on_resume(bool(pending_calls(history)))
seen={message.id for message in history}
incoming=[message for message in (messages[-1:] if resumed else messages) if not message.id or message.id not in seen]
saved=store.session(session)
pending = pending_calls(history)
if pending and saved and saved['status'] in {'paused', 'waiting'}:
# Older sessions left the remainder of a stopped batch pending.
skipped = skipped_calls(pending, '已暂停或等待用户输入,本次后续调用未执行。')
store.append_messages(session, skipped)
history.extend(skipped)
pending = []
if resumed and on_resume:on_resume(bool(pending))
if resumed and not incoming and saved and saved['status']=='completed':
return {'messages':history,'status':'completed'}
self.ctx.agent_messages=observed_messages(history)
if resumed and incoming:
for call in pending_calls(history):
for call in pending:
result=await self._execute(call,recover_only=True)
store.append_message(session,result);history.append(result)
for message in incoming:
Expand All @@ -119,24 +160,26 @@ async def complete(response):
if done:return done
while True:
self.ctx.agent_messages=observed_messages(history)
for call in pending_calls(history):
calls = pending_calls(history)
if calls:
last_finish_feedback=None
result=await self._execute(call)
store.append_message(session,result);history.append(result)
stop=result.additional_kwargs.get('agent_stop')
if stop=='complete':
for remaining in pending_calls(history):
skipped=ToolMessage(content='已申请结束,本次后续调用未执行。',tool_call_id=remaining['id'],name=remaining['name'],status='error')
store.append_message(session,skipped);history.append(skipped)
response=AIMessage(content=call['args'].get('reason') or call['args'].get('title') or '交付文件已保存。')
store.append_message(session,response);history.append(response)
done=await complete(response)
if done:return done
break
if stop:
store.set_session(session,stop,result.content)
return {'messages':history,'status':stop}
if pending_calls(history):continue
stopped = await self._run_batch(store, session, history, calls)
if stopped:
call, result = stopped
stop = result.additional_kwargs['agent_stop']
remaining = calls[calls.index(call)+1:]
if stop == 'complete':
skipped = skipped_calls(remaining, '已申请结束,本次后续调用未执行。')
response = AIMessage(content=call['args'].get('reason') or call['args'].get('title') or '交付文件已保存。')
store.append_messages(session, [result, *skipped, response])
history.extend([result, *skipped, response])
done = await complete(response)
if done:return done
else:
skipped = skipped_calls(remaining, '已暂停或等待用户输入,本次后续调用未执行。')
store.append_messages(session, [result, *skipped], status=stop, reason=result.content)
history.extend([result, *skipped])
return {'messages': history, 'status': stop}
seen={message.id for message in history}
for message in list(history):
diagnostic=message.additional_kwargs.get('tool_diagnostic') if isinstance(message,AIMessage) else None
Expand Down
64 changes: 48 additions & 16 deletions backend/ai_system/agent/runtime.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,12 +8,15 @@
from dataclasses import asdict, dataclass
import inspect
import json
import logging
import time
from uuid import uuid4
from .context import CURRENT_TOOL, CURRENT_TURN, item_id, session_turn
from .protocol import PlanItem, ToolItem
from .projection import tool_projection, safe_diagnostic

logger = logging.getLogger('ai_system.agent.tools')


@dataclass(frozen=True)
class ToolInvocation:
Expand Down Expand Up @@ -131,6 +134,17 @@ def finish(self, status, *, receipt=None):
self.item.update(status=status, finished_at=self.metadata['finished_at'])
return self.turn.put(self.snapshot(), 'item/completed', receipt=receipt)

def record_error(self, exc):
from ai_system.research.review_cache import error_detail
from ai_system.research.json_views import JsonPointerLookupError
detail = error_detail(exc)
self.metadata.update(error_type=type(exc).__name__, message=detail)
if isinstance(exc, JsonPointerLookupError):
self.metadata['json_pointer_error'] = exc.diagnostic
if self.item['type'] == 'plan':
self.item['explanation'] = safe_diagnostic(self.turn.store.root, detail)
return detail


def update_tool(ctx, **changes):
current = CURRENT_TOOL.get()
Expand Down Expand Up @@ -177,15 +191,16 @@ async def _reconcile(ctx, invocation):
return ToolResult('复用已有运行 '+rid+',未重放代码。状态:'+str(info.get('status','unknown'))+'\n'+output[-6000:], status=status)


async def dispatch(ctx, invocation, handler):
async def dispatch(ctx, invocation, handler, *, capture_errors=False, queued_at=None):
"""All model and scheduler calls enter here; raw helper calls stay internal."""
if CURRENT_TURN.get() is None:
research = getattr(ctx, 'research', None)
with session_turn(ctx, (research.research_id if research else 'workspace')+'-lead'):
return await dispatch(ctx, invocation, handler)
return await dispatch(ctx, invocation, handler, capture_errors=capture_errors, queued_at=queued_at)
turn = CURRENT_TURN.get()
from ai_system.research.store import digest
from ai_system.research.runtime import execution_scope
from ai_system.config.generation import ModelGenerationLimit
from ai_system.research.runtime import ModelServiceError, RepeatedOperationBlocked, ResearchBudgetExhausted, execution_scope
from ai_system.modules.registry import display_output
signature = digest([invocation.name, invocation.arguments])
limits = gates(ctx)
Expand All @@ -194,7 +209,11 @@ async def dispatch(ctx, invocation, handler):
async with lock:
turn.store.bind_call(turn.thread_id, invocation.call_id, signature)
saved = turn.store.receipt(turn.thread_id, invocation.call_id, signature)
if saved is not None:return ToolResult(**saved)
if saved is not None:
if queued_at is not None:
logger.info('Tool %s call_id=%s queue_seconds=%.6f execution_seconds=0 recovered=true',
invocation.name, invocation.call_id, time.monotonic()-queued_at)
return ToolResult(**saved)
operation = ToolExecution(ctx, turn, invocation)
existing = turn.store.get_item(operation.item['id'])
if existing:
Expand All @@ -204,15 +223,27 @@ async def dispatch(ctx, invocation, handler):
else:
turn.put(operation.snapshot(), 'item/started')
token = CURRENT_TOOL.set(operation)
started_at = None
try:
check_tool_access(ctx,invocation.name)
async with limits.acquire(invocation.access):
started_at = time.monotonic()
with execution_scope(tool_call_id=invocation.call_id, parent_call_id=operation.item['id'],
events=getattr(ctx,'events',None), research_id=getattr(getattr(ctx,'research',None),'research_id',None)):
result = await _reconcile(ctx, invocation)
if result is None:
value = handler()
result = _result(await value if inspect.isawaitable(value) else value)
try:
value = handler()
if inspect.isawaitable(value):value = await value
except (ModelGenerationLimit, ModelServiceError, RepeatedOperationBlocked, ResearchBudgetExhausted):
raise
except Exception as exc:
# A delegated session owns recovery of its committed child work.
if not capture_errors or invocation.access == 'delegate':raise
detail = operation.record_error(exc)
result = ToolResult(detail, status='failed', message=detail)
else:
result = _result(value)
if isinstance(result.value, dict):
operation.metadata['output'] = {**operation.metadata.get('output',{}), **display_output(invocation.name, result.value)}
for name in ('run_id','question_id','experiment_id'):
Expand All @@ -228,30 +259,30 @@ async def dispatch(ctx, invocation, handler):
operation.finish(result.status, receipt=(invocation.call_id, signature, asdict(result)))
return result
except BaseException as exc:
from ai_system.research.review_cache import error_detail
from ai_system.research.json_views import JsonPointerLookupError
operation.metadata.update(error_type=type(exc).__name__, message=error_detail(exc))
if isinstance(exc, JsonPointerLookupError):
operation.metadata['json_pointer_error'] = exc.diagnostic
if operation.item['type']=='plan':operation.item['explanation']=safe_diagnostic(turn.store.root,error_detail(exc))
operation.record_error(exc)
operation.finish('interrupted' if isinstance(exc, asyncio.CancelledError) else 'failed')
raise
finally:
CURRENT_TOOL.reset(token)
if queued_at is not None:
finished_at = time.monotonic()
started = finished_at if started_at is None else started_at
logger.info('Tool %s call_id=%s queue_seconds=%.6f execution_seconds=%.6f',
invocation.name, invocation.call_id, started-queued_at, finished_at-started)


async def invoke(ctx, registry, name, arguments, *, call_id=None):
async def invoke(ctx, registry, name, arguments, *, call_id=None, capture_errors=False, queued_at=None):
capability = registry.get(name)
from ai_system.research.runtime import CURRENT_EXECUTION
# Explicit model call IDs survive checkpoints; scheduled actions use their
# durable action identity. Standalone invocations get a fresh identity.
call_id = call_id or CURRENT_EXECUTION.get().get('tool_call_id') or uuid4().hex
access = 'delegate' if name == 'research.delegate' else capability.access if capability else 'write'
return await dispatch(ctx, ToolInvocation(name, call_id, arguments, access),
lambda: registry.execute(name, arguments, ctx))
lambda: registry.execute(name, arguments, ctx), capture_errors=capture_errors, queued_at=queued_at)


async def call_tool(ctx, call, handler, *, access='write'):
async def call_tool(ctx, call, handler, *, access='write', queued_at=None):
"""Child/experiment tools share the same dispatcher and result formatting."""
from langchain_core.messages import ToolMessage
async def run():
Expand All @@ -260,7 +291,8 @@ async def run():
return ToolResult(message.content, status='failed' if message.status == 'error' else 'completed')
return message
try:
result = await dispatch(ctx, ToolInvocation(call['name'], call['id'], call.get('args') or {}, access), run)
result = await dispatch(ctx, ToolInvocation(call['name'], call['id'], call['args'], access), run,
capture_errors=True, queued_at=queued_at)
content = result.value if isinstance(result.value, (str,list)) else json.dumps(result.value, ensure_ascii=False)
return ToolMessage(content=content, tool_call_id=call['id'], name=call['name'], status='success' if result.status == 'completed' else 'error')
except (ValueError, KeyError, FileNotFoundError) as exc:
Expand Down
20 changes: 15 additions & 5 deletions backend/ai_system/agent/store.py
Original file line number Diff line number Diff line change
Expand Up @@ -57,17 +57,27 @@ def request(self, session):
return json.loads(row[0]) if row else None

def append_message(self, session, message):
self.append_messages(session, [message])

def append_messages(self, session, messages, *, status=None, reason=None):
from langchain_core.messages import message_to_dict
from uuid import uuid4
if not message.id:message.id=uuid4().hex
with self.transaction() as db:
db.execute('INSERT OR IGNORE INTO session_messages(session_id,id,payload) VALUES (?,?,?)',
(session,message.id,json.dumps(message_to_dict(message),ensure_ascii=False)))
for message in messages:
if not message.id:message.id=uuid4().hex
db.execute('INSERT OR IGNORE INTO session_messages(session_id,id,payload) VALUES (?,?,?)',
(session,message.id,json.dumps(message_to_dict(message),ensure_ascii=False)))
if status is not None:
self._set_session(db, session, status, reason)

def set_session(self, session, status, reason=None):
with self.transaction() as db:
db.execute('INSERT INTO sessions VALUES (?,?,?) ON CONFLICT(id) DO UPDATE SET status=excluded.status,reason=excluded.reason',
(session,status,reason))
self._set_session(db, session, status, reason)

@staticmethod
def _set_session(db, session, status, reason):
db.execute('INSERT INTO sessions VALUES (?,?,?) ON CONFLICT(id) DO UPDATE SET status=excluded.status,reason=excluded.reason',
(session,status,reason))

def session(self, session):
with closing(self.connect()) as db:
Expand Down
Loading