cli.py 5.51 KB
"""Command-line and JSON-lines entry points for the agent toolset."""

import argparse
import json
import os
import sys

from .catalog import DimensionCatalog
from .service import RecommendationAgentTools
from .store import MemoryIndexStore, RedisIndexStore


DEFAULT_CATALOG_PATH = os.path.join(
    os.path.dirname(os.path.dirname(os.path.abspath(__file__))),
    'output',
    'agent_dimension_catalog.json',
)


def _load_catalog(path):
    if path and os.path.exists(path):
        return DimensionCatalog.from_file(path)
    return DimensionCatalog()


def _build_redis_store(args):
    try:
        import redis
    except ImportError:
        raise RuntimeError('redis-py is required for Redis-backed tool calls')

    redis_url = os.environ.get('RECOMMENDATION_REDIS_URL')
    if redis_url:
        client = redis.Redis.from_url(
            redis_url,
            decode_responses=True,
            socket_connect_timeout=args.redis_timeout,
            socket_timeout=args.redis_timeout,
        )
    else:
        client = redis.Redis(
            host=os.environ.get('RECOMMENDATION_REDIS_HOST', 'localhost'),
            port=int(os.environ.get('RECOMMENDATION_REDIS_PORT', '6479')),
            db=int(os.environ.get('RECOMMENDATION_REDIS_DB', '0')),
            password=os.environ.get('RECOMMENDATION_REDIS_PASSWORD'),
            decode_responses=True,
            socket_connect_timeout=args.redis_timeout,
            socket_timeout=args.redis_timeout,
        )
    return RedisIndexStore(client)


def _build_service(args, use_redis=True):
    catalog_path = args.catalog or os.environ.get(
        'RECOMMENDATION_DIMENSION_CATALOG', DEFAULT_CATALOG_PATH
    )
    catalog = _load_catalog(catalog_path)
    store = _build_redis_store(args) if use_redis else MemoryIndexStore()
    return RecommendationAgentTools(store, dimension_catalog=catalog)


def _write_json(payload, compact=False):
    if compact:
        serialized = json.dumps(payload, ensure_ascii=False, separators=(',', ':'))
    else:
        serialized = json.dumps(payload, ensure_ascii=False, indent=2, sort_keys=True)
    sys.stdout.write(serialized + '\n')
    sys.stdout.flush()


def _read_arguments(raw_arguments):
    if raw_arguments == '-':
        raw_arguments = sys.stdin.read()
    try:
        arguments = json.loads(raw_arguments)
    except (TypeError, ValueError) as error:
        raise ValueError('arguments must be valid JSON: %s' % error)
    if not isinstance(arguments, dict):
        raise ValueError('arguments must decode to a JSON object')
    return arguments


def _serve_stdio(service):
    for line in sys.stdin:
        line = line.strip()
        if not line:
            continue
        request_id = None
        try:
            request = json.loads(line)
            if not isinstance(request, dict):
                raise ValueError('request must be a JSON object')
            request_id = request.get('id')
            tool_name = request.get('tool', request.get('name'))
            if not tool_name:
                raise ValueError('request requires tool or name')
            result = service.call_tool(tool_name, request.get('arguments', {}))
            response = {'id': request_id, 'result': result}
        except Exception as error:
            response = {
                'id': request_id,
                'result': {
                    'ok': False,
                    'error': {
                        'code': 'invalid_request',
                        'message': str(error),
                        'retryable': False,
                    },
                },
            }
        _write_json(response, compact=True)
    return 0


def build_parser():
    parser = argparse.ArgumentParser(
        description='Agent-facing tools over the offline recommendation indices'
    )
    parser.add_argument(
        '--catalog', default=None,
        help='Path to agent_dimension_catalog.json',
    )
    parser.add_argument(
        '--redis-timeout', type=float, default=1.5,
        help='Redis connect and read timeout in seconds (default: 1.5)',
    )
    subparsers = parser.add_subparsers(dest='command')

    list_parser = subparsers.add_parser(
        'list-tools', help='Print function-calling tool definitions'
    )
    list_parser.add_argument('--compact', action='store_true')

    call_parser = subparsers.add_parser('call', help='Call one tool')
    call_parser.add_argument('tool_name')
    call_parser.add_argument(
        '--arguments', default='{}',
        help='JSON object, or - to read JSON from stdin',
    )
    call_parser.add_argument('--compact', action='store_true')

    subparsers.add_parser(
        'serve-stdio',
        help='Read one {id, tool, arguments} JSON request per line',
    )
    return parser


def main(argv=None):
    parser = build_parser()
    args = parser.parse_args(argv)
    if not args.command:
        parser.print_help()
        return 2

    if args.command == 'list-tools':
        service = _build_service(args, use_redis=False)
        _write_json(service.tool_definitions(), compact=args.compact)
        return 0


    service = _build_service(args, use_redis=True)
    if args.command == 'call':
        try:
            arguments = _read_arguments(args.arguments)
        except ValueError as error:
            parser.error(str(error))
        result = service.call_tool(args.tool_name, arguments)
        _write_json(result, compact=args.compact)
        return 0 if result.get('ok') else 1
    if args.command == 'serve-stdio':
        return _serve_stdio(service)
    return 2


if __name__ == '__main__':
    sys.exit(main())