workos-office / AgentRuntime /skill_contracts.py
dellweb3's picture
Publish anonymized meeting employee and AI workflow studio
ba0589e verified
Raw History Blame Contribute Delete
7.18 kB
"""Typed contracts and deterministic tests for administrator-authored data skills."""
import ast,copy,hashlib,json,re,math
from APIGateway.app.errors import GatewayError
from CollaborationService.interpreter import PureProgram,ProgramError
TYPES={'string','integer','number','boolean','object','array'}
def fits(value,kind):
return {'string':lambda:isinstance(value,str),'integer':lambda:type(value) is int,
'number':lambda:type(value) is int or (type(value) is float and math.isfinite(value)),'boolean':lambda:type(value) is bool,
'object':lambda:isinstance(value,dict),'array':lambda:isinstance(value,list)}[kind]()
def fields(rows):
if not isinstance(rows,list) or len(rows)>20:raise GatewayError(422,'SKILL_SCHEMA_INVALID','每组最多20个字段。')
result=[];names=set()
for row in rows:
if not isinstance(row,dict) or set(row)-{'name','type','required','description','default'}:raise GatewayError(422,'SKILL_SCHEMA_INVALID','字段属性不符合约定。')
name=row.get('name','');kind=row.get('type','string')
if not isinstance(name,str) or not re.fullmatch(r'[A-Za-z][A-Za-z0-9_]{0,39}',name) or name in names or not isinstance(kind,str) or kind not in TYPES:raise GatewayError(422,'SKILL_SCHEMA_INVALID','字段名需为唯一英文标识,类型需有效。')
if type(row.get('required',False)) is not bool:raise GatewayError(422,'SKILL_SCHEMA_INVALID','required必须为布尔值。')
if len(str(row.get('description','')))>300:raise GatewayError(422,'SKILL_SCHEMA_INVALID','字段说明最多300字。')
if row.get('default') is not None and not fits(row['default'],kind):raise GatewayError(422,'SKILL_SCHEMA_INVALID','默认值类型不符:'+name)
names.add(name);result.append({'name':name,'type':kind,'required':row.get('required',False),'description':row.get('description',''),'default':row.get('default')})
return result
def validate(value,schema,label,defaults=False):
if not isinstance(value,dict):raise GatewayError(422,'SKILL_DATA_INVALID',label+'必须为JSON对象。')
value=copy.deepcopy(value)
for field in fields(schema):
name=field['name']
if name not in value and defaults and field['default'] is not None:value[name]=copy.deepcopy(field['default'])
if name not in value:
if field['required']:raise GatewayError(422,'SKILL_FIELD_REQUIRED',label+'缺少字段:'+name)
elif not fits(value[name],field['type']):raise GatewayError(422,'SKILL_FIELD_TYPE',label+'字段类型不符:'+name)
return value
def infer(code,tests):
try:tree=ast.parse(code)
except SyntaxError:return {'input_schema':[],'output_schema':[],'config_schema':[]}
names=set()
for node in ast.walk(tree):
if isinstance(node,ast.Call) and isinstance(node.func,ast.Attribute) and isinstance(node.func.value,ast.Name) and node.func.value.id=='data' and node.func.attr=='get' and node.args and isinstance(node.args[0],ast.Constant) and isinstance(node.args[0].value,str):names.add(node.args[0].value)
def from_values(values):
result=[]
for name,value in values.items():
if not re.fullmatch(r'[A-Za-z][A-Za-z0-9_]{0,39}',name):continue
kind=next((t for t in ('boolean','integer','number','string','array','object') if fits(value,t)),'string')
result.append({'name':name,'type':kind,'required':False,'description':'根据代码与样例推断,请核对','default':None})
return result
incoming={};outgoing={};config={}
for t in tests:
if isinstance(t.get('input'),dict):incoming.update(t['input'])
if isinstance(t.get('expected'),dict):outgoing.update(t['expected'])
config=incoming.pop('config',{})
for name in names-{'config'}:incoming.setdefault(name,'')
return {'input_schema':from_values(incoming),'output_schema':from_values(outgoing),'config_schema':from_values(config) if isinstance(config,dict) else []}
def execute(config,data):
data=validate(data,config.get('input_schema',[]),'输入',True)
defaults=config.get('defaults',{}); overrides=data.pop('config',{})
if not isinstance(defaults,dict) or not isinstance(overrides,dict):raise GatewayError(422,'SKILL_DATA_INVALID','配置必须为JSON对象。')
settings={**defaults,**overrides}
settings=validate(settings,config.get('config_schema',[]),'配置',True)
if config.get('config_schema'):data['config']=settings
try:result=PureProgram(config['code']).run(data)
except (ProgramError,KeyError,TypeError,ValueError,ZeroDivisionError) as exc:raise GatewayError(422,'SKILL_EXECUTION_FAILED','代码执行失败:'+str(exc)[:300]) from exc
return validate(result,config.get('output_schema',[]),'输出')
def evaluate(config):
tests=config.get('tests',[])
if not isinstance(tests,list) or not 2<=len(tests)<=8:raise GatewayError(422,'SKILL_TESTS_REQUIRED','请提供2–8个测试,至少包含一个边界样例。')
cases=[]
for test in tests:
if not isinstance(test,dict) or set(test)!={'input','expected'}:raise GatewayError(422,'SKILL_TEST_INVALID','测试需包含input和expected。')
try:
actual=execute(config,test['input']);cases.append({**test,'actual':actual,'passed':actual==test['expected']})
except GatewayError as exc:cases.append({**test,'passed':False,'error':exc.message})
return {'passed':all(t['passed'] for t in cases),'cases':cases,'runtime':'pure-python-ast-v1'}
def clean(config):
value=copy.deepcopy(config)
for key in ('input_schema','output_schema','config_schema'):value[key]=fields(value.get(key,[]))
if any(x['name']=='config' for x in value['input_schema']):raise GatewayError(422,'SKILL_SCHEMA_INVALID','config为配置保留字段,请在配置页声明。')
try:PureProgram(value.get('code',''))
except ProgramError as exc:raise GatewayError(422,'INVALID_PROGRAM',str(exc)) from exc
value['defaults']=validate(value.get('defaults',{}),value['config_schema'],'配置',True)
value['code_hash']=hashlib.sha256(value['code'].encode()).hexdigest()
report=evaluate(value)
if not report['passed']:raise GatewayError(422,'SKILL_TESTS_FAILED','技能测试未通过,不能保存为可编排技能。')
value['test_report']=report
return value
def bind(config,outputs,request):
bindings=config.get('input_bindings',{});payload={}
for name,binding in bindings.items():
if binding.get('mode')=='constant':payload[name]=copy.deepcopy(binding.get('value'))
else:
value=outputs.get(binding.get('node_id'),{})
for part in binding.get('field','text').split('.'):
if not isinstance(value,dict) or part not in value:raise GatewayError(422,'SKILL_BINDING_MISSING','上游结果缺少字段:'+binding.get('field',''))
value=value[part]
payload[name]=copy.deepcopy(value)
if 'text' not in bindings and any(f['name']=='text' for f in config.get('input_schema',[])):
payload['text']=next((o['text'] for o in reversed(list(outputs.values())) if 'text' in o),request)
return payload