ums.utils.request

Access to the management, e.g., get the list of messages and single messages. Manually send messages (if necessary, the platforms should do this).

Example

        m_request = ManagementRequest()

        m_request.get_message(count=12)
        # MessageDbRow(count=12 sender='from' recipient='to' ...

        m_request.list_messages(id="test", limit=2)
        # [
        #       MessageDbRow(count=7256, sender='management', ...),
        #       MessageDbRow(count=7255, sender='management', ...),
        # ]

        m_request.total_messages(id="test")
        # 31

See also ums.example.__main__ and run in Docker via docker compose exec management python -m ums.example

  1# Agenten Plattform
  2#
  3# (c) 2024 Magnus Bender
  4# 	Institute of Humanities-Centered Artificial Intelligence (CHAI)
  5# 	Universitaet Hamburg
  6# 	https://www.chai.uni-hamburg.de/~bender
  7#  
  8# source code released under the terms of GNU Public License Version 3
  9# https://www.gnu.org/licenses/gpl-3.0.txt
 10
 11"""
 12	Access to the management, e.g., get the list of messages and single messages.
 13	Manually send messages (if necessary, the platforms should do this). 
 14
 15	### Example
 16	```python
 17
 18		m_request = ManagementRequest()
 19		
 20		m_request.get_message(count=12)
 21		# MessageDbRow(count=12 sender='from' recipient='to' ...
 22
 23		m_request.list_messages(id="test", limit=2)
 24		# [
 25		#	MessageDbRow(count=7256, sender='management', ...),
 26		#	MessageDbRow(count=7255, sender='management', ...),
 27		# ]
 28
 29		m_request.total_messages(id="test")
 30		# 31
 31
 32	```
 33
 34	See also `ums.example.__main__` and run in Docker via ``docker compose exec management python -m ums.example``
 35"""
 36
 37import os
 38from typing import List, Dict, Any
 39
 40import requests
 41from pydantic import validate_call
 42
 43from ums.utils.types import AgentMessage, AgentResponse, MessageDbRow
 44
 45
 46class RequestException(Exception):
 47	"""
 48		Raised on http and similar errors.
 49	"""
 50	pass
 51
 52class ManagementRequest():
 53
 54	MANAGEMENT_URL = os.environ.get('MANAGEMENT_URL', 'http://127.0.0.1:80').strip().strip('/')
 55
 56	@validate_call
 57	def __init__(self, allow_lazy:bool=True):
 58		"""
 59			If `allow_lazy` is active, the type checking (by pydantic) is less strict. 
 60			E.g. it does not require that all files in the data section of messages must exist on the file system.
 61		"""
 62		self.allow_lazy = allow_lazy
 63		self.pydantic_context = {
 64			"require_file_exists": not self.allow_lazy
 65		}
 66
 67	@validate_call
 68	def get_message(self, count:int) -> MessageDbRow:
 69		"""
 70			Get a message (like a table row) from the management by using the `count`.
 71		"""
 72		row = self._get_request(
 73			'list/single',
 74			{"count": count}
 75		)
 76		return MessageDbRow.model_validate(
 77			row, context=self.pydantic_context
 78		)
 79
 80	@validate_call
 81	def list_messages(self,
 82			id:str|None=None, sender:str|None=None, recipient:str|None=None,
 83			processed:bool|None=None, solution:bool|None=None,
 84			time_after:int|None=None, time_before:int|None=None,
 85			limit:int=10, offset:int=0
 86		) -> List[MessageDbRow]:
 87		"""
 88			Get the rows in the tables as list of messages.
 89			The arguments are used for filtering.
 90		"""
 91
 92		kwargs = locals().copy()
 93		params = {}
 94
 95		for k,v in kwargs.items():
 96			if k not in ('self',) and not v is None:
 97				params[k] = v
 98
 99		rows = self._get_request('list', params)
100
101		return [
102				MessageDbRow.model_validate(
103					row, context=self.pydantic_context
104				) for row in rows
105			]
106
107	@validate_call
108	def total_messages(self,
109			id:str|None=None, sender:str|None=None, recipient:str|None=None,
110			processed:bool|None=None, solution:bool|None=None,
111			time_after:int|None=None, time_before:int|None=None
112		) -> int:
113		"""
114			Get the total number of rows in the tables matching the filters.
115		"""
116		
117		kwargs = locals().copy()
118		params = {}
119
120		for k,v in kwargs.items():
121			if k not in ('self',) and not v is None:
122				params[k] = v
123
124		return int(self._get_request('app/table/total', params))
125
126	def _get_request(self, endpoint:str, params:Dict[str, Any]):
127		r = requests.get(
128			"{}/{}".format(self.MANAGEMENT_URL, endpoint),
129			params=params
130		)
131
132		if r.status_code == 200:
133			return r.json()
134		else:
135			raise RequestException(str(r.text)+"\n"+str(r.headers))
136
137	@validate_call
138	def send_message(self, ) -> AgentResponse:
139		# TODO
140		pass
141			
142	def _post_request(self, message:AgentMessage) -> AgentResponse:
143		# TODO
144
145		r = requests.post(
146			"{}/message".format(self.url),
147			data=message.model_dump_json(),
148			headers={"accept" : "application/json", "content-type" : "application/json"}
149		)
150
151		if r.status_code == 200:
152			return AgentResponse.model_validate_json(r.text)
153		else:
154			return AgentResponse(count=-1, error=True, error_msg=str(r.text)+str(r.headers))
class RequestException(builtins.Exception):
47class RequestException(Exception):
48	"""
49		Raised on http and similar errors.
50	"""
51	pass

Raised on http and similar errors.

Inherited Members
builtins.Exception
Exception
builtins.BaseException
with_traceback
add_note
args
class ManagementRequest:
 53class ManagementRequest():
 54
 55	MANAGEMENT_URL = os.environ.get('MANAGEMENT_URL', 'http://127.0.0.1:80').strip().strip('/')
 56
 57	@validate_call
 58	def __init__(self, allow_lazy:bool=True):
 59		"""
 60			If `allow_lazy` is active, the type checking (by pydantic) is less strict. 
 61			E.g. it does not require that all files in the data section of messages must exist on the file system.
 62		"""
 63		self.allow_lazy = allow_lazy
 64		self.pydantic_context = {
 65			"require_file_exists": not self.allow_lazy
 66		}
 67
 68	@validate_call
 69	def get_message(self, count:int) -> MessageDbRow:
 70		"""
 71			Get a message (like a table row) from the management by using the `count`.
 72		"""
 73		row = self._get_request(
 74			'list/single',
 75			{"count": count}
 76		)
 77		return MessageDbRow.model_validate(
 78			row, context=self.pydantic_context
 79		)
 80
 81	@validate_call
 82	def list_messages(self,
 83			id:str|None=None, sender:str|None=None, recipient:str|None=None,
 84			processed:bool|None=None, solution:bool|None=None,
 85			time_after:int|None=None, time_before:int|None=None,
 86			limit:int=10, offset:int=0
 87		) -> List[MessageDbRow]:
 88		"""
 89			Get the rows in the tables as list of messages.
 90			The arguments are used for filtering.
 91		"""
 92
 93		kwargs = locals().copy()
 94		params = {}
 95
 96		for k,v in kwargs.items():
 97			if k not in ('self',) and not v is None:
 98				params[k] = v
 99
100		rows = self._get_request('list', params)
101
102		return [
103				MessageDbRow.model_validate(
104					row, context=self.pydantic_context
105				) for row in rows
106			]
107
108	@validate_call
109	def total_messages(self,
110			id:str|None=None, sender:str|None=None, recipient:str|None=None,
111			processed:bool|None=None, solution:bool|None=None,
112			time_after:int|None=None, time_before:int|None=None
113		) -> int:
114		"""
115			Get the total number of rows in the tables matching the filters.
116		"""
117		
118		kwargs = locals().copy()
119		params = {}
120
121		for k,v in kwargs.items():
122			if k not in ('self',) and not v is None:
123				params[k] = v
124
125		return int(self._get_request('app/table/total', params))
126
127	def _get_request(self, endpoint:str, params:Dict[str, Any]):
128		r = requests.get(
129			"{}/{}".format(self.MANAGEMENT_URL, endpoint),
130			params=params
131		)
132
133		if r.status_code == 200:
134			return r.json()
135		else:
136			raise RequestException(str(r.text)+"\n"+str(r.headers))
137
138	@validate_call
139	def send_message(self, ) -> AgentResponse:
140		# TODO
141		pass
142			
143	def _post_request(self, message:AgentMessage) -> AgentResponse:
144		# TODO
145
146		r = requests.post(
147			"{}/message".format(self.url),
148			data=message.model_dump_json(),
149			headers={"accept" : "application/json", "content-type" : "application/json"}
150		)
151
152		if r.status_code == 200:
153			return AgentResponse.model_validate_json(r.text)
154		else:
155			return AgentResponse(count=-1, error=True, error_msg=str(r.text)+str(r.headers))
@validate_call
ManagementRequest(allow_lazy: bool = True)
57	@validate_call
58	def __init__(self, allow_lazy:bool=True):
59		"""
60			If `allow_lazy` is active, the type checking (by pydantic) is less strict. 
61			E.g. it does not require that all files in the data section of messages must exist on the file system.
62		"""
63		self.allow_lazy = allow_lazy
64		self.pydantic_context = {
65			"require_file_exists": not self.allow_lazy
66		}

If allow_lazy is active, the type checking (by pydantic) is less strict. E.g. it does not require that all files in the data section of messages must exist on the file system.

MANAGEMENT_URL = 'http://127.0.0.1:80'
allow_lazy
pydantic_context
@validate_call
def get_message(self, count: int) -> ums.utils.types.MessageDbRow:
68	@validate_call
69	def get_message(self, count:int) -> MessageDbRow:
70		"""
71			Get a message (like a table row) from the management by using the `count`.
72		"""
73		row = self._get_request(
74			'list/single',
75			{"count": count}
76		)
77		return MessageDbRow.model_validate(
78			row, context=self.pydantic_context
79		)

Get a message (like a table row) from the management by using the count.

@validate_call
def list_messages( self, id: str | None = None, sender: str | None = None, recipient: str | None = None, processed: bool | None = None, solution: bool | None = None, time_after: int | None = None, time_before: int | None = None, limit: int = 10, offset: int = 0) -> List[ums.utils.types.MessageDbRow]:
 81	@validate_call
 82	def list_messages(self,
 83			id:str|None=None, sender:str|None=None, recipient:str|None=None,
 84			processed:bool|None=None, solution:bool|None=None,
 85			time_after:int|None=None, time_before:int|None=None,
 86			limit:int=10, offset:int=0
 87		) -> List[MessageDbRow]:
 88		"""
 89			Get the rows in the tables as list of messages.
 90			The arguments are used for filtering.
 91		"""
 92
 93		kwargs = locals().copy()
 94		params = {}
 95
 96		for k,v in kwargs.items():
 97			if k not in ('self',) and not v is None:
 98				params[k] = v
 99
100		rows = self._get_request('list', params)
101
102		return [
103				MessageDbRow.model_validate(
104					row, context=self.pydantic_context
105				) for row in rows
106			]

Get the rows in the tables as list of messages. The arguments are used for filtering.

@validate_call
def total_messages( self, id: str | None = None, sender: str | None = None, recipient: str | None = None, processed: bool | None = None, solution: bool | None = None, time_after: int | None = None, time_before: int | None = None) -> int:
108	@validate_call
109	def total_messages(self,
110			id:str|None=None, sender:str|None=None, recipient:str|None=None,
111			processed:bool|None=None, solution:bool|None=None,
112			time_after:int|None=None, time_before:int|None=None
113		) -> int:
114		"""
115			Get the total number of rows in the tables matching the filters.
116		"""
117		
118		kwargs = locals().copy()
119		params = {}
120
121		for k,v in kwargs.items():
122			if k not in ('self',) and not v is None:
123				params[k] = v
124
125		return int(self._get_request('app/table/total', params))

Get the total number of rows in the tables matching the filters.

@validate_call
def send_message(self) -> ums.utils.types.AgentResponse:
138	@validate_call
139	def send_message(self, ) -> AgentResponse:
140		# TODO
141		pass