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 Gen AI Builder 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 BaseChunkEvent
s.
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)
--8<-- "docs/griptape-framework/misc/logs/events_4_filtered.txt"
Counting Tokens
To count tokens, you can use Event Listeners and the TokenCounter util:
--8<-- "docs/griptape-framework/misc/src/events_5.py"
--8<-- "docs/griptape-framework/misc/logs/events_5.txt"
Inspecting Payloads
You can use the StartPromptEvent to inspect the Prompt Stack and final prompt string before it is sent to the LLM.
--8<-- "docs/griptape-framework/misc/src/events_6.py"
--8<-- "docs/griptape-framework/misc/logs/events_6.txt"
... 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
.
--8<-- "docs/griptape-framework/misc/src/events_no_publish.py"
--8<-- "docs/griptape-framework/misc/logs/events_no_publish.txt"
← Prev
Eval Engine
↑ Up
Gen AI Builder: A Python Framework for Building Generative AI Applications
Next →
Tokenizers
Could this page be better? Report a problem or suggest an addition!