Complete Griptape Tutorial: Python Framework for Building AI Agents and Pipelines

# Tutorial Lengkap Griptape: Framework Python untuk Membangun AI Agent dan Pipeline Griptape adalah framework open-source Python yang dirancang khusus untuk membangun aplikasi AI yang terstruktur, am...

By Ruby Abdullah · · tutorial
GriptapeAI AgentsPythonLLM FrameworkRAG

Complete Griptape Tutorial: Python Framework for Building AI Agents and Pipelines

Griptape is an open-source Python framework designed specifically for building structured, secure, and production-ready AI applications. Unlike other agent frameworks, Griptape emphasizes predictability and control through a structure-based architecture that separates logic, tools, memory, and conversation flow. In this tutorial, we will learn how to use Griptape from installation to building complex AI agents and pipelines.

Why Griptape?

There are many AI agent frameworks available today, but Griptape has several advantages that make it stand out:

  • Off-Prompt Processing: Griptape allows processing large data outside the LLM context window, reducing token costs and improving accuracy.
  • Structured Pipeline: Supports creating sequential and parallel pipelines with clear dependency management.
  • Built-in Tools: Provides various built-in tools for file operations, web scraping, database queries, and more.
  • Memory Management: A flexible memory system with support for conversation memory, task memory, and meta memory.
  • Enterprise-Ready: Designed with security and scalability in mind for production deployments.
  • Installation

    Prerequisites

    Make sure you have Python 3.9 or later installed on your system.

    python --version
    

    Python 3.11.x or later recommended

    Basic Installation

    Installing Griptape is straightforward using pip:

    pip install griptape
    

    Installation with Additional Features

    To install Griptape with additional drivers and tools:

    # With all drivers
    

    pip install "griptape[all]"

    With specific drivers

    pip install "griptape[drivers-prompt-openai]"

    pip install "griptape[drivers-prompt-anthropic]"

    pip install "griptape[drivers-embedding-openai]"

    pip install "griptape[drivers-vector-pinecone]"

    API Key Configuration

    Griptape supports various LLM providers. Configure API keys through environment variables:

    # For OpenAI (default)
    

    export OPENAIAPIKEY="sk-your-api-key-here"

    For Anthropic Claude

    export ANTHROPICAPIKEY="sk-ant-your-api-key-here"

    For AWS Bedrock

    export AWSACCESSKEYID="your-access-key"

    export AWSSECRETACCESSKEY="your-secret-key"

    export AWSDEFAULTREGION="us-east-1"

    Basic Usage

    Simple Agent

    Let's start by creating a simple agent that can answer questions:

    from griptape.structures import Agent
    

    from griptape.rules import Rule

    agent = Agent(

    rules=[

    Rule("You are a helpful and friendly AI assistant"),

    Rule("Provide concise but comprehensive answers"),

    ]

    )

    agent.run("What is machine learning?")

    The agent's output will contain a structured response with metadata about token usage and processing time.

    Agent with Tools

    One of Griptape's key strengths is its tool system. Here's an example of an agent with calculation and web scraping capabilities:

    from griptape.structures import Agent
    

    from griptape.tools import Calculator, WebScraper, FileManager

    from griptape.rules import Rule

    agent = Agent(

    tools=[

    Calculator(),

    WebScraper(),

    FileManager(),

    ],

    rules=[

    Rule("Use available tools to answer questions accurately"),

    Rule("Always verify calculations using the Calculator tool"),

    ]

    )

    agent.run("What is the result of 1547 * 893 + 2341?")

    Custom Tool

    You can also create custom tools tailored to your needs:

    from griptape.tools import BaseTool
    

    from griptape.artifacts import TextArtifact

    from griptape.utils.decorators import activity

    from schema import Schema, Literal, Optional

    class WeatherTool(BaseTool):

    @activity(

    config={

    "description": "Get weather information for a specific city",

    "schema": Schema({

    Literal("city"): str,

    Optional(Literal("unit")): str,

    }),

    }

    )

    def getweather(self, params: dict) -> TextArtifact:

    city = params["values"]["city"]

    unit = params["values"].get("unit", "celsius")

    # Implement weather API call here

    return TextArtifact(f"Weather in {city}: 28 degrees {unit}, sunny")

    agent = Agent(

    tools=[WeatherTool()]

    )

    agent.run("What's the weather like in Jakarta today?")

    Advanced Features

    Sequential Pipeline

    Pipelines allow you to run a series of tasks sequentially, where the output of one task becomes the input for the next:

    from griptape.structures import Pipeline
    

    from griptape.tasks import PromptTask, ToolkitTask

    from griptape.tools import WebScraper, FileManager

    pipeline = Pipeline()

    pipeline.addtasks(

    PromptTask(

    "Create an article outline about {{ args[0] }}",

    id="outlinetask"

    ),

    PromptTask(

    "Based on the following outline, write a complete article:\n"

    "{{ parentoutput }}",

    id="writingtask"

    ),

    PromptTask(

    "Review and improve the following article for quality and accuracy:\n"

    "{{ parentoutput }}",

    id="reviewtask"

    ),

    )

    pipeline.run("AI Applications in Manufacturing Industry")

    Workflow with Dependency Graph

    For more complex tasks with non-linear dependencies, use Workflow:

    from griptape.structures import Workflow
    

    from griptape.tasks import PromptTask

    workflow = Workflow()

    researchtask = PromptTask(

    "Research {{ args[0] }} and create a summary",

    id="research"

    )

    analysistask = PromptTask(

    "Analyze the data from the following research:\n{{ parentoutput }}",

    id="analysis",

    parentids=["research"]

    )

    visualizationtask = PromptTask(

    "Create visualization recommendations for the data:\n{{ parentoutput }}",

    id="visualization",

    parentids=["research"]

    )

    reporttask = PromptTask(

    "Combine the analysis and visualization recommendations into a report:\n"

    "Analysis: {{ parentsoutputtext['analysis'] }}\n"

    "Visualization: {{ parentsoutputtext['visualization'] }}",

    id="report",

    parentids=["analysis", "visualization"]

    )

    workflow.addtasks(researchtask, analysistask, visualizationtask, reporttask)

    workflow.run("AI Adoption Trends in Southeast Asia 2026")

    In the example above, analysistask and visualizationtask run in parallel after researchtask completes, then their results are combined in reporttask.

    Memory Management

    Griptape provides several types of memory for managing conversation context:

    from griptape.structures import Agent
    

    from griptape.memory.structure import ConversationMemory

    from griptape.drivers import LocalConversationMemoryDriver

    agent = Agent(

    conversationmemory=ConversationMemory(

    driver=LocalConversationMemoryDriver(

    filepath="memory.json"

    )

    )

    )

    First conversation

    agent.run("My name is Alice, I'm a data scientist")

    Agent will remember previous context

    agent.run("What is my profession?")

    Task Memory (Off-Prompt)

    Task Memory is a unique Griptape feature that allows large data to be processed outside the LLM context window:

    from griptape.structures import Agent
    

    from griptape.tools import WebScraper, TaskMemoryClient

    agent = Agent(

    tools=[

    WebScraper(offprompt=True),

    TaskMemoryClient(offprompt=False),

    ]

    )

    WebScraper will store results in Task Memory

    without sending them directly to the LLM

    agent.run("Scrape https://example.com and create a summary")

    Using Various LLM Providers

    Griptape supports various LLM providers through its driver system:

    from griptape.structures import Agent
    

    from griptape.drivers import (

    AnthropicPromptDriver,

    OpenAiChatPromptDriver,

    AmazonBedrockPromptDriver,

    )

    Using Claude

    agentclaude = Agent(

    promptdriver=AnthropicPromptDriver(

    model="claude-sonnet-4-20250514",

    maxtokens=4096,

    )

    )

    Using GPT-4

    agentgpt = Agent(

    promptdriver=OpenAiChatPromptDriver(

    model="gpt-4o",

    maxtokens=4096,

    )

    )

    Using AWS Bedrock

    agentbedrock = Agent(

    promptdriver=AmazonBedrockPromptDriver(

    model="anthropic.claude-3-sonnet-20240229-v1:0",

    )

    )

    RAG (Retrieval-Augmented Generation)

    Griptape provides robust RAG support through its RagEngine:

    from griptape.structures import Agent
    

    from griptape.tools import RagTool

    from griptape.engines.rag import RagEngine

    from griptape.engines.rag.modules import (

    VectorStoreRetrievalRagModule,

    PromptResponseRagModule,

    )

    from griptape.engines.rag.stages import (

    RetrievalRagStage,

    ResponseRagStage,

    )

    from griptape.drivers import (

    LocalVectorStoreDriver,

    OpenAiEmbeddingDriver,

    )

    vectorstore = LocalVectorStoreDriver(

    embeddingdriver=OpenAiEmbeddingDriver()

    )

    ragengine = RagEngine(

    retrievalstage=RetrievalRagStage(

    retrievalmodules=[

    VectorStoreRetrievalRagModule(

    vectorstoredriver=vectorstore,

    queryparams={"topn": 5}

    )

    ]

    ),

    responsestage=ResponseRagStage(

    responsemodules=[

    PromptResponseRagModule()

    ]

    )

    )

    agent = Agent(

    tools=[

    RagTool(

    description="Search information from knowledge base",

    ragengine=ragengine,

    )

    ]

    )

    Event Listeners

    Griptape supports an event system for monitoring and logging:

    from griptape.structures import Agent
    

    from griptape.events import (

    BaseEvent,

    StartTaskEvent,

    FinishTaskEvent,

    StartPromptEvent,

    FinishPromptEvent,

    EventListener,

    )

    def onevent(event: BaseEvent):

    if isinstance(event, StartTaskEvent):

    print(f"Task started: {event.taskid}")

    elif isinstance(event, FinishTaskEvent):

    print(f"Task finished: {event.taskid}")

    elif isinstance(event, FinishPromptEvent):

    print(f"Input tokens: {event.inputtokencount}")

    print(f"Output tokens: {event.outputtokencount}")

    agent = Agent(

    eventlisteners=[

    EventListener(onevent)

    ]

    )

    agent.run("Explain the concept of neural networks")

    Rulesets for Behavior Control

    Rulesets allow you to define structured behavioral rules:

    from griptape.structures import Agent
    

    from griptape.rules import Rule, Ruleset

    customerservicerules = Ruleset(

    name="Customer Service",

    rules=[

    Rule("Always greet customers warmly"),

    Rule("Respond in the same language as the question"),

    Rule("If you don't know the answer, say so honestly"),

    Rule("Offer to connect with the support team if needed"),

    Rule("Never share internal company information"),

    ]

    )

    technicalrules = Ruleset(

    name="Technical",

    rules=[

    Rule("Provide code examples when relevant"),

    Rule("Explain steps in a progressive manner"),

    Rule("Mention the library versions being used"),

    ]

    )

    agent = Agent(

    rulesets=[customerservicerules, technicalrules]

    )

    agent.run("How do I integrate a payment gateway API?")

    Best Practices

    1. Use Off-Prompt for Large Data

    Always use offprompt=True for tools that return large amounts of data. This saves tokens and prevents context window overflow:

    # Good - large data processed outside the prompt
    

    webscraper = WebScraper(offprompt=True)

    Less optimal - large data sent directly to LLM

    webscraper = WebScraper(offprompt=False)

    2. Structure Pipelines Clearly

    Separate tasks into small, focused units that handle one responsibility:

    # Good - separate and focused tasks
    

    pipeline.addtasks(

    PromptTask("Extract data from: {{ args[0] }}", id="extract"),

    PromptTask("Transform data: {{ parentoutput }}", id="transform"),

    PromptTask("Generate report: {{ parentoutput }}", id="report"),

    )

    Less optimal - one large task

    pipeline.addtask(

    PromptTask("Extract, transform, and create a report from: {{ args[0] }}")

    )

    3. Implement Error Handling

    Griptape provides error handling mechanisms you can leverage:

    from griptape.structures import Agent
    

    from griptape.events import EventListener, FinishStructureRunEvent

    def handlecompletion(event: FinishStructureRunEvent):

    if event.structurerun.output:

    print(f"Success: {event.structurerun.output.value[:100]}")

    else:

    print("Task completed without output")

    agent = Agent(

    eventlisteners=[

    EventListener(handlecompletion, eventtypes=[FinishStructureRunEvent])

    ]

    )

    4. Manage API Keys Securely

    Never hardcode API keys in your code. Use environment variables or a secret manager:

    import os
    

    from griptape.structures import Agent

    from griptape.drivers import OpenAiChatPromptDriver

    Good - using environment variables

    agent = Agent(

    promptdriver=OpenAiChatPromptDriver(

    model="gpt-4o",

    apikey=os.environ.get("OPENAIAPIKEY"),

    )

    )

    5. Use Conversation Memory for Chatbots

    For chatbot applications, always use ConversationMemory to maintain conversation context:

    from griptape.structures import Agent
    

    from griptape.memory.structure import ConversationMemory

    agent = Agent(

    conversationmemory=ConversationMemory()

    )

    Conversation loop

    while True:

    userinput = input("You: ")

    if userinput.lower() == "quit":

    break

    response = agent.run(userinput)

    print(f"Agent: {response.outputtask.output.value}")

    6. Optimize with Chunking for Large Documents

    When working with large documents, use chunking to process data efficiently:

    from griptape.chunkers import TextChunker
    

    from griptape.drivers import OpenAiEmbeddingDriver

    chunker = TextChunker(

    maxtokens=500,

    )

    chunks = chunker.chunk("Very long document text here...")

    Process each chunk

    for chunk in chunks:

    # Embed or process the chunk

    pass

    Example Project: AI Research Assistant

    Here's a complete example of building an AI Research Assistant using Griptape:

    from griptape.structures import Agent
    

    from griptape.tools import (

    WebScraper,

    Calculator,

    FileManager,

    TaskMemoryClient,

    )

    from griptape.rules import Rule, Ruleset

    from griptape.memory.structure import ConversationMemory

    from griptape.drivers import (

    AnthropicPromptDriver,

    LocalConversationMemoryDriver,

    )

    researchassistant = Agent(

    promptdriver=AnthropicPromptDriver(

    model="claude-sonnet-4-20250514",

    maxtokens=4096,

    ),

    tools=[

    WebScraper(offprompt=True),

    Calculator(),

    FileManager(),

    TaskMemoryClient(offprompt=False),

    ],

    rulesets=[

    Ruleset(

    name="Research Assistant",

    rules=[

    Rule("You are a thorough and accurate research assistant"),

    Rule("Always cite information sources"),

    Rule("Use WebScraper to get the latest data"),

    Rule("Save research results to files using FileManager"),

    Rule("Provide critical analysis, not just summaries"),

    ]

    )

    ],

    conversationmemory=ConversationMemory(

    driver=LocalConversationMemoryDriver(

    filepath="researchmemory.json"

    )

    ),

    )

    Start research session

    researchassistant.run(

    "Research the latest developments in quantum computing "

    "and its impact on cryptographic security"

    )

    Follow-up question (context preserved)

    research_assistant.run(

    "Based on the previous research, what mitigation steps "

    "can companies take to address quantum threats?"

    )

    Conclusion

    Griptape is a mature and powerful framework for building AI agent-based applications. With features like off-prompt processing, structured pipelines, workflows with dependency graphs, and flexible memory management, Griptape is well-suited for building complex, production-ready AI applications.

    Key takeaways to remember:

    • Use off-prompt processing for token efficiency with large data
    • Leverage Pipeline for sequential tasks and Workflow for complex dependencies
    • Implement proper memory management based on your application needs
    • Use event listeners for monitoring and debugging
    • Always manage API keys securely through environment variables
    • Choose the appropriate LLM provider through Griptape's flexible driver system

    With this solid foundation, you can start building reliable and scalable AI agents for various business and technical needs. Griptape continues to evolve with an active community, making it a solid choice for modern AI projects.

    Related Articles

    LangChain Tutorial: The Most Popular Framework for Building LLM Applications

    Tutorial LangChain: Framework Paling Populer untuk Membangun Aplikasi LLM LangChain adalah framework open-source yang di...

    Complete AgentOps Tutorial: Monitoring and Observability for AI Agents

    Tutorial Lengkap AgentOps: Monitoring dan Observability untuk AI Agent Membangun AI agent yang berjalan di production ta...

    LlamaParse Tutorial: Parsing Complex Documents for RAG Pipelines

    Tutorial LlamaParse: Parsing Dokumen Kompleks untuk RAG Pipeline Membangun aplikasi Retrieval-Augmented Generation (RAG)...

    Semantic Router Tutorial: Smart Routing for LLM Applications

    Tutorial Semantic Router: Routing Cerdas untuk Aplikasi LLM Semantic Router adalah library Python yang memungkinkan Anda...