This example illustrates the creation of streams and agents. The program structure is:

# 1. Define streams
    numbers = Stream('integers from 2')
    prime_stream = Stream('prime numbers')

    # 2. Define agents
    sieve(numbers, prime_stream)

    # 3. Put values into input stream.
    numbers.extend(list(range(2, N)))

    return prime_stream

The agent sieve(numbers, prime_stream) puts the prime numbers up to N on prime_stream. For example if N is 10 then the program terminates with prime_stream containing the sequence [2, 3, 5, 7].

The agent sieve creates additional streams and additional sieve agents.

    #---------------------------------------------------------------
    # The function encapsulated by the agent
    #---------------------------------------------------------------
    def f(v, state, prime_stream, out_stream):
        """
        Parameters
        ----------
        v: an element of an input stream
        state: int
          Initially 0, to indicate that no elements of the input stream
          have been read. Then it becomes the first element of the input
          stream, and from then on state remains unchanged.
        prime_stream: Stream
          A stream of prime numbers. This function appends a prime number
          to this stream.
        out_stream: Stream
          Initially an empty stream. It consists of elements of the
          input stream that are not multiples of state (after state
          becomes the first element of the input stream).

        """
        if state == 0:
            # This is the first value read on the input stream.
            # Assumption: first value must be a prime number. So append it
            # to the stream of primes.
            prime_stream.append(v)
            # Make the new state the first value on the input stream. This
            # state remains unchanged from now onwards.
            state = v
            # Create an agent that sieves out_stream.
            sieve(out_stream, prime_stream)
        # Put elements of the input stream that are not multiples of state
        # on the output stream.
        if v % state != 0:
            out_stream.append(v)
        # A stateful function encapsulated by a sink agent must return the
        # next state. So, return state.
        return state
    #---------------------------------------------------------------
    # Create the agent
    #---------------------------------------------------------------
    # Create a sink agent that encapsulates a stateful function f with
    # an initial state of 0. Pass parameters prime_stream and
    # out_stream from the sink agent to its encapsulated function.
    sink(func=f, in_stream=in_stream, state=0,
         prime_stream=prime_stream, out_stream=Stream())