Arklex AI

repository·main·Indexed 20 days ago

https://github.com/arklexai/agent-first-organization

An agent-first framework for building, deploying, and scaling intelligent multi-agent systems. It utilizes a task-graph-based architecture to orchestrate workers and tools, featuring a TaskGraphGenerator to convert natural language descriptions and domain knowledge into structured JSON configurations. The framework includes an Orchestrator for runtime execution, specialized workers built with LangGraph, and tool integrations via LangChain and LlamaIndex.

Tokens
56.8K
Snippets
152
Records
190
Agent score
72%

What's inside arklex

  1. What is the Arklex AI Agent Framework?

    main

    Arklex is an agent-first framework designed to bridge the gap between structured AI workflows and autonomous AI agents. It combines the robustness of structured workflows with the adaptability of modern agents, making it suitable for complex applications like AI-driven coding, research, and automation.

    Core Components

    • Task Graphs: Structured graphs of agents, workers, and tools that encode reusable logic and workflows.
    • Agents: LLM-powered planners that break down complex tasks and make tool and worker calls through step-by-step reasoning.
    • Workers: Executable units (or subgraphs) that perform tasks or recursively invoke other workers.
    • Tools: Functional units (API calls, search, retrieval, etc.) with built-in validation.
    • Natural Language Understanding (NLU): Semantic parsing of user input for intent and argument extraction.
    • Task Composition: Dynamic breakdown of tasks into reusable, composable components.
    • Human Oversight: Built-in logic for compliance, safety, and fallback to human review.
    • Continual Learning: Automatic evolution of task graphs based on successful or failed trajectories.
  2. Understand the documentation directory structure

    main

    The documentation repository is organized as follows:

    • docs/docs/: Contains the main documentation pages.
      • Config/: Configuration guides.
      • Example/: Usage examples and tutorials.
      • Integration/: Third-party integrations.
      • Workers/: Worker documentation.
      • Evaluation/: Testing and evaluation guides.
    • docs/static/: Static assets such as images.
    • docs/src/: Docusaurus source files.
  3. What is a SearchWorker?

    main
    A SearchWorker is a specialized worker designed to retrieve real-time data from the internet to address complex or time-sensitive queries. Unlike a RAGWorker which retrieves from local documents, the SearchWorker uses the Tavily search engine API to fetch up-to-date information from the web and then generates coherent, user-specific responses based on those results.
  4. What is a TaskGraph in Arklex AI

    main

    A TaskGraph is a blueprint used by agents to break down complex processes into manageable tasks and actionable steps. It serves as a framework of guidelines, guardrails, and strategies that allow multiple workers to collaborate reliably while remaining adaptable to user needs.

    Conceptually, a TaskGraph is a directed graph consisting of:

    • Nodes: Represent specific steps, milestones, or tasks that an agent must accomplish using different workers. Nodes can hold attributes representing the resources required for that step (e.g., company policies, databases, or user profiles).
    • Edges: Represent the user's intent and the execution sequence. The direction of the edge indicates the order in which tasks must be performed.
  5. What is a MessageWorker?

    main

    A MessageWorker is the fundamental building block for handling chat responses in Arklex. It is responsible for delivering messages to the user, whether they are questions or informational responses. Because it is a base component, it can be combined with other workers to create complex conversational processes.

    Internally, a MessageWorker uses a LangGraph StateGraph consisting of a START node and a generator node. The generator node processes the MessageState to produce a response using an LLM.

  6. What is a RAGWorker and how does it work?

    main

    A RAGWorker is a core building block used to implement Retrieval Augmented Generation (RAG). It enables a bot to retrieve relevant information from internal documentation (like policies, FAQs, or product info) and compose an answer based on that context.

    The worker operates as a pipeline consisting of three stages:

    1. Start Node: The entry point of the workflow.
    2. Retriever Node: Uses RetrieveEngine.retrieve to find relevant information by applying FAISS (Facebook AI Similarity Search) on documents located in the path specified by the DATA_DIR environment variable.
    3. Tool Generator Node: Uses ToolGenerator.context_generate to construct a response using the retrieved context and the user's question.

    The internal logic is managed via a LangGraph StateGraph using MessageState.

    graph LR;
        start["START"]--"retrieve()"-->retriever["retriever"]--"context_generate()"-->tool_generator["tool_generator"];
  7. Understand User Simulator evaluation metrics

    main

    When evaluating agent performance using the User Simulator, Arklex AI analyzes three primary metrics to determine the effectiveness of the chatbot and the success of the interaction:

    1. User's goal completion rate: Measures the percentage of conversations where the chatbot successfully fulfills the user's stated goal. Higher is better.
    2. User's goal completion efficiency: Measures the average number of turns (interactions) the chatbot requires to complete the user's goal. Lower is better.
    3. Bot's goal completion rate: Measures the percentage of conversations where the chatbot successfully fulfills the builder's (system) goal. Higher is better.
  8. How TaskGraph generation works

    main

    A TaskGraph is generated from a Config file (a JSON document). The Generator processes the configuration to create a structured sequence of tasks matched to specific workers.

    The generation lifecycle follows these steps:

    1. Generate high-level tasks: The Generator uses the role, user_objective, domain, intro, and task_docs from the Config to identify the primary tasks the bot must handle.
    2. Generate task planning: High-level tasks that are not directly actionable by a provided Worker are broken down into multiple granular steps or instructions.
    3. Interactive with builder: The Generator provides an interactive command-line interface (using textual) allowing a human 'builder' to add, delete, or modify tasks and steps.
    4. Fine-tune steps: The generated task planning is refined based on the builder_objective (which may contain specific strategies or hidden objectives).
    5. Match tasks with workers: The final plan is mapped to the workers defined in the Config. If no workers are specified, steps are assigned to default workers.
  9. How Arklex AI architecture works

    main

    Arklex AI is built around a multi-agent orchestration model using a Task Graph. The core components include:

    • Task Graph: Declarative Directed Acyclic Graph (DAG) workflows that define the agent's logic.
    • Orchestrator: The runtime engine responsible for state management and executing the task graph.
    • Workers: Specialized units that handle specific tasks such as RAG (Retrieval-Augmented Generation), database operations, or web automation.
    • Tools: Integrations that allow agents to interact with external services like Shopify, HubSpot, or Google Calendar.
  10. How the User Simulator works

    main

    The User Simulator evaluates chatbot performance by simulating user interactions through a two-pass process:

    1. Goal Completion Pass: Simulates user utterances based on a configuration file to interact with the chatbot. It measures the task success rate based on the completion of both the user's goal and the builder's goal.
    2. NLU Performance Pass: Simulates user utterances based on a generated taskgraph to interact with the chatbot. It measures intent prediction accuracy to evaluate Natural Language Understanding (NLU) performance.

    This simulator is designed to generate large volumes of synthetic user inputs to test the chatbot across various scenarios.

  11. How TaskGraphs and Config files work together

    main

    In Arklex, an agent is powered by a TaskGraph, which is a structured graph of tasks that the agent traverses during a conversation. Each node in the graph represents a task assigned to a Worker.

    Instead of manually designing complex graphs, you can use a Config JSON file to describe your agent's role, objectives, and domain. The Arklex generator then converts this intuitive configuration into a functional TaskGraph. This process automates the creation of conversation flows, making the agent more controllable and reliable.

    {
        "role": "customer service assistant",
        "user_objective": "...",
        "builder_objective": "...",
        "domain": "...",
        "workers": [...]
    }
  12. How MessageWorker generates responses

    main

    The generator method follows a specific logic flow to produce a response:

    1. Unpack MessageState: It extracts user_message, orchestrator_message, and existing message_flow (concatenating response and message_flow).
    2. Check for Direct Response: It inspects orchestrator_message.attribute. If direct_response is set to True, it returns the orchestrator_message.message immediately without LLM generation.
    3. Determine Prompt Strategy:
      • If message_flow contains existing text, it uses a message_flow_generator_prompt to build upon the existing flow.
      • If no flow exists, it uses a standard message_generator_prompt to generate a response from scratch.
    4. LLM Invocation: The prompt is chunked based on the model's context limits, passed through an LLM chain (self.llm | StrOutputParser()), and the resulting answer is saved to state["response"] while clearing state["message_flow"].
    def generator(self, state: MessageState) -> MessageState:
        # get the input message
        user_message = state['user_message']
        orchestrator_message = state['orchestrator_message']
        message_flow = state.get('response', "") + "\n" + state.get("message_flow", "")
    
        # get the orchestrator message content
        orch_msg_content = orchestrator_message.message
        orch_msg_attr = orchestrator_message.attribute
        direct_response = orch_msg_attr.get('direct_response', False)
    
        if direct_response:
            return orch_msg_content
        
        if message_flow and message_flow != "\n":
            prompt = PromptTemplate.from_template(message_flow_generator_prompt)
            input_prompt = prompt.invoke({
                "sys_instruct": state["sys_instruct"], 
                "message": orch_msg_content, 
                "formatted_chat": user_message.history, 
                "initial_response": message_flow
            })
        else:
            prompt = PromptTemplate.from_template(message_generator_prompt)
            input_prompt = prompt.invoke({
                "sys_instruct": state["sys_instruct"], 
                "message": orch_msg_content, 
                "formatted_chat": user_message.history
            })
    
        logger.info(f"Prompt: {input_prompt.text}")
        chunked_prompt = chunk_string(input_prompt.text, tokenizer=MODEL["tokenizer"], max_length=MODEL["context"])
        final_chain = self.llm | StrOutputParser()
        answer = final_chain.invoke(chunked_prompt)
    
        state["message_flow"] = ""
        state["response"] = answer
        return state