Blame view

offline_tasks/agent_tools/cli.py 5.51 KB
b4f7574f   tangwang   feat(agent): add ...
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
  """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())