Modularity¶
During the development process, we may have already had some individual automas. Now, we want to combine them to create a more powerful automa. An automa can also be added as a Worker to another Automa to achieve reuse.
Let's understand it with a sample case.
Report Writer¶
The typical process of report writing usually involves drafting an outline based on user input and then writing the report according to the outline. Now, let's first write an Automa for generating an outline, and then nest it within the Automa for writing the report.
1. Initialize¶
Initialize the runtime environment.
import os
# Set the API base and key.
_api_key = os.environ.get("OPENAI_API_KEY")
_api_base = os.environ.get("OPENAI_API_BASE")
_model_name = os.environ.get("OPENAI_MODEL_NAME")
# Import the necessary modules.
from typing import List
from pydantic import BaseModel, Field
from bridgic.core.automa import GraphAutoma, worker
from bridgic.core.model.types import Message, Role
from bridgic.core.model.protocols import PydanticModel
from bridgic.llms.openai import OpenAILlm
llm = OpenAILlm(api_base=_api_base, api_key=_api_key, timeout=30)
2. Outline Automa¶
Outline Automa drafts an outline based on user input. Output an Outline object for subsequent processing.
class Outline(BaseModel):
outline: List[str] = Field(description="The outline of the use input to write report")
class OutlineWriter(GraphAutoma):
@worker(is_start=True)
async def pre_query(self, user_input: str): # Receive the user's input and preprocess query
return user_input
@worker(dependencies=["pre_query"], is_output=True)
async def topic_split(self, query: str):
response: Outline = await llm.astructured_output(
model=_model_name,
messages=[
Message.from_text(text="Write a sample report outline within 3 topics based on the user's input", role=Role.SYSTEM),
Message.from_text(text=query, role=Role.USER,),
],
constraint=PydanticModel(model=Outline)
)
return response
3. Write Automa¶
We can reuse the OutlineWriter in ReportWriter.
class ReportWriter(GraphAutoma):
@worker(dependencies=["outline_writer"])
async def write_report(self, outline: Outline):
outline_str = "\n".join(outline.outline)
print(f'- - - - - Outline - - - - -')
print(outline_str)
print(f'- - - - - End - - - - -\n')
response = await llm.achat(
model=_model_name,
messages=[
Message.from_text(text="write a sample report based on the user's input and strictly follow the outline", role=Role.SYSTEM),
Message.from_text(text=f"{outline_str}.", role=Role.USER),
],
)
print(f'- - - - - Report - - - - -')
print(response.message.content)
print(f'- - - - - End - - - - -\n')
return response.message.content
report_writer = ReportWriter()
report_writer.add_worker(
key="outline_writer",
worker=OutlineWriter(),
is_start=True
)
Now, let's run it!
await report_writer.arun(user_input="What is an agent?")
- - - - - Outline - - - - - Definition of an Agent Types of Agents in Different Contexts Role and Function of Agents in AI and Automation - - - - - End - - - - - - - - - - Report - - - - - **Report: Definition of an Agent, Types of Agents in Different Contexts, and Role and Function of Agents in AI and Automation** --- **1. Definition of an Agent** An *agent* is an autonomous entity that perceives its environment through sensors and acts upon that environment using actuators to achieve specific goals. In a broad sense, an agent is capable of making decisions based on its internal state and external inputs, adapting its behavior over time in response to changing conditions. The concept of an agent is foundational in artificial intelligence (AI), robotics, and automated systems. It operates independently or in coordination with other agents, following predefined rules, learning from experience, or using reasoning mechanisms to perform tasks efficiently. In computational terms, an agent typically consists of: - **Perception**: Sensing and interpreting environmental inputs. - **Reasoning/Decision-making**: Processing information to determine the best course of action. - **Action**: Executing decisions through physical or digital means. Agents can be simple (e.g., a thermostat adjusting temperature) or complex (e.g., AI-driven trading bots in financial markets). --- **2. Types of Agents in Different Contexts** Agents vary significantly depending on the domain or context in which they operate. Below are key types categorized by application areas: **a. In Artificial Intelligence (AI):** - **Simple Reflex Agents**: Make decisions based solely on current percept. Example: A thermostat that turns on the heater when the room temperature drops below a threshold. - **Model-Based Reflex Agents**: Use an internal model of the world to make decisions. Example: A self-driving car that predicts traffic patterns based on historical data. - **Goal-Based Agents**: Act to achieve specific goals. Example: A virtual assistant like Siri or Alexa that performs tasks such as setting reminders or sending messages. - **Utility-Based Agents**: Choose actions that maximize expected utility. Example: An AI recommending a product based on user preferences and potential profit. - **Learning Agents**: Improve performance over time through experience. Example: A recommendation engine that learns user behavior and adjusts suggestions. **b. In Robotics:** - **Autonomous Robots**: Operate independently in dynamic environments (e.g., drones, warehouse robots). - **Human-Robot Collaborative Agents**: Work alongside humans (e.g., robotic arms in manufacturing). - **Mobile Agents**: Move through physical environments to perform tasks (e.g., delivery robots). **c. In Software and Business Automation:** - **Business Process Agents**: Automate routine tasks like invoice processing or customer service responses. - **Workflow Agents**: Coordinate multiple tasks within a system (e.g., workflow management in CRM software). - **Customer Service Agents**: Chatbots that respond to user queries in real time. **d. In Distributed Systems:** - **Multi-Agent Systems (MAS)**: Groups of agents that interact to solve complex problems (e.g., traffic management, supply chain optimization). - **Swarm Agents**: Simulate collective behavior (e.g., ant colonies, drone swarms). --- **3. Role and Function of Agents in AI and Automation** Agents play a pivotal role in advancing AI and automation by enabling intelligent, adaptive, and scalable systems. Their key functions include: - **Autonomy and Decision-Making**: Agents operate independently, making real-time decisions without constant human intervention, which is essential in dynamic environments such as autonomous vehicles or smart homes. - **Adaptability and Learning**: Through machine learning and reinforcement learning, agents evolve their strategies based on feedback, improving accuracy and efficiency over time. - **Efficiency and Scalability**: Agents can perform repetitive or time-consuming tasks quickly and consistently, reducing human workload and operational costs. For example, AI agents in customer service reduce response times and increase service availability. - **Interoperability and Integration**: Agents can communicate and collaborate across different platforms and systems, enabling seamless integration in enterprise environments (e.g., connecting ERP, CRM, and supply chain systems). - **Problem Solving and Optimization**: In complex domains like logistics or energy management, agents use algorithms to find optimal solutions, such as route planning or load balancing. - **Human-AI Collaboration**: Agents serve as intelligent interfaces between humans and machines, enhancing user experience by providing personalized, context-aware assistance. In summary, agents are central to the development of intelligent systems that can perceive, reason, act, and learn—making them indispensable in modern AI and automation ecosystems. --- **Conclusion** The concept of an agent bridges the gap between passive systems and intelligent, responsive automation. From simple rule-based tools to sophisticated AI-driven entities, agents are transforming how systems interact with their environments. As AI and automation continue to evolve, the design, deployment, and coordination of agents will remain a critical focus area across industries, driving innovation, efficiency, and human-machine collaboration. --- *End of Report* - - - - - End - - - - -
Great! We successfully reused OutlineWriter in ReportWriter.
What have we done¶
we added an automa as a Worker to another Automa to achieve nested reuse. There are several points that need special attention during the reuse process:
- Worker Dependency: A
Workerin anAutomacan only depend on other workers within the sameAutoma, and cannot depend across differentAutoma. - Routing: A
Workerin anAutomacan only route to other workers within the sameAutoma, and cannot route across differentAutoma. - Human-in-the-loop: When a worker inside throws an event, it hands over this event to the automa agent for handling. At this point, the event handling functions of nested automa need to be registered to the outermost Automa.