Skip to content

Events

Overview

You can configure the global EventBus with EventListeners to listen for various framework events. See Event Listener Drivers for examples on forwarding events to external services.

Specific Event Types

You can listen to specific event types:

from griptape.events import (
    BaseEvent,
    EventBus,
    EventListener,
    FinishActionsSubtaskEvent,
    FinishPromptEvent,
    FinishTaskEvent,
    StartActionsSubtaskEvent,
    StartPromptEvent,
    StartTaskEvent,
)
from griptape.structures import Agent


def on_event(event: BaseEvent) -> None:
    print(event.__class__)


EventBus.add_event_listeners(
    [
        EventListener(
            on_event,
            event_types=[
                StartTaskEvent,
                FinishTaskEvent,
                StartActionsSubtaskEvent,
                FinishActionsSubtaskEvent,
                StartPromptEvent,
                FinishPromptEvent,
            ],
        )
    ]
)

agent = Agent()

agent.run("tell me about griptape")
<class 'griptape.events.start_task_event.StartTaskEvent'>
[02/27/25 20:29:18] INFO     PromptTask b1dc556de12242ab911b8cc7a8e448f0        
                             Input: tell me about griptape                      
<class 'griptape.events.start_prompt_event.StartPromptEvent'>
<class 'griptape.events.finish_prompt_event.FinishPromptEvent'>
<class 'griptape.events.finish_task_event.FinishTaskEvent'>
[02/27/25 20:29:22] INFO     PromptTask b1dc556de12242ab911b8cc7a8e448f0        
                             Output: Grip tape is a sandpaper-like sheet that is
                             applied to the top surface of a skateboard deck to 
                             provide traction between the rider's shoes and the 
                             board. It is an essential component for            
                             skateboarders, as it helps them maintain control   
                             and stability while performing tricks and          
                             maneuvers. Grip tape is typically made from a      
                             durable, gritty material with an adhesive backing  
                             that allows it to stick securely to the deck.      

                             Here are some key points about grip tape:          

                             1. **Material**: Most grip tape is made from       
                             silicon carbide or aluminum oxide, which provides  
                             the rough texture needed for grip.                 

                             2. **Application**: Applying grip tape involves    
                             peeling off the backing and carefully placing it on
                             the skateboard deck, ensuring there are no air     
                             bubbles. Excess tape is usually trimmed off with a 
                             sharp blade.                                       

                             3. **Customization**: Grip tape comes in various   
                             colors, patterns, and designs, allowing            
                             skateboarders to personalize their boards. Some    
                             brands offer die-cut designs or printed graphics.  

                             4. **Maintenance**: Over time, grip tape can wear  
                             down, especially in areas of high use. It may need 
                             to be replaced periodically to maintain optimal    
                             grip.                                              

                             5. **Other Uses**: While primarily used for        
                             skateboards, grip tape can also be applied to other
                             surfaces where additional traction is needed, such 
                             as scooter decks or tool handles.                  

                             Overall, grip tape is a crucial element for        
                             skateboard performance, providing the necessary    
                             friction for safe and effective riding.            

All Event Types

Or listen to all events:

from griptape.events import BaseEvent, EventBus, EventListener
from griptape.structures import Agent


def handler1(event: BaseEvent) -> None:
    print("Handler 1", event.__class__)


def handler2(event: BaseEvent) -> None:
    print("Handler 2", event.__class__)


EventBus.add_event_listeners(
    [
        EventListener(handler1),
        EventListener(handler2),
    ]
)

agent = Agent()

agent.run("tell me about griptape")
Handler 1 <class 'griptape.events.start_structure_run_event.StartStructureRunEvent'>
Handler 2 <class 'griptape.events.start_structure_run_event.StartStructureRunEvent'>
Handler 1 <class 'griptape.events.start_task_event.StartTaskEvent'>
Handler 2 <class 'griptape.events.start_task_event.StartTaskEvent'>
[02/27/25 20:28:19] INFO     PromptTask 167acee86fc948cb953404e8ec537bb5        
                             Input: tell me about griptape                      
Handler 1 <class 'griptape.events.start_prompt_event.StartPromptEvent'>
Handler 2 <class 'griptape.events.start_prompt_event.StartPromptEvent'>
Handler 1 <class 'griptape.events.finish_prompt_event.FinishPromptEvent'>
Handler 2 <class 'griptape.events.finish_prompt_event.FinishPromptEvent'>
Handler 1 <class 'griptape.events.finish_task_event.FinishTaskEvent'>
Handler 2 <class 'griptape.events.finish_task_event.FinishTaskEvent'>
[02/27/25 20:28:22] INFO     PromptTask 167acee86fc948cb953404e8ec537bb5        
                             Output: Grip tape is a gritty, sandpaper-like      
                             material that is applied to the top surface of a   
                             skateboard or scooter deck to provide traction for 
                             the rider's feet. It is essential for performing   
                             tricks and maintaining control while riding. Here  
                             are some key points about grip tape:               

                             1. **Material**: Grip tape is typically made from  
                             silicon carbide or aluminum oxide, which gives it  
                             its rough texture. The backing is usually a strong 
                             adhesive that sticks firmly to the deck.           

                             2. **Application**: To apply grip tape, you peel   
                             off the backing and carefully place it on the deck,
                             smoothing out any air bubbles. Excess tape is      
                             trimmed off around the edges of the deck.          

                             3. **Variety**: Grip tape comes in various colors, 
                             designs, and even custom prints, allowing riders to
                             personalize their boards. Some grip tapes also     
                             feature perforations to prevent air bubbles during 
                             application.                                       

                             4. **Durability**: Over time, grip tape can wear   
                             down, especially in areas of high friction. It may 
                             need to be replaced periodically to maintain       
                             optimal grip.                                      

                             5. **Functionality**: Besides providing grip, the  
                             rough surface of the tape helps riders perform     
                             tricks by allowing them to "stick" to the board    
                             better during maneuvers like ollies and flips.     

                             6. **Maintenance**: Keeping grip tape clean can    
                             extend its life. Dirt and debris can be removed    
                             using a brush or grip tape cleaner.                

                             Grip tape is a crucial component for skateboarders 
                             and scooter riders, enhancing both performance and 
                             safety by ensuring a secure footing.               
Handler 1 <class 'griptape.events.finish_structure_run_event.FinishStructureRunEvent'>
Handler 2 <class 'griptape.events.finish_structure_run_event.FinishStructureRunEvent'>

Stream Iterator

You can use Structure.run_stream() for streaming Events from the Structure in the form of an iterator.

Tip

Set stream=True on your Prompt Driver in order to receive completion chunk events.

from griptape.events import BaseEvent
from griptape.structures import Agent

agent = Agent()

for event in agent.run_stream("Hi!", event_types=[BaseEvent]):  # All Events
    print(type(event))
[02/27/25 20:29:24] INFO     PromptTask cc5206dcacd74046a2063b8fd8f61914        
                             Input: Hi!                                         
<class 'griptape.events.start_structure_run_event.StartStructureRunEvent'>
<class 'griptape.events.start_task_event.StartTaskEvent'>
<class 'griptape.events.start_prompt_event.StartPromptEvent'>
[02/27/25 20:29:28] INFO     PromptTask cc5206dcacd74046a2063b8fd8f61914        
                             Output: Hello! How can I assist you today?         
<class 'griptape.events.finish_prompt_event.FinishPromptEvent'>
<class 'griptape.events.finish_task_event.FinishTaskEvent'>

Context Managers

You can also use EventListeners as a Python Context Manager. The EventListener will automatically be added and removed from the EventBus when entering and exiting the context.

from griptape.events import EventBus, EventListener, FinishStructureRunEvent, StartPromptEvent
from griptape.structures import Agent

EventBus.add_event_listeners(
    [EventListener(lambda e: print(f"Out of context: {e.type}"), event_types=[StartPromptEvent])]
)

agent = Agent(input="Hello!")

with EventListener(lambda e: print(f"In context: {e.type}"), event_types=[FinishStructureRunEvent]):
    agent.run()

agent.run()
[02/27/25 20:28:40] INFO     PromptTask 0f1dcd9263ef4c6caade936c2a31c041        
                             Input: Hello!                                      
Out of context: StartPromptEvent
[02/27/25 20:28:41] INFO     PromptTask 0f1dcd9263ef4c6caade936c2a31c041        
                             Output: Hello! How can I assist you today?         
In context: FinishStructureRunEvent
                    INFO     PromptTask 0f1dcd9263ef4c6caade936c2a31c041        
                             Input: Hello!                                      
Out of context: StartPromptEvent
[02/27/25 20:28:42] INFO     PromptTask 0f1dcd9263ef4c6caade936c2a31c041        
                             Output: Hi there! How can I help you today?        

Streaming

You can use the BaseChunkEvent to stream the completion results from Prompt Drivers.

from griptape.drivers.prompt.openai import OpenAiChatPromptDriver
from griptape.events import BaseChunkEvent, EventBus, EventListener
from griptape.structures import Pipeline
from griptape.tasks import PromptTask
from griptape.tools import PromptSummaryTool, WebScraperTool

EventBus.add_event_listeners(
    [
        EventListener(
            lambda e: print(str(e), end="", flush=True),
            event_types=[BaseChunkEvent],
        ),
    ]
)

pipeline = Pipeline()
pipeline.add_tasks(
    PromptTask(
        "Based on https://griptape.ai, tell me what griptape is.",
        prompt_driver=OpenAiChatPromptDriver(model="gpt-4.1", stream=True),
        tools=[WebScraperTool(off_prompt=True), PromptSummaryTool(off_prompt=False)],
    )
)

pipeline.run()
[02/27/25 20:28:26] INFO     PromptTask b15b3f6e25464da0a43e460c82a49861        
                             Input: Based on https://griptape.ai, tell me what  
                             griptape is.                                       
WebScraperTool.get_content (call_pcIDNi1AXKesObKAJs9AK1kc){"values":{"url":"https://griptape.ai"}}[02/27/25 20:28:28] INFO     Subtask 4f549b191fe147d2a0d05b626c09c43d           
                             Actions: [                                         
                               {                                                
                                 "tag": "call_pcIDNi1AXKesObKAJs9AK1kc",        
                                 "name": "WebScraperTool",                      
                                 "path": "get_content",                         
                                 "input": {                                     
                                   "values": {                                  
                                     "url": "https://griptape.ai"               
                                   }                                            
                                 }                                              
                               }                                                
                             ]                                                  
[02/27/25 20:28:32] INFO     Subtask 4f549b191fe147d2a0d05b626c09c43d           
                             Response: Output of "WebScraperTool.get_content"   
                             was stored in memory with memory_name "TaskMemory" 
                             and artifact_namespace                             
                             "a11e816b9ade4c10b94ed4986ec1982b"                 
PromptSummaryTool.summarize (call_uLwOt80tnwydh0N433pEKxgk){"values":{"summary":{"memory_name":"TaskMemory","artifact_namespace":"a11e816b9ade4c10b94ed4986ec1982b"}}}[02/27/25 20:28:33] INFO     Subtask 57a2be8d678e429d8546f43aff2d2e50           
                             Actions: [                                         
                               {                                                
                                 "tag": "call_uLwOt80tnwydh0N433pEKxgk",        
                                 "name": "PromptSummaryTool",                   
                                 "path": "summarize",                           
                                 "input": {                                     
                                   "values": {                                  
                                     "summary": {                               
                                       "memory_name": "TaskMemory",             
                                       "artifact_namespace":                    
                             "a11e816b9ade4c10b94ed4986ec1982b"                 
                                     }                                          
                                   }                                            
                                 }                                              
                               }                                                
                             ]                                                  
[02/27/25 20:28:37] INFO     Subtask 57a2be8d678e429d8546f43aff2d2e50           
                             Response: Griptape provides a comprehensive        
                             solution for developers to build, deploy, and scale
                             AI-powered applications. It offers an open-source  
                             AI framework and a cloud execution runtime,        
                             enabling developers to create business logic using 
                             Python without relying on prompt engineering.      
                             Griptape supports the deployment of ETL, RAG, and  
                             other structures with simple API abstractions,     
                             eliminating the need for infrastructure management.
                             It also provides tools for monitoring performance  
                             and enforcing policies. The Griptape AI Framework  
                             allows for the creation of Gen AI Agents,          
                             pipelines, and workflows, while the Griptape AI    
                             Cloud handles infrastructure, offering automated   
                             data preparation and retrieval services.           
Griptape provides a comprehensive solution for developers to build, deploy, and scale AI-powered applications. It offers an open-source AI framework and a cloud execution runtime, enabling developers to create business logic using Python without relying on prompt engineering. Griptape supports the deployment of ETL, RAG, and other structures with simple API abstractions, eliminating the need for infrastructure management. It also provides tools for monitoring performance and enforcing policies. The Griptape AI Framework allows for the creation of Gen AI Agents, pipelines, and workflows, while the Griptape AI Cloud handles infrastructure, offering automated data preparation and retrieval services.[02/27/25 20:28:39] INFO     PromptTask b15b3f6e25464da0a43e460c82a49861        
                             Output: Griptape provides a comprehensive solution 
                             for developers to build, deploy, and scale         
                             AI-powered applications. It offers an open-source  
                             AI framework and a cloud execution runtime,        
                             enabling developers to create business logic using 
                             Python without relying on prompt engineering.      
                             Griptape supports the deployment of ETL, RAG, and  
                             other structures with simple API abstractions,     
                             eliminating the need for infrastructure management.
                             It also provides tools for monitoring performance  
                             and enforcing policies. The Griptape AI Framework  
                             allows for the creation of Gen AI Agents,          
                             pipelines, and workflows, while the Griptape AI    
                             Cloud handles infrastructure, offering automated   
                             data preparation and retrieval services.           

You can also use the TextChunkEvent and ActionChunkEvent to further differentiate the different types of chunks for more customized output.

from griptape.drivers.prompt.openai import OpenAiChatPromptDriver
from griptape.events import ActionChunkEvent, EventBus, EventListener, TextChunkEvent
from griptape.structures import Pipeline
from griptape.tasks import PromptTask
from griptape.tools import PromptSummaryTool, WebScraperTool

EventBus.add_event_listeners(
    [
        EventListener(
            lambda e: print(str(e), end="", flush=True),
            event_types=[TextChunkEvent],
        ),
        EventListener(
            lambda e: print(str(e), end="", flush=True),
            event_types=[ActionChunkEvent],
        ),
    ]
)

pipeline = Pipeline()
pipeline.add_tasks(
    PromptTask(
        "Based on https://griptape.ai, tell me what griptape is.",
        prompt_driver=OpenAiChatPromptDriver(model="gpt-4.1", stream=True),
        tools=[WebScraperTool(off_prompt=True), PromptSummaryTool(off_prompt=False)],
    )
)

pipeline.run()
[02/27/25 20:28:28] INFO     PromptTask f28262aaab014f548c8d55f0b0b8fc37        
                             Input: Based on https://griptape.ai, tell me what  
                             griptape is.                                       
WebScraperTool.get_content (call_dpLUPLRdEVuhBbBrTQCtjGDX){"values":{"url":"https://griptape.ai"}}[02/27/25 20:28:30] INFO     Subtask fcd088bbcc494d1584a5d5d5004b1e04           
                             Actions: [                                         
                               {                                                
                                 "tag": "call_dpLUPLRdEVuhBbBrTQCtjGDX",        
                                 "name": "WebScraperTool",                      
                                 "path": "get_content",                         
                                 "input": {                                     
                                   "values": {                                  
                                     "url": "https://griptape.ai"               
                                   }                                            
                                 }                                              
                               }                                                
                             ]                                                  
[02/27/25 20:28:31] INFO     Subtask fcd088bbcc494d1584a5d5d5004b1e04           
                             Response: Output of "WebScraperTool.get_content"   
                             was stored in memory with memory_name "TaskMemory" 
                             and artifact_namespace                             
                             "bd6dee4ddcb640c1bcb50551d57502a7"                 
PromptSummaryTool.summarize (call_TGCW6j9ORjJm42ae1mIG4GBb){"values":{"summary":{"memory_name":"TaskMemory","artifact_namespace":"bd6dee4ddcb640c1bcb50551d57502a7"}}}[02/27/25 20:28:32] INFO     Subtask fca257f69cbf466e8aa0bcff9e25d79b           
                             Actions: [                                         
                               {                                                
                                 "tag": "call_TGCW6j9ORjJm42ae1mIG4GBb",        
                                 "name": "PromptSummaryTool",                   
                                 "path": "summarize",                           
                                 "input": {                                     
                                   "values": {                                  
                                     "summary": {                               
                                       "memory_name": "TaskMemory",             
                                       "artifact_namespace":                    
                             "bd6dee4ddcb640c1bcb50551d57502a7"                 
                                     }                                          
                                   }                                            
                                 }                                              
                               }                                                
                             ]                                                  
[02/27/25 20:28:36] INFO     Subtask fca257f69cbf466e8aa0bcff9e25d79b           
                             Response: Griptape offers a comprehensive solution 
                             for developers to build, deploy, and scale         
                             AI-powered applications. It provides an open-source
                             AI framework and a cloud execution runtime,        
                             enabling developers to create business logic using 
                             Python without relying on prompt engineering.      
                             Griptape's platform supports the development of ETL
                             pipelines, retrieval patterns, and AI agents, while
                             offering secure, efficient, and cost-effective     
                             deployment. The Griptape AI Cloud handles          
                             infrastructure management, providing automated data
                             preparation, retrieval as a service, and runtime   
                             for AI agents and workflows. This allows developers
                             to focus on building and scaling applications      
                             without the complexities of infrastructure         
                             management.                                        
Griptape is a comprehensive solution designed for developers to build, deploy, and scale AI-powered applications. It offers an open-source AI framework and a cloud execution runtime, allowing developers to create business logic using Python without the need for prompt engineering. The platform supports the development of ETL pipelines, retrieval patterns, and AI agents, providing secure, efficient, and cost-effective deployment options. Griptape AI Cloud manages infrastructure, offering automated data preparation, retrieval as a service, and runtime for AI agents and workflows, enabling developers to focus on application development and scaling without dealing with infrastructure complexities.[02/27/25 20:28:38] INFO     PromptTask f28262aaab014f548c8d55f0b0b8fc37        
                             Output: Griptape is a comprehensive solution       
                             designed for developers to build, deploy, and scale
                             AI-powered applications. It offers an open-source  
                             AI framework and a cloud execution runtime,        
                             allowing developers to create business logic using 
                             Python without the need for prompt engineering. The
                             platform supports the development of ETL pipelines,
                             retrieval patterns, and AI agents, providing       
                             secure, efficient, and cost-effective deployment   
                             options. Griptape AI Cloud manages infrastructure, 
                             offering automated data preparation, retrieval as a
                             service, and runtime for AI agents and workflows,  
                             enabling developers to focus on application        
                             development and scaling without dealing with       
                             infrastructure complexities.                       

If you want Griptape to handle the chunk events for you, use the Stream utility to automatically wrap BaseChunkEvents in a Python iterator.

The Stream utility does not automatically enable streaming on the Drivers that produce BaseChunkEvents. Make sure to enable streaming on the Drivers or else Stream will yield no iterations.

import logging

from griptape.configs import Defaults
from griptape.structures import Agent
from griptape.tools import PromptSummaryTool, WebScraperTool
from griptape.utils import Stream

# Hide Griptape's usual output
logging.getLogger(Defaults.logging_config.logger_name).setLevel(logging.ERROR)

agent = Agent(
    input="Based on https://griptape.ai, tell me what griptape is.",
    tools=[
        PromptSummaryTool(off_prompt=True),
        WebScraperTool(off_prompt=False),
    ],
    stream=True,
)


for artifact in Stream(agent).run():
    print(artifact.value, end="", flush=True)
WebScraperTool.call_XNlfty9CYNnlkIcKMFo2USPw (get_content){
  "values": {
    "url": "https://griptape.ai"
  }
}
Griptape is a platform designed to help developers build, deploy, and scale end-to-end solutions, particularly those powered by large language models (LLMs). It offers tools for data preparation, retrieval, AI agents, pipelines, and workflows. Griptape provides an open-source AI framework and an execution runtime called Griptape AI Cloud.

Key features of Griptape include:

- **Build & Secure**: Developers can build business logic using Python, enhancing security, performance, and reducing costs with Off-Promptâ„¢ technology.
- **Deploy & Scale**: It allows for the deployment and running of ETL, RAG, and other structures without managing infrastructure, enabling seamless scaling.
- **Manage & Monitor**: Users can monitor performance, reliability, and spending, and enforce policies across the organization.

Griptape AI Framework offers abstractions for building AI agents, systems of agents, pipelines, workflows, and retrieval-augmented generation (RAG) implementations without needing extensive knowledge of Gen AI or prompt engineering.

Griptape AI Cloud handles infrastructure management, hosting everything from data processing pipelines to serverless application runtimes. It includes features like automated data preparation (ETL), retrieval as a service (RAG), and structure runtime (RUN) for building AI agents and workflows.

Sometimes, streaming can be too verbose. You can use Stream.event_types to only listen to specific event types. A good example is to remove the ActionChunkEvent from the stream if you don't need to see events related to Tool usage.

import logging

from griptape.configs import Defaults
from griptape.events import FinishPromptEvent, FinishStructureRunEvent, TextChunkEvent
from griptape.structures import Agent
from griptape.tools import PromptSummaryTool, WebScraperTool
from griptape.utils import Stream

# Hide Griptape's usual output
logging.getLogger(Defaults.logging_config.logger_name).setLevel(logging.ERROR)

agent = Agent(
    input="Based on https://griptape.ai, tell me what griptape is.",
    tools=[
        PromptSummaryTool(off_prompt=True),
        WebScraperTool(off_prompt=False),
    ],
    stream=True,
)

# Listen for the following event types
event_types = [TextChunkEvent, FinishPromptEvent, FinishStructureRunEvent]

for artifact in Stream(agent, event_types=event_types).run():
    print(artifact.value, end="", flush=True)

Counting Tokens

To count tokens, you can use Event Listeners and the TokenCounter util:

from griptape import utils
from griptape.events import BaseEvent, EventBus, EventListener, FinishPromptEvent
from griptape.structures import Agent

token_counter = utils.TokenCounter()


def count_tokens(e: BaseEvent) -> None:
    if isinstance(e, FinishPromptEvent) and e.output_token_count is not None:
        token_counter.add_tokens(e.output_token_count)


EventBus.add_event_listeners(
    [
        EventListener(
            count_tokens,
            event_types=[FinishPromptEvent],
        )
    ]
)


agent = Agent()

agent.run("tell me about large language models")

print(f"total tokens: {token_counter.tokens}")
[02/27/25 20:28:40] INFO     PromptTask 378a3847973c432491ae8e81c5a8655b        
                             Input: tell me about large language models         
[02/27/25 20:28:49] INFO     PromptTask 378a3847973c432491ae8e81c5a8655b        
                             Output: Large language models (LLMs) are a type of 
                             artificial intelligence (AI) designed to           
                             understand, generate, and manipulate human         
                             language. They are built using deep learning       
                             techniques, particularly neural networks, and are  
                             trained on vast amounts of text data. Here are some
                             key aspects of large language models:              

                             1. **Architecture**: Most large language models are
                             based on transformer architecture, which was       
                             introduced in the paper "Attention is All You Need"
                             by Vaswani et al. in 2017. Transformers use        
                             mechanisms like self-attention to weigh the        
                             importance of different words in a sentence,       
                             allowing the model to capture complex language     
                             patterns and dependencies.                         

                             2. **Training Data**: LLMs are trained on diverse  
                             and extensive datasets that include books,         
                             articles, websites, and other text sources. This   
                             broad exposure helps them learn the nuances of     
                             human language, including grammar, context, and    
                             even some level of reasoning.                      

                             3. **Scale**: The "large" in large language models 
                             refers to both the size of the dataset they are    
                             trained on and the number of parameters they       
                             contain. Models like OpenAI's GPT-3 have hundreds  
                             of billions of parameters, enabling them to perform
                             a wide range of language tasks with high           
                             proficiency.                                       

                             4. **Capabilities**: LLMs can perform various      
                             tasks, including text generation, translation,     
                             summarization, question answering, and sentiment   
                             analysis. They can also be fine-tuned for specific 
                             applications, such as customer service chatbots or 
                             content creation tools.                            

                             5. **Limitations**: Despite their impressive       
                             capabilities, LLMs have limitations. They can      
                             sometimes produce incorrect or nonsensical answers,
                             are sensitive to input phrasing, and may struggle  
                             with tasks requiring deep reasoning or real-world  
                             knowledge beyond their training data. Additionally,
                             they can inadvertently perpetuate biases present in
                             their training data.                               

                             6. **Ethical Considerations**: The deployment of   
                             LLMs raises ethical concerns, such as the potential
                             for misuse in generating misleading or harmful     
                             content, privacy issues related to data usage, and 
                             the environmental impact of training large models. 
                             Researchers and developers are actively working on 
                             addressing these challenges.                       

                             7. **Applications**: LLMs are used in various      
                             industries, including healthcare, finance,         
                             entertainment, and education. They assist in       
                             automating tasks, enhancing human-computer         
                             interaction, and providing insights from large     
                             datasets.                                          

                             Overall, large language models represent a         
                             significant advancement in AI, offering powerful   
                             tools for understanding and generating human       
                             language while also posing challenges that require 
                             careful consideration and management.              
total tokens: 500

Inspecting Payloads

You can use the StartPromptEvent to inspect the Prompt Stack and final prompt string before it is sent to the LLM.

from griptape.events import BaseEvent, EventBus, EventListener, StartPromptEvent
from griptape.structures import Agent


def on_event(event: BaseEvent) -> None:
    if isinstance(event, StartPromptEvent):
        print("Prompt Stack Messages:")
        for message in event.prompt_stack.messages:
            print(f"{message.role}: {message.to_text()}")


EventBus.add_event_listeners([EventListener(on_event=on_event, event_types=[StartPromptEvent])])

agent = Agent()

agent.run("Write me a poem.")
[02/27/25 20:28:25] INFO     PromptTask 69c30d65f97247f9bd4c626ab0278a62        
                             Input: Write me a poem.                            
Prompt Stack Messages:
user: Write me a poem.
[02/27/25 20:28:27] INFO     PromptTask 69c30d65f97247f9bd4c626ab0278a62        
                             Output: In the hush of dawn's first light,         
                             Whispers dance on morning's breeze,                
                             Nature's canvas, pure and bright,                  
                             Awakens with the rustling trees.                   

                             Golden rays kiss dewdrops fair,                    
                             Glistening on the meadow's face,                   
                             A symphony of colors rare,                         
                             In this tranquil, sacred space.                    

                             Birds compose their morning song,                  
                             Melodies that gently rise,                         
                             In harmony, they sing along,                       
                             Beneath the vast and endless skies.                

                             The world, anew with each sunrise,                 
                             Promises of hope and grace,                        
                             In every shadow, light defies,                     
                             And dreams take flight in open space.              

                             So let your heart embrace the morn,                
                             With courage, love, and dreams untold,             
                             For in each day, new paths are born,               
                             And stories of the soul unfold.                    
...
Prompt Stack Messages:
system:
user: Write me a poem.
Final Prompt String:


User: Write me a poem.

Assistant:
...

EventListenerDriver.on_event Return Value Behavior

The value that gets returned from the EventListener.on_event will determine what gets sent to the event_listener_driver.

EventListener.on_event is None

By default, the EventListener.on_event function is None. Any events that the EventListener is listening for will get sent to the event_listener_driver as-is.

Return BaseEvent or dict

You can return a BaseEvent or dict object from EventListener.on_event, and it will get sent to the event_listener_driver.

Return None

You can return None in the on_event function to prevent the event from getting sent to the event_listener_driver.

from __future__ import annotations

from typing import Optional

from griptape.artifacts import ErrorArtifact, InfoArtifact
from griptape.drivers.event_listener.griptape_cloud import GriptapeCloudEventListenerDriver
from griptape.events import BaseEvent, EventBus, EventListener, FinishStructureRunEvent
from griptape.structures import Agent


def handler_maybe_drop_events(event: FinishStructureRunEvent) -> Optional[BaseEvent | dict]:
    if event.structure_id == "some_structure_id":
        # Drop the event if the structure_id is "some_structure_id"
        return None
    if isinstance(event.output_task_output, InfoArtifact):
        # Print the output of the task if it is an InfoArtifact
        # and then drop the event
        print(f"Info: {event.output_task_output}")
        return None
    if isinstance(event.output_task_output, ErrorArtifact):
        # Print the output of the task if it is an ErrorArtifact
        # and then convert it to a dictionary and return it
        print(f"Error: {event.output_task_output}")
        return {
            "error": event.output_task_output.to_text(),
            "exception_message": str(event.output_task_output.exception),
        }

    return event


EventBus.add_event_listeners(
    [
        EventListener(
            handler_maybe_drop_events,
            event_types=[FinishStructureRunEvent],
            # By default, GriptapeCloudEventListenerDriver uses the api key provided
            # in the GT_CLOUD_API_KEY environment variable.
            event_listener_driver=GriptapeCloudEventListenerDriver(),
        ),
    ]
)


agent1 = Agent(id="some_structure_id")
agent1.run("Create a list of 8 questions for an interview with a science fiction author.")

agent2 = Agent(id="another_structure_id")
agent2.run("Create a list of 10 questions for an interview with a theoretical physicist.")
[02/27/25 20:28:57] INFO     PromptTask d60ef2ac8efe47718bc1a1406b198108        
                             Input: Create a list of 8 questions for an         
                             interview with a science fiction author.           
[02/27/25 20:28:59] INFO     PromptTask d60ef2ac8efe47718bc1a1406b198108        
                             Output: Certainly! Here are eight questions you    
                             might consider asking a science fiction author     
                             during an interview:                               

                             1. **Inspiration and Beginnings**: What initially  
                             drew you to the science fiction genre, and how did 
                             you get started as a writer in this field?         

                             2. **World-Building**: Can you walk us through your
                             process of world-building? How do you balance      
                             scientific plausibility with creative imagination? 

                             3. **Character Development**: How do you approach  
                             creating characters that resonate with readers in a
                             genre often dominated by complex ideas and         
                             futuristic settings?                               

                             4. **Themes and Messages**: Are there particular   
                             themes or messages you aim to convey through your  
                             work, and how do you weave them into your          
                             narratives?                                        

                             5. **Influences**: Which authors or works have had 
                             the most significant impact on your writing, and   
                             how have they influenced your style or themes?     

                             6. **Technological Predictions**: Have any of the  
                             technologies or societal changes you've imagined in
                             your books come to fruition, or do you see them on 
                             the horizon?                                       

                             7. **Challenges in Writing Sci-Fi**: What are some 
                             of the biggest challenges you face when writing    
                             science fiction, and how do you overcome them?     

                             8. **Future Projects**: Can you share any details  
                             about your upcoming projects or what readers can   
                             expect from you in the future?                     

                             These questions aim to explore the author's        
                             creative process, influences, and perspectives on  
                             the genre.                                         
                    INFO     PromptTask 8a52a8f5af444172a8900fc7dfbd8d05        
                             Input: Create a list of 10 questions for an        
                             interview with a theoretical physicist.            
[02/27/25 20:29:15] INFO     PromptTask 8a52a8f5af444172a8900fc7dfbd8d05        
                             Output: Certainly! Here are ten questions that     
                             could be used in an interview with a theoretical   
                             physicist:                                         

                             1. **Background and Inspiration:**                 
                                - What initially sparked your interest in       
                             theoretical physics, and how did you decide to     
                             pursue it as a career?                             

                             2. **Research Focus:**                             
                                - Can you describe your current research focus  
                             and what you find most exciting about it?          

                             3. **Challenges in the Field:**                    
                                - What are some of the biggest challenges you   
                             face in your research, and how do you approach     
                             overcoming them?                                   

                             4. **Interdisciplinary Connections:**              
                                - How do you see theoretical physics            
                             intersecting with other scientific disciplines, and
                             why are these connections important?               

                             5. **Theoretical vs. Experimental:**               
                                - How do you view the relationship between      
                             theoretical and experimental physics, and how do   
                             they complement each other in advancing our        
                             understanding of the universe?                     

                             6. **Impact of Technology:**                       
                                - In what ways has technology influenced        
                             theoretical physics research, and what future      
                             technological advancements do you anticipate will  
                             have a significant impact?                         

                             7. **Public Understanding:**                       
                                - How do you think theoretical physicists can   
                             better communicate complex concepts to the general 
                             public, and why is this important?                 

                             8. **Ethical Considerations:**                     
                                - Are there any ethical considerations or       
                             societal implications of your work that you think  
                             about, and how do you address them?                

                             9. **Future of Theoretical Physics:**              
                                - What do you see as the most promising or      
                             exciting areas of theoretical physics research in  
                             the next decade?                                   

                             10. **Advice for Aspiring Physicists:**            
                                 - What advice would you give to students or    
                             young scientists who are interested in pursuing a  
                             career in theoretical physics?                     

                             These questions aim to explore the physicist's     
                             personal journey, their current work, and broader  
                             perspectives on the field.