Skip to content

Language model

A language model joins the network in the same way as any other processor. A Node hosts an Agent that takes text and returns text. The SDK ships ready-made processors for the two common cases. The first runs a small model on your own hardware and the second forwards every prompt to a hosted service. A third script asks either of them a question.

The sources are in examples-src/language-model/.

A model on your machine

local_model.py
"""Serves TinyLlama-1.1B-Chat as a lone wolf: text in, text out, on your own machine."""
from unaiverse.agent import Agent
from unaiverse.modules.networks import TinyLLama
from unaiverse.networking.node.node import Node

agent = Agent(proc=TinyLLama(), proc_inputs=["text"], proc_outputs=["text"])
node = Node(agent, node_name="TinyLLama", hidden=True, clock_delta=1. / 10.)
node.run()

TinyLLama wraps the chat model TinyLlama/TinyLlama-1.1B-Chat-v1.0 from Hugging Face in a text-generation pipeline. It prepends the system prompt "You are a helpful assistant", samples at most 256 new tokens (temperature 0.7, top-k 50, top-p 0.95) and returns only the answer of the assistant. Phi does the same with microsoft/Phi-3.5-mini-instruct. Both choose the device from their device argument, then from the environment variable PROC_DEVICE and finally fall back to the CPU. The first run downloads the weights from Hugging Face.

The strings "text" in proc_inputs and proc_outputs are shorthand for StreamType(data_type="text").

A hosted model

hosted_model.py
"""Serves a model hosted by Featherless: the node keeps no weights, every call goes to the service."""
from unaiverse.agent import Agent
from unaiverse.modules.networks import FeatherlessAPI
from unaiverse.networking.node.node import Node

# The key comes from FEATHERLESS_API_KEY when api_key is not given
model = FeatherlessAPI(model="Qwen/Qwen3-32B", cost=2, max_tokens=512, temperature=0.3,
                       system_prompt="You are a museum guide. Answer in at most three sentences.",
                       sampler={"chat_template_kwargs": {"enable_thinking": False}})

agent = Agent(proc=model, proc_inputs=["text"], proc_outputs=["text"])
node = Node(agent, node_name="MuseumGuide", hidden=True, clock_delta=1. / 25.)
node.run()

FeatherlessAPI keeps no weights on the node. Every forward pass sends the prompt to Featherless and returns the text of the answer. The main parameters are:

Parameter Meaning
model the identifier of the model on Featherless
cost the concurrency units that one call of this model takes on your Featherless plan: 1, 2 or 4
system_prompt prepended to every call ("" for none)
max_tokens, temperature, top_p, top_k, min_p, frequency_penalty, presence_penalty, repetition_penalty sampling settings (a negative number or None keeps the default of the service)
sampler any other field of the request, merged last
api_key the Featherless key, read from the environment variable FEATHERLESS_API_KEY when omitted
key_units the units of your plan, read from FEATHERLESS_KEY_UNITS (8 by default) when omitted

The first FeatherlessAPI processor of a machine starts a small local gateway that all the others share. The gateway queues the calls of every process and keeps the total cost under the units of each key. When the last processor goes away, the gateway stops by itself.

OpenRouterAPI has the same sampling parameters and calls OpenRouter directly without any gateway or units. Its key comes from api_key or from OPENROUTER_API_KEY. The model comes from model or from OPENROUTER_MODEL_ID. For a call that fails it makes at most max_retries attempts (3 by default) and waits longer before each new attempt.

Ask a question

ask.py
"""Asks one question to a text agent of the same account and prints the answer."""
import sys
from unaiverse.agent import Agent
from unaiverse.streams import StreamType
from unaiverse.interaction import CompletionReason
from unaiverse.networking.node.node import Node

TARGET = sys.argv[1] if len(sys.argv) > 1 else "TinyLLama"
QUESTION = sys.argv[2] if len(sys.argv) > 2 else "Who painted the Primavera?"


class Asker(Agent):
    """An agent without a processor that asks one question and prints the answer."""

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.request = None
        self.answered = False

    async def behave(self):
        await super().behave()
        if self.request is None and self.resolve_agent_ref(TARGET) is not None:
            if await self.send(action_name="process", target=TARGET,
                               data_samples={"proc_output_0": QUESTION},
                               callback="on_done"):
                self.request = self.get_last_sent_interaction()

        # The answer arrives under the uuid of the request on the processor stream of the target
        if self.request is not None and not self.answered:
            for streams in self.find_streams(self.request.target[0], "processor").values():
                for stream in streams.values():
                    answer = stream.get(uuid=self.request.uuid)
                    if answer is not None and not self.answered:
                        self.answered = True
                        print(f"{TARGET}: {answer}")

    async def on_done(self, interaction=None):
        if interaction.completion_reason != CompletionReason.OK:
            print(f"No answer: {interaction.completion_reason}")
        return True


agent = Asker(proc=None, proc_inputs=[StreamType(data_type="text")], proc_outputs=[StreamType(data_type="text")])
node = Node(agent, node_name="Asker", hidden=True, clock_delta=1. / 10.)
node.run(get_in_touch=TARGET, max_time=120.)

Like the client of the image classifier, it sends a process request with the question as the sample of its own text output. It then reads the answer on the processor stream of the target under the uuid of the request.

python local_model.py
python ask.py TinyLLama "Who painted the Primavera?"
export FEATHERLESS_API_KEY=...
python hosted_model.py
python ask.py MuseumGuide "Where is the Primavera kept today?"

Forms and corrective rounds

A language model is the processor that most often receives an interactive message, for example a form with three options from a quiz world. The model reads the form as its text instruction (the alt of the block) and writes an answer in free text. Before that answer leaves the node, the agent checks it against the form. When the answer does not satisfy the form, the agent asks the model again up to two more times (UAI_MAX_RETRIES) and tells it why the answer was rejected. After the last round the agent sends a reply block with the values it could read and the text of the model. From this block the asker learns which values are missing. The agent withholds only an empty answer and an answer that would arrive after the interaction expired. The quiz shows the world side of this exchange.