This module holds the ready-made processors of the SDK. Each class is a subclass of ModuleWrapper that builds a model and declares its input and output streams (proc_inputs and proc_outputs) by itself. Agent(proc=TinyLLama()) therefore needs no stream description. The classes fall into four families:
Recurrent and state-space networks that process a signal sample by sample (RNN, RNNTokenLM, CSSM, CDiagR, CDiagC, CTE, CTB, CTBE and their variants).
Image classifiers and a detector built on torchvision (CNN, ResNet, ViT, DenseNet, EfficientNet, FasterRCNN and the CNU variants).
Language and vision models that run locally through Hugging Face transformers (TinyLLama, LLama, Phi, SmolVLM, LangSegmentAnything, SiteRAG).
Clients of hosted language models (FeatherlessAPI, OpenRouterAPI).
The concepts behind them are in Models. Agents explains when the agent calls a processor in a worker thread and when inline.
fromunaiverse.agentimportAgentfromunaiverse.modules.networksimportResNetagent=Agent(proc=ResNet(d_dim=5))# One picture in, five scores in (0, 1) out
Every constructor ends with *args, **kwargs that go to ModuleWrapper.__init__. The useful ones are proc_opts (the optimizer and the losses, see Learning over time) and seed. seed seeds torch, random and numpy after the network of the class has been built. Because the weights exist by then, seed does not make them reproducible. Reproducible initial weights need a call of torch.manual_seed before the constructor.
The device of the wrapper comes from the device keyword argument, then from the environment variable PROC_DEVICE, then defaults to the CPU (see ModuleWrapper.guess_device). The classes with an explicit device parameter (the language and vision models) use the same rule for their model.
These networks keep a hidden state h of size h_dim across calls. They read two tensor streams and write one:
Stream
Kind
Shape
Content
proc_input_0
tensor, torch.float32
(None, *u_shape)
The signal u. The network flattens it to [b, u_dim] with u_dim the product of u_shape.
proc_input_1
tensor, torch.float32
(None, d_dim)
The descriptor du, an extra input concatenated before u.
proc_output_0
tensor, torch.float32
(None, y_dim)
The output y.
The inner module (the attribute module of the wrapper) has the signature forward(u, du, first=True). The agent passes first=True on the first step of an interaction and False on the following ones. With first=True the state restarts from h_init. This buffer of shape [batch_size, h_dim] is drawn from a normal distribution at construction. With first=False it continues from the state of the previous call. A None input stands for a zero tensor of the right shape.
The state-space networks (CSSM and the following classes) share these arguments and attributes:
Argument
Type
Default
Meaning
u_shape
tuple[int]
required
The shape of one sample of u without the batch dimension.
d_dim
int
required
The size of the descriptor du.
y_dim
int
required
The size of the output.
h_dim
int
required
The size of the state.
sigma
callable
torch.tanh for CSSM, the identity elsewhere
The function applied to the state before the output layer: y = C(sigma(h)).
project_every
int
0
The network projects the parameters of its transition onto a stable set once every project_every calls (the projection of each class is below). 0 never projects.
local
bool
False
True exposes the old state as h and reads the output from it. False exposes the new state.
batch_size
int
1
The batch size of h_init and of the zero inputs.
After each call the inner module exposes h, dh = (h_new - h) / delta and delta. These are the attributes that HL reads to run Hamiltonian Learning. CSSM, CDiagR and CDiagC use delta = 1.
A plain recurrent network with linear maps without bias: h = tanh(A h + B [du, u]) and y = C h.
Argument
Type
Default
Meaning
u_shape, d_dim, y_dim, h_dim, batch_size
As in the table above.
device
str, torch.device or None
None
The device to which the inner module moves its inputs.
With first=False the previous state enters the step detached from the graph. The class does not forward device to ModuleWrapper. The wrapper therefore places the network on PROC_DEVICE or on the CPU while the inputs go to device. A device different from that placement makes the first call fail with a device mismatch.
A recurrent language model over tokens: an embedding of num_emb tokens of size emb_dim, a state of size h_dim and a linear output of y_dim logits.
Argument
Type
Default
Meaning
num_emb
int
required
The size of the vocabulary.
emb_dim
int
required
The size of a token embedding.
y_dim
int
required
The number of output logits.
h_dim
int
required
The size of the state.
batch_size
int
1
The batch size of the initial state and of the initial input.
On a call with first=False the module ignores its input and feeds the embedding of the argmax of its previous output. This makes it generate a sequence by itself. On a call with first=True it uses its input only when the input is already a float tensor of shape [batch_size, emb_dim]. Any other input makes it start from a zero vector. A token id is never embedded on the first step. During learning ModuleWrapper.learn_backward replaces the stored output y with the target and the next step reads the right token (teacher forcing).
The declared streams do not match what the module returns. The output stream has shape (y_dim,) while the module returns [batch_size, y_dim]. Every call through the wrapper raises ValueError: Expected data with shape (y_dim,), got torch.Size([1, y_dim]). The inner module works when called directly.
A linear state-space network: h_new = A h + B [du, u] with a dense h_dim × h_dim matrix A. The output is C(sigma(h)) with sigma = torch.tanh by default. The projection of project_every does nothing in this class.
A state-space network with a diagonal real transition: h_new = a ⊙ h + B [du, u] where a is a learned vector of size h_dim. The projection replaces a with its sign and thus keeps each eigenvalue at +1 or -1.
The complex counterpart of CDiagR: a, B and C are complex (torch.cfloat) and the output is the real part of C(sigma(h)). The projection divides a by its modulus and thus puts every eigenvalue on the unit circle.
Real inputs fail
The input streams are torch.float32 while B is complex. A call with a real u or du raises RuntimeError: expected m1 and m2 to have the same dtype. Only a call where both inputs are None runs.
As in the shared table. The projection does nothing in this class.
delta
float
required
The length of the integration step.
cnu_memories
int
0
A positive value replaces the output layer C with a LinearCNU of cnu_memories keys. The CNU layer compares its keys with the input [du, u] and not with the state. It blends one memory per sample (the CNU argument delta=1) and moves its keys with beta_k equal to the integration step delta.
The step inverts A. Because an antisymmetric matrix of odd size is always singular, an odd h_dim makes the first call raise torch.linalg.LinAlgError. With cnu_memories > 0 the output weights are computed for a single sample and the network needs batch_size=1.
A CTE whose first sample fixes the initial state and whose dynamics then run without input. On first=True the state starts at B [du, u] divided by the sum of the elements of [du, u]. The input of every step, the first one included, is replaced by zeros before the transition. The arguments are those of CTE. The division is per sample and broadcasts correctly only with batch_size=1. An input whose elements sum to zero gives an infinite or undefined state.
A CTE over tokens. An embedding of num_emb tokens of size emb_dim turns each token id into u and the network runs with delta=1, no projection, local=False and batch_size=1.
Argument
Type
Meaning
num_emb
int
The size of the vocabulary.
emb_dim
int
The size of a token embedding.
d_dim, y_dim, h_dim
int
As in the shared table.
The declared input stream is a torch.float32 tensor of shape (None, emb_dim) while the embedding needs integer ids. The wrapper rejects an integer tensor (Expected data of type torch.float32) and the embedding rejects a float one. A call through the wrapper fails either way. The inner module works when called directly with a torch.long tensor of ids.
def__init__(self,u_shape:tuple[int],d_dim:int,y_dim:int,h_dim:int,delta:float=0.1,alpha:float=0.,sigma:Callable=lambdax:x,project_every:int=0,local:bool=False,batch_size:int=1,*args,**kwargs):u_shape=torch.Size(u_shape)u_dim=u_shape.numel()du_dim=d_dimasserth_dim%2==0,"Hidden dimension must be even for 2x2 blocks"classNet(torch.nn.Module):def__init__(self):super().__init__()self.order=h_dim//2self.omega=torch.nn.Parameter(torch.empty(self.order))self.register_buffer('ones',torch.ones(self.order,requires_grad=False))self.B=torch.nn.Linear(u_dim+du_dim,h_dim,bias=False)self.C=torch.nn.Linear(h_dim,y_dim,bias=False)assertalpha==-1.oralpha>=0.,"Invalid alpha value (must be -1, 0, or > 0)."ifalpha>0.:self.project_method='const'self.register_buffer('alpha',torch.full_like(self.omega.data,alpha))elifalpha==0.:self.project_method='modulus'self.register_buffer('alpha',torch.zeros_like(self.omega.data))elifalpha==-1.:self.project_method='alpha'self.register_buffer('alpha',torch.zeros_like(self.omega.data))self.register_buffer('h_init',torch.randn((batch_size,h_dim)))self.register_buffer('h_next',torch.randn((batch_size,h_dim)))self.h=Noneself.dh=Noneself.sigma=sigmaself.u_dim=u_dimself.du_dim=du_dimself.batch_size=batch_sizeself.delta=deltaself.local=localself.forward_count=0self.project_every=project_everyself.reset_parameters()defreset_parameters(self)->None:torch.nn.init.uniform_(self.omega)@torch.no_grad()defadjust_eigs(self):ifself.project_method=='alpha':self.alpha.copy_((1.-torch.sqrt(1.-(self.delta*self.omega)**2)/self.delta))elifself.project_method=='modulus':module=torch.sqrt(self.ones**2+(self.delta*self.omega)**2)self.omega.div_(module)self.ones.div_(module)# noinspection PyUnusedLocaldefinit_h(self,udu:torch.Tensor)->torch.Tensor:returnself.h_init.data@staticmethoddefhandle_inputs(du,u):returndu,udefforward(self,u:torch.Tensor,du:torch.Tensor,first:bool=True):device=self.h_init.deviceu=u.flatten(1).to(device)ifuisnotNoneelsetorch.zeros((self.batch_size,self.u_dim),device=device)du=du.to(device)ifduisnotNoneelsetorch.zeros((self.batch_size,self.du_dim),device=device)iffirst:h=self.init_h(torch.cat([du,u],dim=1))self.forward_count=0else:h=self.h_next.datah.requires_grad_()h_pair=h.view(-1,self.order,2)ifself.project_every:ifself.forward_count%self.project_every==0:self.adjust_eigs()du,u=self.handle_inputs(du,u)h1=(self.ones-self.delta*self.alpha)*h_pair[...,0]+self.delta*self.omega*h_pair[...,1]h2=-self.delta*self.omega*h_pair[...,0]+(self.ones-self.delta*self.alpha)*h_pair[...,1]rec=torch.stack([h1,h2],dim=-1).flatten(start_dim=1)inp=self.delta*self.B(torch.cat([du,u],dim=1))h_new=rec+inpifself.local:self.h=hself.dh=(h_new-self.h)/self.deltaelse:self.h=h_newself.dh=(self.h-h)/self.deltay=self.C(self.sigma(self.h))self.h_next.data=h_new.detach()self.forward_count+=1returnyproc_inputs,proc_outputs=get_proc_inputs_and_proc_outputs_for_rnn(u_shape,du_dim,y_dim)super(CTB,self).__init__(module=Net(),proc_inputs=proc_inputs,proc_outputs=proc_outputs,*args,**kwargs)
A network of h_dim / 2 independent 2D rotations integrated with an explicit Euler step. Each pair (h_a, h_b) of the state evolves as
As in the shared table. An odd h_dim makes the constructor raise AssertionError.
delta
float
0.1
The Euler step.
alpha
float
0.0
The damping on the diagonal. It also chooses the projection.
alpha
Damping
Projection
> 0
Constant, equal to alpha.
None.
0
None.
Divides omega and the diagonal by sqrt(1 + (delta·omega)²) to put the eigenvalues of each block on the unit circle.
-1
Starts at zero.
Replaces the damping with 1 - sqrt(1 - (delta·omega)²) / delta. With delta < 1 this value is negative and the blocks grow at every step. delta·omega > 1 gives NaN.
The exact counterpart of CTB without damping. Each pair of the state rotates by the angle omega·delta with cos and sin. The input term is the exact integral of the rotation over the step and contains a division by omega. A frequency close to zero therefore makes the input term large. The arguments are those of CTE (with delta required and cnu_memories available) and h_dim must be even. The projection does nothing in this class.
A CTBE whose first sample fixes the initial state and whose dynamics then run without input in the same way as CTEInitStateBZeroInput. Here the initial state is B [du, u] divided by the sum of all the elements of the batch. This version accepts any batch_size.
The classifiers read one picture (proc_input_0, an img stream) and write one tensor (None, y_dim) of torch.float32 scores (proc_output_0). With d_dim > 0 the scores come from a sigmoid and lie in (0, 1). With d_dim = -1 (where accepted) the pretrained head stays in place and the output holds its 1000 ImageNet logits. The wrapper turns the picture into a batch of one with a transform of transforms_factory. ViT, DenseNet, EfficientNet and FasterRCNN apply their own transform inside the module instead.
A small convolutional network for tests: three convolutions of 64, 128 and 256 channels with ReLU and average pooling, then LazyLinear(2048), ReLU, Linear(2048, d_dim) and a sigmoid.
Argument
Type
Default
Meaning
d_dim
int
required
The number of outputs.
in_channels
int
3
3 resizes the picture with "rgb<in_res>". Any other value uses "gray<in_res>".
in_res
int
32
The side of the square picture after resize and center crop.
LazyLinear creates its weights on the first call. An optimizer built before that call does not see them.
A single LinearCNU from the flattened picture (in_res · in_res · in_channels values) to d_dim outputs and a sigmoid after it. The arguments are those of CNNCNU.
CNN for MNIST: it forces in_channels=1 and in_res=28 and replaces the input transform with "gray_mnist". The arguments in_channels and in_res must not be passed by position.
Every call fails
The three MNIST classes replace the transform through set_stream_to_proc_transforms. That method stores a single transform where the stream expects a pair. Every call raises TypeError: 'Compose' object is not subscriptable. CNN(d_dim, in_channels=1, in_res=28) runs with the generic grayscale transform.
ResNet with a LinearCNU(2048, d_dim) and a sigmoid as last layer. The arguments d_dim and cnu_memories (both required), delta=1, scramble=False and freeze_backbone=True mean what they mean for ResNet and CNNCNU. With d_dim <= 0 the ImageNet head stays in place.
A torchvision ViT-B/16 with the IMAGENET1K_V1 weights and their own preprocessing. d_dim > 0 replaces the head with Linear(768, 2048), ReLU, Linear(2048, d_dim) and a sigmoid. Nothing is frozen. The attribute labels holds the class names. With d_dim > 0 they are "unk". With d_dim = -1 the constructor downloads the 1000 ImageNet names from https://raw.githubusercontent.com/pytorch/hub/master/imagenet_classes.txt and fails without network access.
A torchvision DenseNet-121 built with weights=None. Its weights are random and the 1000 outputs of d_dim = -1 carry no meaning until the network is trained. d_dim > 0 replaces the classifier as in ViT.
def__init__(self,*args,**kwargs):self.labels:list[str]=['__background__','person','bicycle','car','motorcycle','airplane','bus','train','truck','boat','traffic light','fire hydrant','N/A','stop sign','parking meter','bench','bird','cat','dog','horse','sheep','cow','elephant','bear','zebra','giraffe','N/A','backpack','umbrella','N/A','N/A','handbag','tie','suitcase','frisbee','skis','snowboard','sports ball','kite','baseball bat','baseball glove','skateboard','surfboard','tennis racket','bottle','N/A','wine glass','cup','fork','knife','spoon','bowl','banana','apple','sandwich','orange','broccoli','carrot','hot dog','pizza','donut','cake','chair','couch','potted plant','bed','N/A','dining table','N/A','N/A','toilet','N/A','tv','laptop','mouse','remote','keyboard','cell phone','microwave','oven','toaster','sink','refrigerator','N/A','book','clock','vase','scissors','teddy bear','hair drier','toothbrush']labels=self.labelsweights=torchvision.models.detection.FasterRCNN_ResNet50_FPN_Weights.DEFAULTfaster_rcnn=torchvision.models.detection.fasterrcnn_resnet50_fpn(weights=weights)faster_rcnn.eval()transforms=torchvision.transforms.Compose([transforms_factory("rgb-no_norm"),torchvision.transforms.Lambda(lambdax:x.squeeze(0)),weights.transforms()])classNet(torch.nn.Module):def__init__(self):super().__init__()self.backbone=faster_rcnnself.tfm=transformsself.labels=labelsdefforward(self,y:Image.Image):device=next(self.backbone.parameters()).deviceo=self.backbone([self.tfm(y).to(device)])# List with 1 image per element (no batch dim)found_class_indices=o[0]['labels']found_class_scores=o[0]['scores']found_class_boxes=o[0]['boxes']valid=found_class_scores>0.8found_class_indices:torch.Tensor=found_class_indices[valid]found_class_scores=found_class_scores[valid]found_class_boxes=found_class_boxes[valid]found_class_names:list[str]=[self.labels[int(i.item())]foriinfound_class_indices]returnfound_class_indices,found_class_scores,found_class_boxes,", ".join(found_class_names)super(FasterRCNN,self).__init__(module=Net(),proc_inputs=[StreamType(data_type="img",pubsub=False,private_only=False)],proc_outputs=[StreamType(data_type="tensor",tensor_dtype=torch.long,tensor_shape=(None,),pubsub=False,private_only=False),StreamType(data_type="tensor",tensor_dtype=torch.float32,tensor_shape=(None,),pubsub=False,private_only=False),StreamType(data_type="tensor",tensor_dtype=torch.float32,tensor_shape=(None,4),pubsub=False,private_only=False),StreamType(data_type="text",pubsub=False,private_only=False)],*args,**kwargs)
Object detection with the torchvision Faster R-CNN ResNet-50 FPN in evaluation mode (DEFAULT weights, COCO classes). It reads one picture and writes four streams:
Stream
Kind
Content
proc_output_0
tensor torch.long, shape (None,)
The class index of each detected object.
proc_output_1
tensor torch.float32, shape (None,)
The score of each object.
proc_output_2
tensor torch.float32, shape (None, 4)
The box of each object as (x1, y1, x2, y2) in pixels.
proc_output_3
text
The names of the objects separated by ", ".
Only the objects with a score above 0.8 are kept. The threshold is fixed. The attribute labels is the list of 91 COCO names indexed by class ("N/A" for the unused indices).
These classes download their model from Hugging Face the first time and run it on device (the argument, then PROC_DEVICE, then the CPU). A gated model needs a Hugging Face login on an account that has accepted its license.
def__init__(self,device=None,*args,**kwargs):classNet(torch.nn.Module):def__init__(self,_device):super().__init__()self.__pipe=pipeline("text-generation",model="TinyLlama/TinyLlama-1.1B-Chat-v1.0",torch_dtype=torch.bfloat16,device=_device)defforward(self,msg:str)->str:msg_struct=[{"role":"system","content":"You are a helpful assistant"},{"role":"user","content":msg}]assertself.__pipe.tokenizerisnotNoneprompt=self.__pipe.tokenizer.apply_chat_template(msg_struct,tokenize=False,add_generation_prompt=True)assertisinstance(prompt,str)out:list=self.__pipe(prompt,max_new_tokens=256,do_sample=True,temperature=0.7,top_k=50,top_p=0.95)out:str=out[0]["generated_text"]if(outisnotNoneandlen(out)>0and"generated_text"inout[0])else"Error!"if"<|assistant|>\n"inout:out=out.split("<|assistant|>\n")[1]returnout.strip()# Populate self.deviceself.guess_device(device)super(TinyLLama,self).__init__(module=Net(self.device),device=device,proc_inputs=[StreamType(data_type="text",pubsub=False,private_only=False)],proc_outputs=[StreamType(data_type="text",pubsub=False,private_only=False)],*args,**kwargs)
TinyLlama/TinyLlama-1.1B-Chat-v1.0 in bfloat16. It reads one text stream and writes one text stream. Each call wraps the message in a chat with the system prompt "You are a helpful assistant" and samples up to 256 new tokens with temperature=0.7, top_k=50 and top_p=0.95. The answer is the stripped text after the last assistant tag. An empty generation returns "Error!".
def__init__(self,device=None,*args,**kwargs):classNet(torch.nn.Module):def__init__(self,_device):super().__init__()self.__pipe=pipeline("text-generation",model="meta-llama/Llama-3.2-3B-Instruct",torch_dtype=torch.bfloat16,device=_device)defforward(self,msg:str)->str:msg_struct=[{"role":"system","content":"You are a helpful assistant"},{"role":"user","content":msg}]assertself.__pipe.tokenizerisnotNoneprompt=self.__pipe.tokenizer.apply_chat_template(msg_struct,tokenize=False,add_generation_prompt=True)assertisinstance(prompt,str)out=self.__pipe(prompt,max_new_tokens=256,do_sample=True,return_full_text=False,temperature=0.7,top_k=50,top_p=0.95)out=out[0]["generated_text"]if(outisnotNoneandlen(out)>0and"generated_text"inout[0])else"Error!"if"<|assistant|>\n"inout:out=out.split("<|assistant|>\n")[1]returnout.strip()# Populate self.deviceself.guess_device(device)super(LLama,self).__init__(module=Net(self.device),device=device,proc_inputs=[StreamType(data_type="text",pubsub=False,private_only=False)],proc_outputs=[StreamType(data_type="text",pubsub=False,private_only=False)],*args,**kwargs)
meta-llama/Llama-3.2-3B-Instruct in bfloat16 (a gated model). Streams, prompt and sampling are those of TinyLLama. The pipeline returns only the generated text.
def__init__(self,device=None,*args,**kwargs):classNet(torch.nn.Module):def__init__(self,_device):super().__init__()self.__pipe=pipeline("text-generation",model="microsoft/Phi-3.5-mini-instruct",torch_dtype="auto",device=_device)defforward(self,msg:str)->str:msg_struct=[{"role":"system","content":"You are a helpful assistant"},{"role":"user","content":msg}]assertself.__pipe.tokenizerisnotNoneprompt=self.__pipe.tokenizer.apply_chat_template(msg_struct,tokenize=False,add_generation_prompt=True)assertisinstance(prompt,str)out_:list=self.__pipe(prompt,max_new_tokens=256,do_sample=True,return_full_text=False)out:str=out_[0]["generated_text"]if(out_isnotNoneandlen(out_)>0and"generated_text"inout_[0])else"Error!"if"<|assistant|>\n"inout:out=out.split("<|assistant|>\n")[1]returnout.strip()# Populate self.deviceself.guess_device(device)super(Phi,self).__init__(module=Net(self.device),device=device,proc_inputs=[StreamType(data_type="text",pubsub=False,private_only=False)],proc_outputs=[StreamType(data_type="text",pubsub=False,private_only=False)],*args,**kwargs)
microsoft/Phi-3.5-mini-instruct with the dtype chosen by transformers. Streams and prompt are those of TinyLLama. It samples up to 256 new tokens with the default sampling options of the model.
def__init__(self,device=None,*args,**kwargs):fromtransformersimportAutoModelForImageTextToTextclassNet(torch.nn.Module):def__init__(self,_device):super().__init__()model_id="HuggingFaceTB/SmolVLM2-500M-Video-Instruct"self.__backbone=(AutoModelForImageTextToText.from_pretrained(model_id,torch_dtype=torch.bfloat16,device_map=_device).to(_device))self.__pp=AutoProcessor.from_pretrained(model_id,device_map=_device)defforward(self,image_pil:Image.Image,msg:str="what is this?"):image_pil=image_pil.convert("RGB")ifimage_pil.mode!="RGB"elseimage_pil# Forcing RGB_device=next(self.__backbone.parameters()).devicemsg_struct=[{"role":"user","content":[{"type":"text","text":f"{msg}"},{"type":"image","image":image_pil}]}]prompt=self.__pp.apply_chat_template(msg_struct,tokenize=True,add_generation_prompt=True,return_dict=True,return_tensors="pt").to(_device,dtype=torch.bfloat16)out=self.__backbone.generate(**prompt,do_sample=False,max_new_tokens=128)out=self.__pp.batch_decode(out,skip_special_tokens=True)[0]ifoutisnotNoneelse"Error!"if"Assistant:"inout:out=out.split("Assistant:")[1]returnout.strip()# Populate self.deviceself.guess_device(device)super(SmolVLM,self).__init__(module=Net(self.device),device=device,proc_inputs=[StreamType(data_type="img",pubsub=False,private_only=False),StreamType(data_type="text",pubsub=False,private_only=False)],proc_outputs=[StreamType(data_type="text",pubsub=False,private_only=False)],*args,**kwargs)
HuggingFaceTB/SmolVLM2-500M-Video-Instruct in bfloat16. It reads a picture (proc_input_0) and a text (proc_input_1) and writes a text. The module converts the picture to RGB, asks the question with greedy decoding and up to 128 new tokens and returns the text after "Assistant:". A call without text asks "what is this?".
def__init__(self,device=None,*args,**kwargs):fromlang_samimportLangSAMfromPILimportImageDraw,ImageFontclassNet(torch.nn.Module):def__init__(self,_device):super().__init__()# Generate a 64x64 error image (with text "Error" on it)error_img=Image.new("RGB",(64,64),color="white")draw=ImageDraw.Draw(error_img)font=ImageFont.load_default()text="Error"bbox=draw.textbbox((0,0),text,font=font)text_width=bbox[2]-bbox[0]text_height=bbox[3]-bbox[1]position=((64-text_width)//2,(64-text_height)//2)draw.text(position,text,fill="black",font=font)self.__sam=LangSAM(device=_device)self.__error_img=error_imgdefforward(self,image_pil:Image.Image,msg:str):try:image_pil=image_pil.convert("RGB")ifimage_pil.mode!="RGB"elseimage_pil# Forcing RGBout=self.__sam.predict([image_pil],[msg])if(outisNoneornotisinstance(out,list)orlen(out)<1ornotisinstance(out[0],dict)or'masks'notinout[0])orout[0]['masks'].ndim!=3:returnimage_pilelse:returnLangSegmentAnything.highlight_masks_on_image(image_pil,out[0]['masks'])exceptException:returnself.__error_img# Populate self.deviceself.guess_device(device)super(LangSegmentAnything,self).__init__(module=Net(self.device),device=device,proc_inputs=[StreamType(data_type="img",pubsub=False,private_only=False),StreamType(data_type="text",pubsub=False,private_only=False)],proc_outputs=[StreamType(data_type="img",pubsub=False,private_only=False)],*args,**kwargs)
Segmentation guided by text with LangSAM of the lang_sam package. The package is not a dependency of the SDK and the constructor raises ImportError without it. It reads a picture and a text and writes a picture: the input with the masks of the objects named by the text painted over it. A picture without masks comes back unchanged. Any exception during the call returns a 64 × 64 white picture with the word Error.
def__init__(self,site_url:str,site_folder:str=os.path.join("rag","downloaded_site"),db_folder:str=os.path.join("rag","chroma_db"),*args,**kwargs):# Saving optionsself.site_url=site_urlself.site_folder=site_folderself.db_folder=db_folder# Loading neural modeldevice_env=os.getenv("PROC_DEVICE",None)target_device=torch.device("cpu")ifdevice_envisNoneelsetorch.device(device_env)model_id="TheBloke/vicuna-7b-1.1-HF"tokenizer=AutoTokenizer.from_pretrained(model_id)# noqamodel=AutoModelForCausalLM.from_pretrained(model_id,torch_dtype=torch.float16,device_map=target_device,offload_folder="offload")pipe=pipeline("text-generation",model=model,tokenizer=tokenizer,max_new_tokens=200)# Embedderfromlangchain.embeddingsimportSentenceTransformerEmbeddingsself.embedder=SentenceTransformerEmbeddings(model_name="all-MiniLM-L6-v2",model_kwargs={"device":target_device.type})# Crawling site (uses self.embedder + self.site_folder + self.db_folder + self.site_url)self.crawl_website()self.crawled_site_to_rag_knowledge_base()# Setting up RAG stufffromlangchain.vectorstoresimportChromadb=Chroma(persist_directory=db_folder,embedding_function=self.embedder)retriever=db.as_retriever(search_kwargs={"k":3})classNet(torch.nn.Module):def__init__(self):super().__init__()self._pipe=pipeself._retriever=retrieverdefforward(self,msg:str):# Build contextdocs=self._retriever.get_relevant_documents(msg)context="\n\n".join(doc.page_contentfordocindocs)prompt=f"Answer the question based on the following context:\n\n{context}\n\nQuestion: {msg}\nAnswer:"# Generate answerout=self._pipe(prompt,max_new_tokens=256,do_sample=True,temperature=0.7)out=out[0]['generated_text'][len(prompt):].strip()if(outisnotNoneandlen(out)>0and"generated_text"inout[0])else"Error!"# Append source URLsbest_doc_with_score=self._retriever.vectorstore.similarity_search_with_score(msg,k=1)best_doc,_=best_doc_with_score[0]docs=[best_doc]sources=set("<a href='"+doc.metadata['source']+"' onclick='window.open(this.href); return false;' style='color: blue;'>"+doc.metadata['source']+"</a>"fordocindocs)sources_text="<br/><br/>\nURLs:\n"+"\n".join(sources)returnout.strip()+sources_textsuper(SiteRAG,self).__init__(module=Net(),proc_inputs=[StreamType(data_type="text",pubsub=False,private_only=False)],proc_outputs=[StreamType(data_type="text",pubsub=False,private_only=False)],*args,**kwargs)
Question answering over the pages of one web site with retrieval-augmented generation. The constructor does all the preparation:
It loads TheBloke/vicuna-7b-1.1-HF in float16 on PROC_DEVICE (or the CPU) with offload_folder="offload" in the working directory.
It loads the embedder all-MiniLM-L6-v2.
It calls crawl_website() and crawled_site_to_rag_knowledge_base().
It opens the vector store in db_folder with a retriever of the 3 closest chunks.
Argument
Type
Default
Meaning
site_url
str
required
The first page. The crawler follows only the links that start with this string.
site_folder
str
"rag/downloaded_site"
The folder of the downloaded pages. The constructor deletes it with all its content and creates it again.
db_folder
str
"rag/chroma_db"
The folder of the vector store.
The class needs packages that the SDK does not declare: requests, beautifulsoup4, chromadb, sentence-transformers and a release of langchain that still provides the import paths langchain.embeddings, langchain.vectorstores, langchain.docstore and langchain.text_splitter. It reads one text stream and writes one text stream. The answer is the generated text (sampling with temperature=0.7, up to 256 tokens) followed by <br/><br/> and an HTML link to the page closest to the question.
Downloads up to max_pages pages (default 300) breadth-first from site_url into site_folder. The method deletes site_folder first. It keeps only the responses of type text/html and saves each one as <path>.crawled with / replaced by __ (index.html.crawled for the root). A request times out after 10 seconds. Errors are printed and skipped. The constructor calls it.
Extracts the text of every .crawled file in site_folder, splits it into chunks of 1000 characters with an overlap of 100, embeds the chunks and writes them to a persistent vector store in db_folder. Each chunk keeps the URL of its page as source. The constructor calls it after crawl_website().
Both clients read one text stream and write one text stream. They accept the same sampling options. An option left at its default (a negative number or None) is not sent and the provider applies its own default. The options that the OpenAI chat-completions API accepts as named fields (OPENAI_NATIVE_SAMPLER_PARAMS in utils) go into those fields. Every other option (top_k, repetition_penalty, min_p and the keys of sampler) travels in the extra body of the request.
Argument
Type
Default
Meaning
system_prompt
str
""
The system message of every call. "" sends no system message.
max_tokens
int
-1
The maximum number of generated tokens. Sent only when positive.
temperature
float
-1.0
Sent only when >= 0.
top_p
float
-1.0
Sent only when >= 0.
top_k
int
-1
Sent only when >= 0.
frequency_penalty
float or None
None
Sent only when not None.
presence_penalty
float or None
None
Sent only when not None.
repetition_penalty
float or None
None
Sent only when not None. Providers without it ignore it.
min_p
float or None
None
Sent only when not None. Providers without it ignore it.
sampler
dict or None
None
Any other option. Its keys are merged last and win over the arguments above.
These clients report a failure through log.critical and the call raises unaiverse.custom.GenException.
def__init__(self,model:str|None=None,cost:int=1,system_prompt:str="",process_id:str|None=None,max_tokens:int=-1,temperature:float=-1.,top_p:float=-1.,top_k:int=-1,frequency_penalty:float|None=None,presence_penalty:float|None=None,repetition_penalty:float|None=None,min_p:float|None=None,sampler:dict|None=None,connect_timeout:float=15.0,api_key:str|None=None,key_units:int|None=None,*args,**kwargs):"""Create a FeatherlessAPI handle and connect it to the shared gateway. Args: model: The model identifier used for every call (None lets the server fall back to its MODEL_ID default). cost: The unit cost charged for every call (one of VALID_COSTS) (Default: 1). system_prompt: The system prompt prepended to every call ("" means no system prompt) (Default: ""). process_id: Identifier used for round-robin fairness; defaults to this process's PID. max_tokens: Maximum number of tokens to generate per call (-1 means no limit) (Default: -1). temperature: Sampling temperature for every call (negative lets the API use its default) (Default: -1.). top_p: Nucleus-sampling probability (negative lets the API use its default) (Default: -1.). top_k: Top-k sampling cutoff (negative lets the API use its default) (Default: -1). frequency_penalty: Frequency penalty (None lets the API use its default) (Default: None). presence_penalty: Presence penalty (None lets the API use its default) (Default: None). repetition_penalty: Repetition penalty, a vLLM/Featherless extension (None uses the default) (Default None). min_p: Minimum-probability cutoff, a vLLM/Featherless extension (None uses the default) (Default: None). sampler: Extra sampler params merged last (its keys win); use it for any knob not covered above. connect_timeout: Maximum seconds to wait for the gateway server to come up (Default: 15.0). api_key: The Featherless API key (account) charged for every call; None falls back to the FEATHERLESS_API_KEY environment variable (Default: None). key_units: The total unit budget supported by the account of ``api_key``; None falls back to the FEATHERLESS_KEY_UNITS environment variable (the gateway sizes each account's budget on first sight of its key, later mismatching declarations are ignored) (Default: None). """ifcostnotinAPIGatewayServer.VALID_COSTS:log.critical(f"Invalid cost {cost}: it must be one of {APIGatewayServer.VALID_COSTS}")# Bring up the shared gateway server before opening any sockets (idempotent across processes)FeatherlessAPI._ensure_server(connect_timeout)classNet(torch.nn.Module):"""Holds the sampler config and the two gateway sockets, and routes each `forward(prompt)` through the gateway. Plain Python attributes (socket, dict, str): none get registered as torch submodules since none are `nn.Module`/`Parameter`/`Tensor`."""def__init__(self):super().__init__()self.model_name:str|None=modelself.cost:int=costself.system_prompt:str=system_prompt# Account: the API key charged for every call and the total unit budget of that account. Both travel# with each request, so the gateway can keep per-key queues/budgets whatever process spawned itself.api_key:str=api_keyoros.environ.get("FEATHERLESS_API_KEY","")self.key_units:int=key_unitsifkey_unitsisnotNoneelse(int(os.environ.get("FEATHERLESS_KEY_UNITS","8")))ifnotself.api_key:log.critical("No API key: the api_key argument was not given ""and FEATHERLESS_API_KEY was not set!")# Per-call sampler: include each knob only when explicitly set, so unset ones fall back# to the API default. The free-form `sampler` arg is merged last and overrides.self.sampler:dict={}ifmax_tokens>0:self.sampler["max_tokens"]=max_tokensiftemperature>=0.:self.sampler["temperature"]=temperatureiftop_p>=0.:self.sampler["top_p"]=top_piftop_k>=0:self.sampler["top_k"]=top_kiffrequency_penaltyisnotNone:self.sampler["frequency_penalty"]=frequency_penaltyifpresence_penaltyisnotNone:self.sampler["presence_penalty"]=presence_penaltyifrepetition_penaltyisnotNone:self.sampler["repetition_penalty"]=repetition_penaltyifmin_pisnotNone:self.sampler["min_p"]=min_pifsampler:self.sampler.update(sampler)# Round-robin fairness is per process; default ID is the PIDself.process_id:str=str(process_idifprocess_idisnotNoneelseos.getpid())# Persistent registration socket: lifetime == this caller's interest in the gatewayself._reg:socket.socket=socket.create_connection((APIGatewayServer.HOST,APIGatewayServer.PORT))self._reg.sendall(b'{"op":"hello"}\n')# Separate request socket (one in-flight request per instance; this client is synchronous)self._req:socket.socket=socket.create_connection((APIGatewayServer.HOST,APIGatewayServer.PORT))self._rf=self._req.makefile("r")defforward(self,prompt:str)->str:ifnotisinstance(prompt,str):log.critical(f"Invalid prompt: it must be a str, got {type(prompt).__name__}")msg=json.dumps({"op":"generate","process_id":self.process_id,"sys_prompt":self.system_prompt,"prompt":prompt,"cost":self.cost,"model":self.model_name,"sampler":self.sampler,"api_key":self.api_key,"key_units":self.key_units})+"\n"self._req.sendall(msg.encode())line=self._rf.readline()ifnotline:log.critical("Gateway closed the connection")resp=json.loads(line)ifnotresp.get("ok"):log.critical(f"Gateway returned an error: {resp.get('error','unknown error')}")returnresp["result"]defclose(self)->None:"""Close both gateway sockets, releasing this caller's interest."""forsin(self._req,self._reg):try:s.close()exceptOSError:passsuper(FeatherlessAPI,self).__init__(module=Net(),proc_inputs=[StreamType(data_type="text",pubsub=False,private_only=False)],proc_outputs=[StreamType(data_type="text",pubsub=False,private_only=False)],*args,**kwargs)
A client of Featherless. All the FeatherlessAPI instances of one machine send their requests through one local gateway process (APIGatewayServer in utils). The gateway keeps one budget of units per API key and serves the processes in turn. Many agents can therefore share one account without exceeding its concurrency limit.
Argument
Type
Default
Meaning
model
str or None
None
The Featherless model of every call. None lets the gateway use the environment variable MODEL_ID.
cost
int
1
The units that each call takes from the budget. It must be one of APIGatewayServer.VALID_COSTS (1, 2, 4 by default).
process_id
str or None
None
The identity under which the gateway queues the requests of the caller. None uses the PID. Instances with the same process_id share one queue.
connect_timeout
float
15.0
The seconds to wait for the gateway to come up.
api_key
str or None
None
The Featherless key. None reads FEATHERLESS_API_KEY.
key_units
int or None
None
The total units of the account. None reads FEATHERLESS_KEY_UNITS (default 8). The first request that mentions a key fixes its budget in the gateway. Later values are ignored.
The sampling arguments are those of the shared table. The constructor runs four steps:
It raises GenException when cost is not valid.
It starts the gateway when nobody listens on GW_HOST:GW_PORT (default 127.0.0.1:11321). The gateway is a detached process python -c "from unaiverse.modules.utils import serve_api_gateway; serve_api_gateway()" started under a file lock that lets only one process start it. The constructor raises GenException when the gateway is not reachable within connect_timeout.
It raises GenException when there is no API key.
It opens two TCP connections to the gateway: one that registers the instance for as long as it lives and one for the requests.
A call sends the prompt, blocks until the gateway answers and returns the text. It has no timeout of its own. A call whose prompt is not a str, an error reported by the gateway and a closed connection all raise GenException. The gateway stops when the last registered instance closes. The gateway writes on the terminal of the process that started it because its output is not redirected.
The gateway calls Featherless through the openai package. The SDK does not declare this package and without it every call fails with an error from the gateway. A request whose cost exceeds the budget of its key can never be served. The gateway holds it forever, the caller blocks and every later request on the same key waits behind it.
fromunaiverse.modules.networksimportFeatherlessAPIwithFeatherlessAPI(model="meta-llama/Meta-Llama-3.1-8B-Instruct",cost=1,max_tokens=200)asapi:text=api("Name three rivers of Italy.")[0]
defclose(self)->None:"""Close both the request and the persistent registration socket, releasing this caller's interest."""assertself.moduleisnotNoneifhasattr(self.module,'close'):self.module.close()
Closes the two connections of this instance. The gateway shuts down when no registered instance is left. Leaving a with block calls it. A process that exits closes the connections as well.
def__init__(self,model:str|None=None,system_prompt:str="",max_tokens:int=-1,temperature:float=-1.,top_p:float=-1.,top_k:int=-1,frequency_penalty:float|None=None,presence_penalty:float|None=None,repetition_penalty:float|None=None,min_p:float|None=None,sampler:dict|None=None,api_key:str|None=None,timeout:float=120.,max_retries:int=3,*args,**kwargs):"""Create an OpenRouterAPI handle with its own OpenAI-compatible client. Args: model: The OpenRouter model slug used for every call, e.g. "openai/gpt-4o" (None falls back to the OPENROUTER_MODEL_ID environment variable) (Default: None). system_prompt: The system prompt prepended to every call ("" means no system prompt) (Default: ""). max_tokens: Maximum number of tokens to generate per call (-1 means no limit) (Default: -1). temperature: Sampling temperature for every call (negative lets the API use its default) (Default: -1.). top_p: Nucleus-sampling probability (negative lets the API use its default) (Default: -1.). top_k: Top-k sampling cutoff (negative lets the API use its default) (Default: -1). frequency_penalty: Frequency penalty (None lets the API use its default) (Default: None). presence_penalty: Presence penalty (None lets the API use its default) (Default: None). repetition_penalty: Repetition penalty, ignored by providers not supporting it (Default: None). min_p: Minimum-probability cutoff, ignored by providers not supporting it (Default: None). sampler: Extra params merged last (its keys win); use it for any knob not covered above, including OpenRouter-specific fields such as "provider", "models" (fallback chain) or "reasoning". api_key: The OpenRouter API key charged for every call; None falls back to the OPENROUTER_API_KEY environment variable (Default: None). timeout: Maximum seconds to wait for a single HTTP request (Default: 120.). max_retries: Maximum number of attempts per call, with exponential backoff in between (Default: 3). """ifmax_retries<1:log.critical(f"Invalid max_retries {max_retries}: it must be at least 1")classNet(torch.nn.Module):"""Holds the sampler config and the OpenRouter client, and sends each `forward(prompt)` straight to the API. Plain Python attributes (client, dict, str): none get registered as torch submodules since none are `nn.Module`/`Parameter`/`Tensor`."""def__init__(self):super().__init__()fromopenaiimportOpenAIfromopenai.types.chatimportChatCompletionself._completion_type=ChatCompletionself.model_name:str=modeloros.environ.get("OPENROUTER_MODEL_ID","")self.system_prompt:str=system_promptself.max_retries:int=max_retriesifnotself.model_name:log.critical("No model: the model argument was not given ""and OPENROUTER_MODEL_ID was not set!")# Account: the API key charged for every callkey=api_keyoros.environ.get("OPENROUTER_API_KEY","")ifnotkey:log.critical("No API key: the api_key argument was not given ""and OPENROUTER_API_KEY was not set!")# Process-local client, reused for every call so HTTP keep-alive avoids a fresh TLS handshake per# query. SDK-level retries are off: forward() retries on its own, also covering empty contentself._client=OpenAI(base_url="https://openrouter.ai/api/v1",api_key=key,timeout=timeout,max_retries=0,default_headers={"HTTP-Referer":"https://unaiverse.io","X-Title":"UNaIVERSE"})# Per-call sampler: include each knob only when explicitly set, so unset ones fall back# to the API default. The free-form `sampler` arg is merged last and overrides.self.sampler:dict={}ifmax_tokens>0:self.sampler["max_tokens"]=max_tokensiftemperature>=0.:self.sampler["temperature"]=temperatureiftop_p>=0.:self.sampler["top_p"]=top_piftop_k>=0:self.sampler["top_k"]=top_kiffrequency_penaltyisnotNone:self.sampler["frequency_penalty"]=frequency_penaltyifpresence_penaltyisnotNone:self.sampler["presence_penalty"]=presence_penaltyifrepetition_penaltyisnotNone:self.sampler["repetition_penalty"]=repetition_penaltyifmin_pisnotNone:self.sampler["min_p"]=min_pifsampler:self.sampler.update(sampler)# Split the sampler once: OpenAI-native keys go top-level, the rest (top_k, min_p, provider, models,# ...) ride along in extra_body, otherwise the OpenAI SDK rejects them as unexpected argumentsself._native:dict={k:vfork,vinself.sampler.items()ifkinOPENAI_NATIVE_SAMPLER_PARAMS}self._extra_body:dict={k:vfork,vinself.sampler.items()ifknotinOPENAI_NATIVE_SAMPLER_PARAMS}defforward(self,prompt:str)->str:ifnotisinstance(prompt,str):log.critical(f"Invalid prompt: it must be a str, got {type(prompt).__name__}")# Always use chat completions; include the system message only when a system prompt is givenmsgs=[{"role":"system","content":self.system_prompt}]ifself.system_promptelse[]msgs.append({"role":"user","content":prompt})# The dict is typed dict[str, object] so PyCharm accepts the mixed value types (str/list/int/float)_kwargs:dict[str,object]={"model":self.model_name,"messages":msgs,**self._native}ifself._extra_body:_kwargs["extra_body"]=self._extra_body# Retry with exponential backoff, keeping the last error so a final failure reports its causelast_err=Noneforattemptinrange(self.max_retries):try:resp=self._client.chat.completions.create(**_kwargs)# type: ignoreifnotisinstance(resp,self._completion_type):log.critical(f"Unexpected response type {type(resp).__name__}: streaming is not supported")# Return the first choice that carries non-empty text (content may be None)forchoiceinresp.choices:content=choice.message.contentifcontentisnotNoneandcontent.strip():returncontent# Empty/blank content: treat it as a transient failure so the loop retries instead of ""finish=resp.choices[0].finish_reasonifresp.choiceselse"n/a"last_err=RuntimeError(f"Empty content from model (finish_reason={finish})")exceptExceptionase:last_err=e# No point sleeping after the last attemptifattempt+1<self.max_retries:log.error(f"Empty response or exception! (model={self.model_name}, attempt={attempt+1}, "f"last_err={last_err!r}), waiting {2**attempt} seconds before trying again...")time.sleep(2**attempt)log.critical(f"OpenRouter call failed after retries: {last_err!r}")# This will raise an exceptionreturn""# Never reacheddefclose(self)->None:"""Close the HTTP client, releasing its pooled connections."""try:self._client.close()exceptException:passsuper(OpenRouterAPI,self).__init__(module=Net(),proc_inputs=[StreamType(data_type="text",pubsub=False,private_only=False)],proc_outputs=[StreamType(data_type="text",pubsub=False,private_only=False)],*args,**kwargs)
A client of OpenRouter. Each instance talks to https://openrouter.ai/api/v1 directly with its own HTTP client. There is no gateway and no budget.
Argument
Type
Default
Meaning
model
str or None
None
The OpenRouter model slug, such as "openai/gpt-4o". None reads OPENROUTER_MODEL_ID.
api_key
str or None
None
The OpenRouter key. None reads OPENROUTER_API_KEY.
timeout
float
120.0
The seconds allowed to one HTTP request.
max_retries
int
3
The attempts per call. A value below 1 raises GenException.
The sampling arguments are those of the shared table. sampler also carries OpenRouter fields such as provider, models (a fallback chain) or reasoning. The class needs the openai package. The SDK does not declare it and without it the constructor raises ImportError. A missing model or key raises GenException.
A call sends the prompt as a user message and returns the first non-blank text of the answer. An exception, a rate limit or a blank answer counts as a failed attempt. The client logs it on the ERROR channel and waits 2 ** attempt seconds (1, 2, 4, ...) before the next attempt. After max_retries failed attempts the call raises GenException with the last error. Every request carries the headers HTTP-Referer: https://unaiverse.io and X-Title: UNaIVERSE.
fromunaiverse.agentimportAgentfromunaiverse.modules.networksimportOpenRouterAPIagent=Agent(proc=OpenRouterAPI(model="meta-llama/llama-3.3-70b-instruct",system_prompt="You are the concierge of a small hotel.",temperature=0.3,max_tokens=300))
defclose(self)->None:"""Close the underlying HTTP client, releasing its pooled connections."""assertself.moduleisnotNoneifhasattr(self.module,'close'):self.module.close()
Closes the HTTP client and its pooled connections. Leaving a with block calls it.