SlideShare a Scribd company logo
1 of 29
Concurrent programming with Agents
Tomáš Petříček
http://tomasp.net/blog
http://twitter.com/tomaspetricek
Introducing agents
Inside agent’s brain
Inter-agent communication
Reusable agents
Intelligence networks
Sequential programs
Task based parallelism
Agent-based concurrency
Agent-based concurrency
Programs compose from agents
Instead of functions or objects
Agents exchange messages
Receive message and react
Reactive system
Handle inputs while running
Emit results while running
Example
Introducing agents
Simple chat room
Functional loop with single state
Single state
Same reaction to all messages
Implemented using recursive loop
What if reaction depends on the state?
What if agent cannot handle some message?
Immutable state
Maintained as parameter of recursive function
Can use mutable collections for performance
Hiding agent’s brain
Accessing agent directly
Exposes implementation details
Users can call wrong methods (e.g. Receive)
Encapsulating agent
Agent as a private filed
Add methods for all (public) messages
Expose asynchronous calls first
Example
Encapsulating agent into an object
Exposing chat room via HTTP
Hiding agent’s brain
 Asynchronous calls from F#
 Synchronous calls from F# (optional)
 Asynchronous calls from C# (task based)
member x.AsyncGetContent(?timeout) =
agent.PostAndAsyncReply(GetContent, ?timeout=timeout)
member x.GetContent(?timeout) =
agent.PostAndReply(GetContent, ?timeout=timeout)
member x.GetContentAsync() =
Async.StartAsTask(agent.PostAndAsyncReply(GetContent))
member x.GetContentAsync(cancellationToken) =
Async.StartAsTask(agent.PostAndAsyncReply(GetContent),
cancellationToken=cancellationToken)
Introducing agents
Inside agent’s brain
Inter-agent communication
Reusable agents
Intelligence networks
Inside agent’s brain
Single state
Accept and react
to all messages
Example: Twitter status agent with pause
Resume
Pause
d
Running
Resume Status
Pause
Multiple states
Agent implements a
state machine
Example
Reading statuses from Twitter
Pausing the stream using blocking agent
State and state transitions
Accepting all messages
Asynchronously Receive and use pattern matching
Waiting for specific message
Other messages stay in the queue
Writing message handling using Scan
let rec state = agent.Scan(function
| Message -> Some <| async {
handleMessage()
return! newState }
| _ -> None )
Introducing agents
Inside agent’s brain
Inter-agent communication
Reusable agents
Intelligence networks
Inter-agent communication
Direct links between agents
Complicates reusability and reconfiguration
Decoupling using events
Expose event instead of sending message
We used events in the previous example!
Types of agent’s members
Send message to the agent
Members of type: 'T -> unit
Notifications from the agent
Exposed as events or observables: IObservable<'T>
No synchronization and no thread guarantees
Send and wait for a reply
Uses asynchronous reply channels from F# library
Takes arguments and returns result: 'T -> Async<'R>
Connecting agents
Sending message in response to notification
Alternatively, Observable.subscribe supports removal
Connecting agents with asynchronous actions
Create and start asynchronous workflow
source.Notification |> Observable.add target.Action
async { while true do
let! value = source.AsyncAction()
do! target.Action(value) }
|> Async.Start
Introducing agents
Inside agent’s brain
Inter-agent communication
Reusable agents
Intelligence networks
Reusable agents I.
Aggregating messages into bulks
Bulk specified number of messages
Emit bulk after timeout
Uses of bulking agent
Grouping data for further processing
Writing live data to a database
new BulkingAgent : int -> int -> BulkingAgent
member Enqueue : 'T -> unit
member BulkProduced : Event<'T[]>
Example
Bulk processing of Twitter statuses
A look at the BulkingAgent implementation
Reusable agents II.
Blocking queue with limited size
Block reader when queue is empty
Block adder when queue is full
Uses of blocking queue agent
The producer consumer pattern
Immediate buffer in pipeline processing
new BlockingQueueAgent : int -> BlockingQueueAgent
member AsyncGet : unit -> Async<'T>
member AsyncAdd : 'T -> Async<unit>
Introducing agents
Inside agent’s brain
Inter-agent communication
Reusable agents
Intelligence networks
Managing intelligence network
 Lots of things going on!
How to keep a big picture?
Using loosely coupled connections
Agents don’t reference each other directly
Common ways of organizing agents
Worker agent – Single agent does all the work
Layered network – Agent uses agents from lower level
Pipeline processing – Step-by-step processing
Pipeline processing
Values processed in multiple steps
Worker takes value, processes it, and sends it
Worker is blocked when source is empty
Worker is blocked when target is full
Steps of the pipeline run in parallel
Example
Pipeline image processing
Summary
Why use agent-based concurrency?
Easy to understand reactive applications
Elegant implementation of concurrent patterns
How to write an agent-based application?
State machine using recursive functions
Encapsulate and provide communication points
(send and send & reply methods and notifications)
Use reusable agents for recurring patterns
Questions?
Email: tomas@tomasp.net
Blog: http://tomasp.net/blog
Twitter: http://twitter.com/tomaspetricek
My book: http://functional-programming.net

More Related Content

Similar to Concurrent programming with Agents: Inside agent's brain

Oop2011 actor presentation_stal
Oop2011 actor presentation_stalOop2011 actor presentation_stal
Oop2011 actor presentation_stalMichael Stal
 
Architectural Patterns - Interactive and Event Handling Patterns
Architectural Patterns  - Interactive and Event Handling PatternsArchitectural Patterns  - Interactive and Event Handling Patterns
Architectural Patterns - Interactive and Event Handling Patternsassinha
 
Web Services 8
Web Services 8Web Services 8
Web Services 8pradeepfdo
 
Delegates and events
Delegates and eventsDelegates and events
Delegates and eventsIblesoft
 
Design patterns - ICIN 2010
Design patterns - ICIN 2010Design patterns - ICIN 2010
Design patterns - ICIN 2010steccami
 
Restate: Event-driven Asynchronous Services, Easy as Synchronous RPC
Restate: Event-driven Asynchronous Services, Easy as Synchronous RPCRestate: Event-driven Asynchronous Services, Easy as Synchronous RPC
Restate: Event-driven Asynchronous Services, Easy as Synchronous RPCHostedbyConfluent
 
Design Pattern with Actionscript
Design Pattern with ActionscriptDesign Pattern with Actionscript
Design Pattern with ActionscriptDaniel Swid
 
Android 101 Session @thejunction32
Android 101 Session @thejunction32Android 101 Session @thejunction32
Android 101 Session @thejunction32Eden Shochat
 
Distributed Objects and Remote Invocation
Distributed Objects and Remote InvocationDistributed Objects and Remote Invocation
Distributed Objects and Remote InvocationMedicaps University
 
Task communication
Task communicationTask communication
Task communication1jayanti
 
Ddd melbourne 2011 C# async ctp
Ddd melbourne 2011  C# async ctpDdd melbourne 2011  C# async ctp
Ddd melbourne 2011 C# async ctpPratik Khasnabis
 
Intention Oriented Model Interaction
Intention Oriented Model InteractionIntention Oriented Model Interaction
Intention Oriented Model InteractionYasir Karam
 

Similar to Concurrent programming with Agents: Inside agent's brain (20)

Oop2011 actor presentation_stal
Oop2011 actor presentation_stalOop2011 actor presentation_stal
Oop2011 actor presentation_stal
 
Architectural Patterns - Interactive and Event Handling Patterns
Architectural Patterns  - Interactive and Event Handling PatternsArchitectural Patterns  - Interactive and Event Handling Patterns
Architectural Patterns - Interactive and Event Handling Patterns
 
Web Services 8
Web Services 8Web Services 8
Web Services 8
 
IoT in salsa Serverless
IoT in salsa ServerlessIoT in salsa Serverless
IoT in salsa Serverless
 
Akka framework
Akka frameworkAkka framework
Akka framework
 
Delegates and events
Delegates and eventsDelegates and events
Delegates and events
 
Windows 8 BootCamp
Windows 8 BootCampWindows 8 BootCamp
Windows 8 BootCamp
 
Design patterns - ICIN 2010
Design patterns - ICIN 2010Design patterns - ICIN 2010
Design patterns - ICIN 2010
 
Event driven systems
Event driven systems Event driven systems
Event driven systems
 
Sysprog 10
Sysprog 10Sysprog 10
Sysprog 10
 
Sysprog 10
Sysprog 10Sysprog 10
Sysprog 10
 
Restate: Event-driven Asynchronous Services, Easy as Synchronous RPC
Restate: Event-driven Asynchronous Services, Easy as Synchronous RPCRestate: Event-driven Asynchronous Services, Easy as Synchronous RPC
Restate: Event-driven Asynchronous Services, Easy as Synchronous RPC
 
Design Pattern with Actionscript
Design Pattern with ActionscriptDesign Pattern with Actionscript
Design Pattern with Actionscript
 
Distributed System
Distributed System Distributed System
Distributed System
 
Android 101 Session @thejunction32
Android 101 Session @thejunction32Android 101 Session @thejunction32
Android 101 Session @thejunction32
 
Asynchronyin net
Asynchronyin netAsynchronyin net
Asynchronyin net
 
Distributed Objects and Remote Invocation
Distributed Objects and Remote InvocationDistributed Objects and Remote Invocation
Distributed Objects and Remote Invocation
 
Task communication
Task communicationTask communication
Task communication
 
Ddd melbourne 2011 C# async ctp
Ddd melbourne 2011  C# async ctpDdd melbourne 2011  C# async ctp
Ddd melbourne 2011 C# async ctp
 
Intention Oriented Model Interaction
Intention Oriented Model InteractionIntention Oriented Model Interaction
Intention Oriented Model Interaction
 

More from Tomas Petricek

Coeffects: A Calculus of Context-Dependent Computation
Coeffects: A Calculus of Context-Dependent ComputationCoeffects: A Calculus of Context-Dependent Computation
Coeffects: A Calculus of Context-Dependent ComputationTomas Petricek
 
Domain Specific Languages: The Functional Way
Domain Specific Languages: The Functional WayDomain Specific Languages: The Functional Way
Domain Specific Languages: The Functional WayTomas Petricek
 
F# Data: Making structured data first class citizens
F# Data: Making structured data first class citizensF# Data: Making structured data first class citizens
F# Data: Making structured data first class citizensTomas Petricek
 
Doing data science with F# (BuildStuff)
Doing data science with F# (BuildStuff)Doing data science with F# (BuildStuff)
Doing data science with F# (BuildStuff)Tomas Petricek
 
Doing data science with F#
Doing data science with F#Doing data science with F#
Doing data science with F#Tomas Petricek
 
F# and Financial Data Making Data Analysis Simple
F# and Financial Data Making Data Analysis SimpleF# and Financial Data Making Data Analysis Simple
F# and Financial Data Making Data Analysis SimpleTomas Petricek
 
Creating Domain Specific Languages in F#
Creating Domain Specific Languages in F#Creating Domain Specific Languages in F#
Creating Domain Specific Languages in F#Tomas Petricek
 
How F# Learned to Stop Worrying and Love the Data
How F# Learned to Stop Worrying and Love the DataHow F# Learned to Stop Worrying and Love the Data
How F# Learned to Stop Worrying and Love the DataTomas Petricek
 
Information-rich programming in F# (ML Workshop 2012)
Information-rich programming in F# (ML Workshop 2012)Information-rich programming in F# (ML Workshop 2012)
Information-rich programming in F# (ML Workshop 2012)Tomas Petricek
 
F# Type Providers in Depth
F# Type Providers in DepthF# Type Providers in Depth
F# Type Providers in DepthTomas Petricek
 
Asynchronous programming in F# (QCon 2012)
Asynchronous programming in F# (QCon 2012)Asynchronous programming in F# (QCon 2012)
Asynchronous programming in F# (QCon 2012)Tomas Petricek
 
Queries in general purpose languages
Queries in general purpose languagesQueries in general purpose languages
Queries in general purpose languagesTomas Petricek
 
Docase notation for Haskell
Docase notation for HaskellDocase notation for Haskell
Docase notation for HaskellTomas Petricek
 
Accessing loosely structured data from F# and C#
Accessing loosely structured data from F# and C#Accessing loosely structured data from F# and C#
Accessing loosely structured data from F# and C#Tomas Petricek
 

More from Tomas Petricek (19)

Coeffects: A Calculus of Context-Dependent Computation
Coeffects: A Calculus of Context-Dependent ComputationCoeffects: A Calculus of Context-Dependent Computation
Coeffects: A Calculus of Context-Dependent Computation
 
Domain Specific Languages: The Functional Way
Domain Specific Languages: The Functional WayDomain Specific Languages: The Functional Way
Domain Specific Languages: The Functional Way
 
F# Data: Making structured data first class citizens
F# Data: Making structured data first class citizensF# Data: Making structured data first class citizens
F# Data: Making structured data first class citizens
 
Doing data science with F# (BuildStuff)
Doing data science with F# (BuildStuff)Doing data science with F# (BuildStuff)
Doing data science with F# (BuildStuff)
 
Doing data science with F#
Doing data science with F#Doing data science with F#
Doing data science with F#
 
F# and Financial Data Making Data Analysis Simple
F# and Financial Data Making Data Analysis SimpleF# and Financial Data Making Data Analysis Simple
F# and Financial Data Making Data Analysis Simple
 
Creating Domain Specific Languages in F#
Creating Domain Specific Languages in F#Creating Domain Specific Languages in F#
Creating Domain Specific Languages in F#
 
How F# Learned to Stop Worrying and Love the Data
How F# Learned to Stop Worrying and Love the DataHow F# Learned to Stop Worrying and Love the Data
How F# Learned to Stop Worrying and Love the Data
 
Information-rich programming in F# (ML Workshop 2012)
Information-rich programming in F# (ML Workshop 2012)Information-rich programming in F# (ML Workshop 2012)
Information-rich programming in F# (ML Workshop 2012)
 
F# Type Providers in Depth
F# Type Providers in DepthF# Type Providers in Depth
F# Type Providers in Depth
 
Asynchronous programming in F# (QCon 2012)
Asynchronous programming in F# (QCon 2012)Asynchronous programming in F# (QCon 2012)
Asynchronous programming in F# (QCon 2012)
 
Queries in general purpose languages
Queries in general purpose languagesQueries in general purpose languages
Queries in general purpose languages
 
Docase notation for Haskell
Docase notation for HaskellDocase notation for Haskell
Docase notation for Haskell
 
Accessing loosely structured data from F# and C#
Accessing loosely structured data from F# and C#Accessing loosely structured data from F# and C#
Accessing loosely structured data from F# and C#
 
F# on the Server-Side
F# on the Server-SideF# on the Server-Side
F# on the Server-Side
 
F# Tutorial @ QCon
F# Tutorial @ QConF# Tutorial @ QCon
F# Tutorial @ QCon
 
Teaching F#
Teaching F#Teaching F#
Teaching F#
 
F# in MonoDevelop
F# in MonoDevelopF# in MonoDevelop
F# in MonoDevelop
 
Academia
AcademiaAcademia
Academia
 

Recently uploaded

How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?XfilesPro
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure servicePooja Nehwal
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersThousandEyes
 
Next-generation AAM aircraft unveiled by Supernal, S-A2
Next-generation AAM aircraft unveiled by Supernal, S-A2Next-generation AAM aircraft unveiled by Supernal, S-A2
Next-generation AAM aircraft unveiled by Supernal, S-A2Hyundai Motor Group
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticscarlostorres15106
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 
Key Features Of Token Development (1).pptx
Key  Features Of Token  Development (1).pptxKey  Features Of Token  Development (1).pptx
Key Features Of Token Development (1).pptxLBM Solutions
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):comworks
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machinePadma Pradeep
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationSafe Software
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 

Recently uploaded (20)

How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?
 
Vulnerability_Management_GRC_by Sohang Sengupta.pptx
Vulnerability_Management_GRC_by Sohang Sengupta.pptxVulnerability_Management_GRC_by Sohang Sengupta.pptx
Vulnerability_Management_GRC_by Sohang Sengupta.pptx
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
 
Next-generation AAM aircraft unveiled by Supernal, S-A2
Next-generation AAM aircraft unveiled by Supernal, S-A2Next-generation AAM aircraft unveiled by Supernal, S-A2
Next-generation AAM aircraft unveiled by Supernal, S-A2
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food Manufacturing
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping Elbows
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 
Key Features Of Token Development (1).pptx
Key  Features Of Token  Development (1).pptxKey  Features Of Token  Development (1).pptx
Key Features Of Token Development (1).pptx
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machine
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
The transition to renewables in India.pdf
The transition to renewables in India.pdfThe transition to renewables in India.pdf
The transition to renewables in India.pdf
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptxE-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
 

Concurrent programming with Agents: Inside agent's brain

  • 1. Concurrent programming with Agents Tomáš Petříček http://tomasp.net/blog http://twitter.com/tomaspetricek
  • 2. Introducing agents Inside agent’s brain Inter-agent communication Reusable agents Intelligence networks
  • 6. Agent-based concurrency Programs compose from agents Instead of functions or objects Agents exchange messages Receive message and react Reactive system Handle inputs while running Emit results while running
  • 8. Functional loop with single state Single state Same reaction to all messages Implemented using recursive loop What if reaction depends on the state? What if agent cannot handle some message? Immutable state Maintained as parameter of recursive function Can use mutable collections for performance
  • 9. Hiding agent’s brain Accessing agent directly Exposes implementation details Users can call wrong methods (e.g. Receive) Encapsulating agent Agent as a private filed Add methods for all (public) messages Expose asynchronous calls first
  • 10. Example Encapsulating agent into an object Exposing chat room via HTTP
  • 11. Hiding agent’s brain  Asynchronous calls from F#  Synchronous calls from F# (optional)  Asynchronous calls from C# (task based) member x.AsyncGetContent(?timeout) = agent.PostAndAsyncReply(GetContent, ?timeout=timeout) member x.GetContent(?timeout) = agent.PostAndReply(GetContent, ?timeout=timeout) member x.GetContentAsync() = Async.StartAsTask(agent.PostAndAsyncReply(GetContent)) member x.GetContentAsync(cancellationToken) = Async.StartAsTask(agent.PostAndAsyncReply(GetContent), cancellationToken=cancellationToken)
  • 12. Introducing agents Inside agent’s brain Inter-agent communication Reusable agents Intelligence networks
  • 13. Inside agent’s brain Single state Accept and react to all messages Example: Twitter status agent with pause Resume Pause d Running Resume Status Pause Multiple states Agent implements a state machine
  • 14. Example Reading statuses from Twitter Pausing the stream using blocking agent
  • 15. State and state transitions Accepting all messages Asynchronously Receive and use pattern matching Waiting for specific message Other messages stay in the queue Writing message handling using Scan let rec state = agent.Scan(function | Message -> Some <| async { handleMessage() return! newState } | _ -> None )
  • 16. Introducing agents Inside agent’s brain Inter-agent communication Reusable agents Intelligence networks
  • 17. Inter-agent communication Direct links between agents Complicates reusability and reconfiguration Decoupling using events Expose event instead of sending message We used events in the previous example!
  • 18. Types of agent’s members Send message to the agent Members of type: 'T -> unit Notifications from the agent Exposed as events or observables: IObservable<'T> No synchronization and no thread guarantees Send and wait for a reply Uses asynchronous reply channels from F# library Takes arguments and returns result: 'T -> Async<'R>
  • 19. Connecting agents Sending message in response to notification Alternatively, Observable.subscribe supports removal Connecting agents with asynchronous actions Create and start asynchronous workflow source.Notification |> Observable.add target.Action async { while true do let! value = source.AsyncAction() do! target.Action(value) } |> Async.Start
  • 20. Introducing agents Inside agent’s brain Inter-agent communication Reusable agents Intelligence networks
  • 21. Reusable agents I. Aggregating messages into bulks Bulk specified number of messages Emit bulk after timeout Uses of bulking agent Grouping data for further processing Writing live data to a database new BulkingAgent : int -> int -> BulkingAgent member Enqueue : 'T -> unit member BulkProduced : Event<'T[]>
  • 22. Example Bulk processing of Twitter statuses A look at the BulkingAgent implementation
  • 23. Reusable agents II. Blocking queue with limited size Block reader when queue is empty Block adder when queue is full Uses of blocking queue agent The producer consumer pattern Immediate buffer in pipeline processing new BlockingQueueAgent : int -> BlockingQueueAgent member AsyncGet : unit -> Async<'T> member AsyncAdd : 'T -> Async<unit>
  • 24. Introducing agents Inside agent’s brain Inter-agent communication Reusable agents Intelligence networks
  • 25. Managing intelligence network  Lots of things going on! How to keep a big picture? Using loosely coupled connections Agents don’t reference each other directly Common ways of organizing agents Worker agent – Single agent does all the work Layered network – Agent uses agents from lower level Pipeline processing – Step-by-step processing
  • 26. Pipeline processing Values processed in multiple steps Worker takes value, processes it, and sends it Worker is blocked when source is empty Worker is blocked when target is full Steps of the pipeline run in parallel
  • 28. Summary Why use agent-based concurrency? Easy to understand reactive applications Elegant implementation of concurrent patterns How to write an agent-based application? State machine using recursive functions Encapsulate and provide communication points (send and send & reply methods and notifications) Use reusable agents for recurring patterns
  • 29. Questions? Email: tomas@tomasp.net Blog: http://tomasp.net/blog Twitter: http://twitter.com/tomaspetricek My book: http://functional-programming.net