Threads in Marvin provide a powerful mechanism for managing conversation history and context across your AI workflows. Unlike ControlFlow’s flows, threads in Marvin are focused on conversation management and persistence rather than workflow orchestration.
Threads can be passed to tasks to maintain conversation context:
Copy
Ask AI
import marvinthread = marvin.Thread()task = marvin.Task( instructions="Write a poem about AI", result_type=str)# Run the task with the threadresult = task.run(thread=thread)
You can retrieve messages from a thread with various filters:
Copy
Ask AI
# Get all messagesmessages = thread.get_messages()# Get messages with filtersmessages = thread.get_messages( include_system_messages=False, # Exclude system messages before=datetime.now(), # Messages before a timestamp after=some_timestamp, # Messages after a timestamp limit=10 # Limit number of messages)
Marvin provides context management for threads, making it easy to set the current thread:
Copy
Ask AI
with thread: # This thread is now the current thread task1.run() # Uses the thread automatically task2.run() # Same thread is used# Thread context is restored after the block
Threads are automatically persisted to a database when configured:
Copy
Ask AI
# Messages and LLM calls are automatically savedthread.add_user_message("Save this message")# Later, create a thread with the same ID to access historysame_thread = marvin.Thread(id=thread.id)messages = same_thread.get_messages() # Includes saved messages
While threads provide short-term conversation context within a session, Memory offers long-term persistence across multiple sessions. The two can work together:
Copy
Ask AI
import marvinfrom marvin import Thread, Memory, Agent# Create a memory for storing user preferencesuser_preferences = Memory(key="user_preferences")# Create an agent with this memoryassistant = Agent( name="Personal Assistant", instructions="You are a helpful assistant", memories=[user_preferences])# Use the agent in a threadwith Thread() as thread: # The agent can access both thread context (recent conversation) # and memory (long-term stored information) assistant.run("Remember that I prefer dark mode") assistant.run("What are my UI preferences?") # Will recall from memory
Threads maintain the flow of conversation, while Memory stores specific information that should persist across different threads and sessions. See the Memory documentation for more details on working with persistent memory.