a digital person for bluesky
1#!/usr/bin/env python3
2"""Register all Void tools with a Letta agent."""
3import os
4import sys
5import logging
6from typing import List
7from letta_client import Letta
8from rich.console import Console
9from rich.table import Table
10from config_loader import get_letta_config
11
12# Import standalone functions and their schemas
13from tools.search import search_bluesky_posts, SearchArgs
14from tools.post import create_new_bluesky_post, PostArgs
15from tools.feed import get_bluesky_feed, FeedArgs
16from tools.blocks import attach_user_blocks, detach_user_blocks, user_note_append, user_note_replace, user_note_set, user_note_view, AttachUserBlocksArgs, DetachUserBlocksArgs, UserNoteAppendArgs, UserNoteReplaceArgs, UserNoteSetArgs, UserNoteViewArgs
17from tools.halt import halt_activity, HaltArgs
18from tools.thread import add_post_to_bluesky_reply_thread, ReplyThreadPostArgs
19from tools.ignore import ignore_notification, IgnoreNotificationArgs
20from tools.whitewind import create_whitewind_blog_post, WhitewindPostArgs
21from tools.ack import annotate_ack, AnnotateAckArgs
22from tools.webpage import fetch_webpage, WebpageArgs
23
24letta_config = get_letta_config()
25logging.basicConfig(level=logging.INFO)
26logger = logging.getLogger(__name__)
27console = Console()
28
29
30# Tool configurations: function paired with its args_schema and metadata
31TOOL_CONFIGS = [
32 {
33 "func": search_bluesky_posts,
34 "args_schema": SearchArgs,
35 "description": "Search for posts on Bluesky matching the given criteria",
36 "tags": ["bluesky", "search", "posts"]
37 },
38 {
39 "func": create_new_bluesky_post,
40 "args_schema": PostArgs,
41 "description": "Create a new Bluesky post or thread",
42 "tags": ["bluesky", "post", "create", "thread"]
43 },
44 {
45 "func": get_bluesky_feed,
46 "args_schema": FeedArgs,
47 "description": "Retrieve a Bluesky feed (home timeline or custom feed)",
48 "tags": ["bluesky", "feed", "timeline"]
49 },
50 # Note: attach_user_blocks is available on the server but not exposed to the agent
51 # to prevent the agent from managing its own memory blocks
52 {
53 "func": detach_user_blocks,
54 "args_schema": DetachUserBlocksArgs,
55 "description": "Detach user-specific memory blocks from the agent. Blocks are preserved for later use.",
56 "tags": ["memory", "blocks", "user"]
57 },
58 {
59 "func": user_note_append,
60 "args_schema": UserNoteAppendArgs,
61 "description": "Append a note to a user's memory block. Creates the block if it doesn't exist.",
62 "tags": ["memory", "blocks", "user", "append"]
63 },
64 {
65 "func": user_note_replace,
66 "args_schema": UserNoteReplaceArgs,
67 "description": "Replace text in a user's memory block.",
68 "tags": ["memory", "blocks", "user", "replace"]
69 },
70 {
71 "func": user_note_set,
72 "args_schema": UserNoteSetArgs,
73 "description": "Set the complete content of a user's memory block.",
74 "tags": ["memory", "blocks", "user", "set"]
75 },
76 {
77 "func": user_note_view,
78 "args_schema": UserNoteViewArgs,
79 "description": "View the content of a user's memory block.",
80 "tags": ["memory", "blocks", "user", "view"]
81 },
82 {
83 "func": halt_activity,
84 "args_schema": HaltArgs,
85 "description": "Signal to halt all bot activity and terminate bsky.py",
86 "tags": ["control", "halt", "terminate"]
87 },
88 {
89 "func": add_post_to_bluesky_reply_thread,
90 "args_schema": ReplyThreadPostArgs,
91 "description": "Add a single post to the current Bluesky reply thread atomically",
92 "tags": ["bluesky", "reply", "thread", "atomic"]
93 },
94 {
95 "func": ignore_notification,
96 "args_schema": IgnoreNotificationArgs,
97 "description": "Explicitly ignore a notification without replying (useful for ignoring bot interactions)",
98 "tags": ["notification", "ignore", "control", "bot"]
99 },
100 {
101 "func": create_whitewind_blog_post,
102 "args_schema": WhitewindPostArgs,
103 "description": "Create a blog post on Whitewind with markdown support",
104 "tags": ["whitewind", "blog", "post", "markdown"]
105 },
106 {
107 "func": annotate_ack,
108 "args_schema": AnnotateAckArgs,
109 "description": "Add a note to the acknowledgment record for the current post interaction",
110 "tags": ["acknowledgment", "note", "annotation", "metadata"]
111 },
112 {
113 "func": fetch_webpage,
114 "args_schema": WebpageArgs,
115 "description": "Fetch a webpage and convert it to markdown/text format using Jina AI reader",
116 "tags": ["web", "fetch", "webpage", "markdown", "jina"]
117 },
118]
119
120
121def register_tools(agent_id: str = None, tools: List[str] = None):
122 """Register tools with a Letta agent.
123
124 Args:
125 agent_id: ID of the agent to attach tools to. If None, uses config default.
126 tools: List of tool names to register. If None, registers all tools.
127 """
128 # Use agent ID from config if not provided
129 if agent_id is None:
130 agent_id = letta_config['agent_id']
131
132 try:
133 # Initialize Letta client with API key from config
134 client = Letta(token=letta_config['api_key'], timeout=letta_config['timeout'])
135
136 # Get the agent by ID
137 try:
138 agent = client.agents.retrieve(agent_id=agent_id)
139 except Exception as e:
140 console.print(f"[red]Error: Agent '{agent_id}' not found[/red]")
141 console.print(f"Error details: {e}")
142 return
143
144 # Filter tools if specific ones requested
145 tools_to_register = TOOL_CONFIGS
146 if tools:
147 tools_to_register = [t for t in TOOL_CONFIGS if t["func"].__name__ in tools]
148 if len(tools_to_register) != len(tools):
149 missing = set(tools) - {t["func"].__name__ for t in tools_to_register}
150 console.print(f"[yellow]Warning: Unknown tools: {missing}[/yellow]")
151
152 # Create results table
153 table = Table(title=f"Tool Registration for Agent '{agent.name}' ({agent_id})")
154 table.add_column("Tool", style="cyan")
155 table.add_column("Status", style="green")
156 table.add_column("Description")
157
158 # Register each tool
159 for tool_config in tools_to_register:
160 func = tool_config["func"]
161 tool_name = func.__name__
162
163 try:
164 # Create or update the tool using the standalone function
165 created_tool = client.tools.upsert_from_function(
166 func=func,
167 args_schema=tool_config["args_schema"],
168 tags=tool_config["tags"]
169 )
170
171 # Get current agent tools
172 current_tools = client.agents.tools.list(agent_id=str(agent.id))
173 tool_names = [t.name for t in current_tools]
174
175 # Check if already attached
176 if created_tool.name in tool_names:
177 table.add_row(tool_name, "Already Attached", tool_config["description"])
178 else:
179 # Attach to agent
180 client.agents.tools.attach(
181 agent_id=str(agent.id),
182 tool_id=str(created_tool.id)
183 )
184 table.add_row(tool_name, "✓ Attached", tool_config["description"])
185
186 except Exception as e:
187 table.add_row(tool_name, f"✗ Error: {str(e)}", tool_config["description"])
188 logger.error(f"Error registering tool {tool_name}: {e}")
189
190 console.print(table)
191
192 except Exception as e:
193 console.print(f"[red]Error: {str(e)}[/red]")
194 logger.error(f"Fatal error: {e}")
195
196
197def list_available_tools():
198 """List all available tools."""
199 table = Table(title="Available Void Tools")
200 table.add_column("Tool Name", style="cyan")
201 table.add_column("Description")
202 table.add_column("Tags", style="dim")
203
204 for tool_config in TOOL_CONFIGS:
205 table.add_row(
206 tool_config["func"].__name__,
207 tool_config["description"],
208 ", ".join(tool_config["tags"])
209 )
210
211 console.print(table)
212
213
214if __name__ == "__main__":
215 import argparse
216
217 parser = argparse.ArgumentParser(description="Register Void tools with a Letta agent")
218 parser.add_argument("--agent-id", help=f"Agent ID (default: from config)")
219 parser.add_argument("--tools", nargs="+", help="Specific tools to register (default: all)")
220 parser.add_argument("--list", action="store_true", help="List available tools")
221
222 args = parser.parse_args()
223
224 if args.list:
225 list_available_tools()
226 else:
227 # Use config default if no agent specified
228 agent_id = args.agent_id if args.agent_id else letta_config['agent_id']
229 console.print(f"\n[bold]Registering tools for agent: {agent_id}[/bold]\n")
230 register_tools(agent_id, args.tools)