Sento is a 'message passing' library/framework with actors similar to Erlang or Akka. It supports creating systems that should work reactive, require parallel computing and event based message handling.
Sento features:
ask
(?
) and tell
(!
) operations. ask
can be asynchronous or synchronous.init
, get
and set
. There are also specialized Agents for Common Lisps array and hash-map data structures.ask
and tell
but collects multiple Actors for load-balancing.(Please also checkout the API documentation for further information) (for migrations from Sento v2, please check below migration guide)
The first thing you wanna do is to create an actor system. In simple terms, an actor system is a container where all actors live in. So at any time the actor system knows which actors exist.
To create an actor system we can first change package to :sento-user
because it imports the majority of necessary namespaces fopr convenience. Then, do:
(defvar *system* (make-actor-system))
When we look at *system*
in the repl we see some information of the actor system:
#<ACTOR-SYSTEM config: (DISPATCHERS (SHARED (WORKERS 4 STRATEGY RANDOM)) TIMEOUT-TIMER (RESOLUTION 500 MAX-SIZE 1000) EVENTSTREAM (DISPATCHER-ID SHARED) SCHEDULER (ENABLED TRUE RESOLUTION 100 MAX-SIZE 500) ), user actors: 0, internal actors: 5>
The actor-system
has, by default, four shared message dispatcher workers. Depending on how busy the system tends to be this default can be increased. Those four workers are part of the 'internal actors'. The 5th actor drives the event-stream (later more on that, but in a nutshell it's something like an event bus).
There are none 'user actors' yet, and the 'config' is the default config specifying the number of message dispatch workers (4) and the strategy they use to balance throughput, 'random' here.
Using a custom config is it possible to change much of those defaults. For instance, create custom dispatchers, i.e. a dedicated dispatcher used for the 'Tasks' api (see later for more info). The event-stream by default uses the global 'shared' dispatcher. Changing the config it would be possible to have the event-stream actor use a :pinned
dispatcher (more on dispatchers later) to optimize throughput. Etc.
Actors live in the actor system, but more concrete in an actor-context
. An actor-context
contains a collection (of actors) and represents a Common Lisp protocol that defines a set of generic functions for creating, removing and finding actors in an actor-context
. The actor system itself is also implementing the actor-context
protocol, so it also acts as such and hence the protocol ac
(actor-context
) is used to operate on the actor system.
I.e. to shutdown the actor system one has to execute: (ac:shutdown *system*)
.
Now we want to create actors.
(actor-of *system* :name "answerer" :receive (lambda (msg) (let ((output (format nil "Hello ~a" msg))) (reply output))))
This creates an actor in *system*
. Notice that the actor is not assigned to a variable (but you can). It is now registered in the system. Using function ac:find-actors
you'll be able to find it again. Of course it makes sense to store important actors that are frequently used in a defparameter
variable.
The :receive
key argument to actor-of
is a function which implements the message processing behaviour of an actor. The parameter to the 'receive' function is just the received message (msg).
actor-of
also allows to specify the initial state, a name, and a custom actor type via key parameters. By default a standard actor of type 'actor
is created. It is possible to subclass 'actor
and specify your own. It is further possible to specify an 'after initialization' function, using the :init
key, and 'after destroy' function using :destroy
keyword. :init
can, for example, be used to subscribe to the event-stream for listening to important messages.
The return value of 'receive' function is only used when using the synchronous ask-s
function to 'ask' the actor. Using ask
(equivalent: ?
) the return value is ignored. If an answer should be provided to an asking actor, or if replying is part of an interface contract, then reply
should be used.
The above actor was stored to a variable *answerer*
. We can evaluate this in repl and see:
#<ACTOR path: /user/answerer, cell: #<ACTOR answerer, running: T, state: NIL, message-box: #<SENTO.MESSAGEB:MESSAGE-BOX/DP mesgb-1356, processed messages: 1, max-queue-size: 0, queue: #<SENTO.QUEUE:QUEUE-UNBOUNDED 82701A6D13>>>>
We'll see the 'path' of the actor. The prefix '/user' means that the actor was created in a user actor context of the actor system. Further we see whether the actor is 'running', its 'state' and the used 'message-box' type, by default it uses an unbounded queue.
Now, when sending a message using 'ask' pattern to the above actor like so:
(? *answerer* "FooBar")
we'll get a 'future' as result, because ?
/ask
is asynchronous.
#<FUTURE promise: #<BLACKBIRD-BASE:PROMISE finished: NIL errored: NIL forward: NIL 80100E8B7B>>
We can check for a 'future' result. By now the answer from the *answerer*
(via reply
) should be available:
USER> (fresult *) "Hello FooBar"
If the reply had not been received yet, fresult
would return :not-ready
. So, fresult
doesn't block, it is necessary to repeatedly probe using fresult
until result is other than :not-ready
.
A nicer and asynchronous way without querying is to use fcompleted
. Using fcompleted
you setup a callback function that is called with the result when it is available. Like this:
(fcompleted (? *answerer* "Buzz") (result) (format t "The answer is: ~a~%" result))
Which will asynchronously print "The answer is: Hello Buzz" after a short while.
This will also work when the ask
/?
was used with a timeout, in which case result
will be a tuple of (:handler-error . <ask-timeout condition>)
if the operation timed out.
To build actor hierarchies one has to create actors in actors. This is of course possible. There are two options for this.
actor-of
s :init
function like so:(actor-of *system* :name "answerer-with-child" :receive (lambda (msg) (let ((output (format nil "Hello ~a" msg))) (reply output))) :init (lambda (self) (actor-of self :name "child-answerer" :receive (lambda (msg) (let ((output (format nil "Hello-child ~a" msg))) (format nil "~a~%" output))))))
Notice the context for creating 'child-answerer', it is self
, which is 'answerer-with-child'.
(actor-of *answerer* :name "child-answerer" :receive (lambda (msg) (let ((output (format nil "~a" "Hello-child ~a" msg))) (format nil "~a~%" output))))
This uses *answerer*
context as parameter of actor-of
. But has the same effect as above.
Now we can check if there is an actor in context of 'answerer-with-child':
USER> (all-actors *actor-with-child*) (#<ACTOR path: /user/answerer-with-child/child-answerer, cell: #<ACTOR child-answerer, running: T, state: NIL, message-box: #<SENTO.MESSAGEB:MESSAGE-BOX/DP mesgb-1374, processed messages: 0, max-queue-size: 0, queue: #<SENTO.QUEUE:QUEUE-UNBOUNDED 8200A195FB>>>>)
The 'path' is what we expected: '/user/answerer-with-child/child-answerer'.
Another example that only works with tell
/!
(fire and forget).
We have those two actors.
The 'ping' actor:
(defparameter *ping* (actor-of *system* :receive (lambda (msg) (cond ((consp msg) (case (car msg) (:start-ping (progn (format t "Starting ping...~%") (! (cdr msg) :ping *self*))))) ((eq msg :pong) (progn (format t "pong~%") (sleep 2) (reply :ping)))))))
And the 'pong' actor:
(defparameter *pong* (actor-of *system* :receive (lambda (msg) (case msg (:ping (progn (format t "ping~%") (sleep 2) (reply :pong)))))))
The 'ping' actor understands a :start-ping
message which is a cons
and has as cdr
the 'pong' actor instance.
It also understands a :pong
message as received from 'pong' actor.
The 'pong' actor only understands a :ping
message. Each of the actors respond with either :ping
or :pong
respectively after waiting 2 seconds.
We trigger the ping-pong by doing:
(! *ping* `(:start-ping . ,*pong*))
And then see in the console like:
Starting ping... ping pong ping ...
To stop the ping-pong one just has to send (! *ping* :stop)
to one of them.
:stop
will completely stop the actors message processing, and the actor will not be useable anymore.
At last an example for the synchronous 'ask', ask-s
. It is insofar similar to ask
that it provides a result to the caller. However, it is not bound to reply
as with ask
. Here, the return value of the 'receive' function is returned to the caller, and ask-s
will block until 'receive' function returns.
Beware that ask-s
will dead-lock your actor when ask-s
is used to call itself.
Let's make an example:
(defparameter *s-asker* (actor-of *system* :receive (lambda (msg) (cond ((stringp msg) (format nil "Hello ~a" msg)) (t (format nil "Unknown message!"))))))
So we can do:
USER> (ask-s *s-asker* "Foo") "Hello Foo" USER> (ask-s *s-asker* 'foo) "Unknown message!"
:pinned
vs. :shared
Dispatchers are somewhat alike thread pools. Dispatchers of the :shared
type are a pool of workers. Workers are actors using a :pinned
dispatcher. :pinned
just means that an actor spawns its own mailbox thread.
So :pinned
and :shared
are types of dispatchers. :pinned
spawns its own mailbox thread, :shared
uses a worker pool to handle the mailbox messages.
By default an actor created using actor-of
uses a :shared
dispatcher type which uses the shared message dispatcher that is automatically setup in the system.
When creating an actor it is possible to specify the dispatcher-id
. This parameter specifies which 'dispatcher' should handle the mailbox queue/messages.
Please see below for more info on dispatchers.
If actors are not directly stored in a dynamic or lexical context they can still be looked up and used. The actor-context
protocol contains a function find-actors
which can lookup actors in various ways. Checkout the API documentation.
Let's asume we have such a simple actor that just increments the value passed to it.
(defparameter *incer*
(actor-of *system*
:receive (lambda (value)
(reply (1+ value)))))
Since ask
returns a future it is possible to map multiple ask
operations like this:
(-> (ask *incer* 0)
(fmap (result)
(ask *incer* result))
(fmap (result)
(ask *incer* result))
(fcompleted (result)
(format t "result: ~a~%" result)
(assert (= result 3))))
A timeout (in seconds) can be specified for both ask-s
and
ask
and is done like so:
To demonstrate this we could setup an example 'sleeper' actor:
(ac:actor-of *system* :receive (lambda (msg) (sleep 5)))
If we store this to *sleeper*
and do the following, the
ask-s
will return a handler-error
with an
ask-timeout
condition.
(act:ask-s *sleeper* "Foo" :time-out 2)
(:HANDLER-ERROR . #<CL-GSERVER.UTILS:ASK-TIMEOUT #x30200319F97D>)
This works similar with the ask
only that the future will
be fulfilled with the handler-error
cons
.
To get a readable error message of the condition we can do:
CL-USER> (format t "~a" (cdr *))
A timeout set to 2 seconds occurred. Cause:
#<BORDEAUX-THREADS:TIMEOUT #x302002FAB73D>
Note that ask-s
uses the calling thread for the timeout checks.
ask
uses a wheel timer to handle timeouts. The default resolution for ask
timeouts is 500ms with a maximum size of wheel slots (registered timeouts) of 1000. What this means is that you can have timeouts of a multiple of 500ms and 1000 ask
operations with timeouts. This default can be tweaked when creating an actor-system, see API documentation for more details.
receive
Be careful with doing long running computations in the receive
function message handler, because it will block message processing. It is advised to use a third-party thread-pool or a library like lparallel to do the computations with, and return early from the receive
message handler.
The computation result can be 'awaited' for in an asynchronous manner and a response to *sender*
can be sent manually (via reply
). The sender of the original message is set to the dynamic variable *sender*
.
Due to an asynchronous callback of a computation running is a separate thread, the *sender*
must be copied into a lexical environment because at the time of when the callback is executed the *sender*
can have a different value.
For instance, if there is a potentially long running and asynchronous operation happening in 'receive', the original sender must be captured and the async operation executed in a lexical context, like so (receive function):
(lambda (msg) (case msg (:do-lengthy-op (let ((sender *sender*)) ;; do lengthy computation (reply :my-later-reply sender))) (otherwise ;; do other non async stuff (reply :my-reply))))
Notice that for the lengthy operation the sender must be captured because if the lengthy operation is asynchronous 'receive' function is perhaps called for another message where *sender*
is different. In that case sender
must be supplied explicitly for reply
.
See this test for more info.
NOTE: you should not change actor state from within an asynchronously executed operation in receive
. This is not
字节跳动发布的AI编程神器IDE
Trae是一种自适应的集成开发环境(IDE),通过自动化和多元协作改变开发流程。利用Trae,团队能够更快速、精确地编写和部署代码,从而提高编程效率和项目交付速度。Trae具备上下文感知和代码自动完成功能,是提升开发效率的理想工具。
AI小说写作助手,一站式润色、改写、扩写
蛙蛙写作—国内先进的AI写作平台,涵盖小说、学术、社交媒体等多场景。提供续写、改写、润色等功能,助力创作者高效优化写作流程。界面简洁,功能全面,适合各类写作者提升内容品质和工作效率。
全能AI智能助手,随时解答生活与工作的多样问题
问小白,由元石科技研发的AI智能助手,快速准确地解答各种生活和工作问题,包括但不限于搜索、规划和社交互动,帮助用户在日常生活中提高效率,轻松管理个人事务。
实时语音翻译/同声传译工具
Transly是一个多场景的AI大语言模型驱动的同声传译、专业翻译助手,它拥有超精准的音频识别翻译能力,几乎零延迟的使用体验和支持多国语言可以让你带它走遍全球,无论你是留学生、商务人士、韩剧美剧爱好者,还是出国游玩、多国会议、跨国追星等等,都可以满足你所有需要同传的场景需求,线上线下通用,扫除语言障碍,让全世界的语言交流不再有国界。
一键生成PPT和Word,让学习生活更轻松
讯飞智文是一个利用 AI 技术的项目,能够帮助用户生成 PPT 以及各类文档。无论是商业领域的市场分析报告、年度目标制定,还是学生群体的职业生涯规划、实习避坑指南,亦或是活动策划、旅游攻略等内容,它都能提供支持,帮助用户精准表达,轻松呈现各种信息。
深度推理能力全新升级,全面对标OpenAI o1
科大讯飞的星火大模型,支持语言理解、知识问答和文本创作等多功能,适用于多种文件和业务场景,提升办公和日常生活的效率。讯飞星火是一个提供丰富智能服务的平台,涵盖科技资讯、图像创作、写作辅助、编程解答、科研文献解读等功能,能为不同需求的用户提供便捷高效的帮助,助力用户轻松获取信息、解决问题,满足多样化使用场景。
一种基于大语言模型的高效单流解耦语音令牌文本到语音合成模型
Spark-TTS 是一个基于 PyTorch 的开源文本到语音合成项目,由多个知名机构联合参与。该项目提供了高效的 LLM(大语言模型)驱动的语音合成方案,支持语音克隆和语音创建功能,可通过命令行界面(CLI)和 Web UI 两种方式使用。用户可以根据需求调整语音的性别、音高、速度等参数,生成高质量的语音。该项目适用于多种场景,如有声读物制作、智能语音助手开发等。
AI助力,做PPT更简单!
咔片是一款轻量化在线演示设计工具,借助 AI 技术,实现从内容生成到智能设计的一站式 PPT 制作服务。支持多种文档格式导入生成 PPT,提供海量模板、智能美化、素材替换等功能,适用于销售、教师、学生等各类人群,能高效制作出高品质 PPT,满足不同场景演示需求。
选题、配图、成文,一站式创作,让内容运营更高效
讯飞绘文,一个AI集成平台,支持写作、选题、配图、排版和发布。高效生成适用于各类媒体的定制内容,加速品牌传播,提升内容营销效果。
专业的AI公文写作平台,公文写作神器
AI 材料星,专业的 AI 公文写作辅助平台,为体制内工作人员提供高效的公文写作解决方案。拥有海量公文文库、9 大核心 AI 功能,支持 30 + 文稿类型生成,助力快速完成领导讲话、工作总结、述职报告等材料,提升办公效率,是体制打工人的得力写作神器。
最新AI工具、AI资讯
独家AI资源、AI项目落地
微信扫一扫关注公众号