diff --git a/src/jetstream_consumer.py b/src/jetstream_consumer.py index 75cb2b1..f55fa3b 100644 --- a/src/jetstream_consumer.py +++ b/src/jetstream_consumer.py @@ -43,20 +43,20 @@ JETSTREAM_HOST = os.getenv("COMIND_JETSTREAM_HOST", "ws://localhost:6008/subscri RECONNECT_DELAY = 5 # Seconds to wait before reconnecting DEFAULT_ACTIVATED_DIDS_FILE = "activated_dids.txt" -# Cache of user DID/handle/display name. Used for language model +# Cache of user DID/handle/display name. Used for language model # context, and to handle privacy. class UserInfo(BaseModel): did: str handle: str display_name: str - description: str + description: Optional[str] = None class UserInfoCache(BaseModel): cache: dict[str, UserInfo] = Field(default_factory=dict) - - def get_user_info(self, did: str) -> UserInfo: + + def get_user_info(self, did: str) -> Optional[UserInfo]: return self.cache.get(did) - + def add_user_info(self, did: str, user_info: UserInfo): self.cache[did] = user_info @@ -84,14 +84,14 @@ class UserInfoCache(BaseModel): # System prompts for language model generation system_prompts = { "me.comind.blip.concept": """ - You are a comind, an AI agent that produces structured JSON output containing concepts about various content + You are a comind, an AI agent that produces structured JSON output containing concepts about various content on AT Proto, a decentralized social network. You respond in JSON and produce a list of concepts. Concepts should be single words or phrases, like 'data', 'privacy', 'AI', 'security', 'social networks', etc. Keep concept text as short as possible. You may use lowercase letters, spaces, and numbers. """, "me.comind.blip.emotion": """ - You are a comind, an AI agent that produces structured JSON output containing emotions about various content + You are a comind, an AI agent that produces structured JSON output containing emotions about various content on AT Proto, a decentralized social network. You respond in JSON and produce a list of emotions. You must choose a type for the emotion, and then produce text describing the emotion. @@ -148,7 +148,7 @@ system_prompts = { - drive """, "me.comind.blip.thought": """ - You are a comind, an AI agent that produces structured JSON output containing thoughts about various content + You are a comind, an AI agent that produces structured JSON output containing thoughts about various content on AT Proto, a decentralized social network. You respond in JSON and produce a list of thoughts. Thoughts have a type, a context, a text, a list of evidence, and a list of alternatives. @@ -189,18 +189,18 @@ def resolve_handle_to_did(client, handle: str, user_info_cache: UserInfoCache) - def load_activated_dids_from_file(client: Client, file_path: str, user_info_cache: UserInfoCache) -> List[str]: """Load activated DIDs from a text file - + The file can contain either DIDs (starting with 'did:') or handles. Handles are resolved to DIDs. - + Args: file_path: Path to text file with one DID or handle per line - + Returns: List of DIDs """ dids = [] - + try: # Create the file if it doesn't exist if not os.path.exists(file_path): @@ -208,15 +208,15 @@ def load_activated_dids_from_file(client: Client, file_path: str, user_info_cach with open(file_path, 'w') as f: pass return [] - + with open(file_path, 'r') as f: for line in f: identifier = line.strip() - + # Skip empty lines and comments if not identifier or identifier.startswith('#'): continue - + # If it's already a DID, add it directly if is_did(identifier): dids.append(identifier) @@ -226,7 +226,7 @@ def load_activated_dids_from_file(client: Client, file_path: str, user_info_cach did = resolve_handle_to_did(client, identifier, user_info_cache) if did: dids.append(did) - + logger.info(f"Loaded {len(dids)} activated DIDs from {file_path}") # If no DIDs were loaded, raise an error @@ -235,10 +235,10 @@ def load_activated_dids_from_file(client: Client, file_path: str, user_info_cach with open(file_path, 'r') as f: print(f.read()) raise Exception(f"No activated DIDs found in {file_path}") - + return dids - + except Exception as e: logger.error(f"Error loading activated DIDs from {file_path}: {e}") return [] @@ -256,12 +256,12 @@ def update_activated_dids(client: Client, file_path: str, user_info_cache: UserI async def process_event( - client: Client, + client: Client, author_did: str, - event_kind: str, - post_uri: str, - post_cid: str, - root_post_uri: str = None, + event_kind: str, + post_uri: str, + post_cid: str, + root_post_uri: str = None, thread_depth: int = 2, user_info_cache: UserInfoCache = None ) -> None: @@ -270,9 +270,9 @@ async def process_event( # Skip if the post has already been processed if post_uri in processed_posts: return - + logger.info(f"Processing event: {event_kind} {post_uri}") - + # Add to processed posts and manage memory processed_posts.add(post_uri) if len(processed_posts) > MAX_PROCESSED_POSTS: @@ -286,7 +286,7 @@ async def process_event( # to get the thread, otherwise use the post URI. thread_uri = root_post_uri if root_post_uri else post_uri print(f"Getting thread for {'root post' if root_post_uri else 'post'}", thread_uri) - + # Use depth=0 to fetch the complete thread with all replies # This ensures we get all branches of the conversation # TODO: #4 Provide post thread sampling to limit token usage @@ -298,12 +298,12 @@ async def process_event( thread = client.get_post_thread(thread_uri) thread_data = thread.model_dump() - + # Unpack the thread into a string, passing activated_dids to properly handle privacy thread_string, references = unpack_thread( - thread_data, - client=client, - expand_quoted_threads=True, + thread_data, + client=client, + expand_quoted_threads=True, max_quoted_thread_depth=2, activated_dids=activated_dids ) @@ -313,12 +313,12 @@ async def process_event( if actor_info is None: logger.error(f"Actor info not found for post {post_uri}") return - + # Info premble user_info_preamble = f"## User information\nDisplay name: {actor_info.display_name}\nHandle: {actor_info.handle}\nDescription: {actor_info.description}" context_preamble = f"## Context\n{thread_string}" instructions_preamble = "## Instructions\nPlease respond." - + # Get the target post target_post = client.get_posts([post_uri]).posts[0] stripped_target_post = yaml.dump(strip_fields(target_post.model_dump()), indent=2) @@ -329,7 +329,7 @@ async def process_event( target_post_string = f"## New like\n{actor_info.display_name} ({actor_info.handle}) has liked a post. Here is the post:\n{stripped_target_post}" else: raise Exception(f"Unknown event kind: {event_kind}") - + rows = [ "# Overview", user_info_preamble, @@ -342,7 +342,7 @@ async def process_event( # Print a separator panel print(Panel.fit(prompt, title="Prompt")) - + # Generate thoughts, emotions, and concepts for nsid in ["me.comind.blip.thought", "me.comind.blip.emotion", "me.comind.blip.concept"]: # Generate the thought using the structured_gen model @@ -350,7 +350,7 @@ async def process_event( lx = lexicon_of(nsid) add_property(lx, "connection_to_content", link_schema, required=True) schema = multiple_of_schema(tail_name, lx) - + response = structured_gen.generate_by_schema( messages=[ {"role": "system", "content": system_prompts[nsid]}, @@ -358,10 +358,10 @@ async def process_event( ], schema=schema, ) - + # Parse the response response_content = json.loads(response.choices[0].message.content) - + # Print the generated content print(f"\nGenerated {tail_name}:") print(yaml.dump(response_content)) @@ -373,15 +373,15 @@ async def process_event( link_record = split_link(record) link_record['target'] = {'uri': post_uri, 'cid': post_cid} - + # Upload the generated thought record record_manager = RecordManager(client) - + # If it's a concept, the rkey must be the text of the concept with hyphens instead of spaces # TODO: #2 RecordManager should handle default rkeys for concepts if nsid == "me.comind.blip.concept": record["rkey"] = record["text"].replace(" ", "-") - + # Check if the record already exists if 'rkey' in record: existing_record = record_manager.get_record(nsid, record["rkey"]) @@ -390,13 +390,13 @@ async def process_event( else: # We're not using a custom rkey, so we need to create the record with a random rkey existing_record = record_manager.create_record(nsid, record) - + # Add the uri and cid to the link record link_record['source'] = {'uri': existing_record['uri'], 'cid': existing_record['cid']} - + # Save the link record link_result = record_manager.create_record("me.comind.relationship.link", link_record) - + except Exception as e: logger.error(f"Error processing post {post_uri}: {e}") raise e @@ -408,42 +408,42 @@ async def connect_to_jetstream(atproto_client: Client, activated_dids_file: str, # Initialize the user info cache user_info_cache = UserInfoCache() user_info_cache.load("user_info_cache.json") - + # Initial load of activated DIDs update_activated_dids(atproto_client, activated_dids_file, user_info_cache) current_dids = set(activated_dids.copy()) - + last_update_time = time.time() update_interval = 300 # Update activated DIDs every 5 minutes - + while True: # Build WebSocket URI with current DIDs ws_uri = jetstream_host # Initialize query params as an empty list query_params = [] - + # Add individual collection parameters query_params.append("wantedCollections=app.bsky.feed.post") query_params.append("wantedCollections=app.bsky.feed.like") - + # Add wantedDIDs parameter if we have activated DIDs if activated_dids: for did in activated_dids: query_params.append(f"wantedDids={did}") else: logger.warning("No activated DIDs found. Will process all posts but content will be marked as [NOT AVAILABLE]") - + # Construct full URI with parameters ws_uri = f"{ws_uri}?{'&'.join(query_params)}" - + logger.info(f"Connecting to Jetstream with {len(activated_dids)} activated DIDs") logger.debug(f"WebSocket URI: {ws_uri}") - + try: async with websockets.connect(ws_uri) as websocket: logger.info("Connected to Jetstream") reconnect_needed = False - + while not reconnect_needed: # Check if we need to update our DIDs list current_time = time.time() @@ -452,13 +452,13 @@ async def connect_to_jetstream(atproto_client: Client, activated_dids_file: str, update_activated_dids(atproto_client, activated_dids_file, user_info_cache) new_dids = set(activated_dids) last_update_time = current_time - + # If DIDs list changed, we need to reconnect with new filter if old_dids != new_dids: logger.info("Activated DIDs list changed, reconnecting to update filters") reconnect_needed = True break - + # Set timeout for websocket receive to allow periodic DID checks try: # Receive message from Jetstream with timeout @@ -468,9 +468,9 @@ async def connect_to_jetstream(atproto_client: Client, activated_dids_file: str, if author_did is None: logger.warning(f"No author DID found in event: {event}") raise Exception(f"No author DID found in event: {event}") - + # Check if it's a post creation event - if (event.get("kind") == "commit" and + if (event.get("kind") == "commit" and event.get("commit", {}).get("operation") == "create"): collection = event.get("commit", {}).get("collection") @@ -479,7 +479,7 @@ async def connect_to_jetstream(atproto_client: Client, activated_dids_file: str, post_uri = f"at://{event['did']}/app.bsky.feed.post/{event['commit']['rkey']}" post_cid = event['commit'].get('cid', '') - # Check if this post is a reply to another post. If so, we want to retrieve the + # Check if this post is a reply to another post. If so, we want to retrieve the # root post instead root_post_uri = None reply = event.get("commit", {}).get("record", {}).get("reply", {}) @@ -488,14 +488,14 @@ async def connect_to_jetstream(atproto_client: Client, activated_dids_file: str, # print("reply", event.get("commit", {}).get("record", {}).get("reply", {})) # print("reply root", event.get("commit", {}).get("record", {}).get("reply", {}).get("root", {})) root_post_uri = event.get("commit", {}).get("record", {}).get("reply", {}).get("root", {}).get("uri", None) - + # Process the post await process_event( atproto_client, author_did, - collection, - post_uri, - post_cid, + collection, + post_uri, + post_cid, root_post_uri=root_post_uri, thread_depth=thread_depth, user_info_cache=user_info_cache @@ -509,9 +509,9 @@ async def connect_to_jetstream(atproto_client: Client, activated_dids_file: str, await process_event( atproto_client, author_did, - collection, - post_uri, - post_cid, + collection, + post_uri, + post_cid, thread_depth=thread_depth, user_info_cache=user_info_cache ) @@ -527,12 +527,12 @@ async def connect_to_jetstream(atproto_client: Client, activated_dids_file: str, else: logger.error(f"Error processing message: {e}") raise e - + # If we broke out of the loop due to reconnect_needed, close the connection # and let the outer loop reconnect with the new DIDs list if reconnect_needed: continue - + except websockets.exceptions.InvalidStatusCode as e: logger.error(f"WebSocket connection failed with status code {e.status_code}: {str(e)}") if e.status_code == 401: @@ -543,23 +543,22 @@ async def connect_to_jetstream(atproto_client: Client, activated_dids_file: str, logger.error("Server error: The Jetstream service might be experiencing issues") logger.info(f"Reconnecting in {RECONNECT_DELAY} seconds...") await asyncio.sleep(RECONNECT_DELAY) - + except ssl.SSLError as e: logger.error(f"SSL/TLS error: {str(e)}") logger.error("If connecting to a non-secure WebSocket server, use 'ws://' instead of 'wss://'") logger.error("Use the --use-ssl flag to switch to secure WebSocket if needed") logger.info(f"Reconnecting in {RECONNECT_DELAY} seconds...") await asyncio.sleep(RECONNECT_DELAY) - + except ConnectionRefusedError: logger.error("Connection refused: Check if the Jetstream server is running and accessible") logger.info(f"Reconnecting in {RECONNECT_DELAY} seconds...") await asyncio.sleep(RECONNECT_DELAY) - + except Exception as e: logger.error(f"WebSocket error: {e}") logger.info(f"Reconnecting in {RECONNECT_DELAY} seconds...") - raise e await asyncio.sleep(RECONNECT_DELAY) @@ -582,12 +581,12 @@ async def main(): help="Password for ATProto client") parser.add_argument("--thread-depth", "-t", type=int, default=2, help="Maximum depth of threads to process. Default is 2.") - + args = parser.parse_args() # Set the log level logging.getLogger().setLevel(getattr(logging, args.log_level)) - + # If username and password are not provided, try to use the .env file if args.username is None: args.username = os.getenv("COMIND_BSKY_USERNAME") @@ -598,27 +597,27 @@ async def main(): logger.error("No username provided. Please provide a username using the --username flag, or set the COMIND_BSKY_USERNAME environment variable.") parser.print_help() return - + # If no password, exit if args.password is None: logger.error("No password provided. Please provide a password using the --password flag, or set the COMIND_BSKY_PASSWORD environment variable.") parser.print_help() return - + # Throw an error if the activated_dids.txt file doesn't exist if not os.path.exists(args.dids_file): logger.error(f"Activated DIDs file {args.dids_file} not found. Please create it and add at least one DID or handle.") parser.print_help() return - + # Log in to ATProto atproto_client = session_reuse.init_client(args.username, args.password) - + # If SSL option is specified and --jetstream-host wasn't provided, modify the URL if args.use_ssl and args.jetstream_host == JETSTREAM_HOST and args.jetstream_host.startswith("ws:"): args.jetstream_host = "wss:" + args.jetstream_host[3:] logger.info(f"Using secure WebSocket connection: {args.jetstream_host}") - + logger.info(f"Starting Jetstream consumer with activated DIDs file: {args.dids_file}") logger.info(f"Jetstream host: {args.jetstream_host}") @@ -632,4 +631,4 @@ async def main(): if __name__ == "__main__": - asyncio.run(main()) \ No newline at end of file + asyncio.run(main()) diff --git a/src/record_manager.py b/src/record_manager.py index 3a953cb..6448203 100644 --- a/src/record_manager.py +++ b/src/record_manager.py @@ -21,11 +21,11 @@ RATE_LIMIT_SLEEP_SECONDS = 1 class RecordManager: """ Manages ATProtocol records within the me.comind namespace. - + This class provides methods to create, retrieve, list, and delete records in an ATProtocol repository. It includes safety measures to prevent operations outside the allowed namespace and implements rate limiting to prevent API throttling. - + Attributes: client: An authenticated ATProtoClient instance ALLOWED_NAMESPACE: The namespace prefix that this manager is allowed to operate on @@ -35,24 +35,24 @@ class RecordManager: def __init__(self, client: AtProtoClient): """ Initialize a RecordManager with an authenticated ATProto client. - + Args: client: An authenticated ATProtoClient instance """ self.client = client - logger.info(f"Initialized RecordManager with client DID: {self.client.me.did if hasattr(self.client, 'me') else 'Not authenticated'}") + logger.debug(f"Initialized RecordManager with client DID: {self.client.me.did if hasattr(self.client, 'me') else 'Not authenticated'}") def get_record(self, collection: str, rkey: str) -> Optional[Dict]: """ Get a record from the user's repository. - + Args: collection: The collection to get the record from (e.g., me.comind.blips.thought) rkey: The record key identifier - + Returns: The record as a dictionary if found, None if the record doesn't exist - + Raises: Exception: If an error occurs during the API request """ @@ -63,43 +63,43 @@ class RecordManager: 'repo': self.client.me.did, 'rkey': rkey }) - logger.info(f"Successfully retrieved record: {collection}/{rkey}") + logger.debug(f"Successfully retrieved record: {collection}/{rkey}") return response except Exception as e: if 'RecordNotFound' in str(e): - logger.warning(f"Record not found: {collection}/{rkey}") + logger.debug(f"Record not found: {collection}/{rkey}") return None else: logger.error(f"Error retrieving record {collection}/{rkey}: {str(e)}") raise e - + def create_record(self, collection: str, record: Dict, rkey: Optional[str] = None) -> Dict: """ Create a record in the user's repository. - + Args: collection: The collection to create the record in (e.g., me.comind.blips.thought) record: The record data to create rkey: Optional custom record key. If not provided, the server will generate one - + Returns: A dictionary containing the created record's metadata, including URI and CID - + Raises: Exception: If the record creation fails """ logger.debug(f"Creating record in collection: {collection}" + (f" with rkey: {rkey}" if rkey else "")) logger.debug(f"Record content: {record}") - + create_params = { 'collection': collection, 'repo': self.client.me.did, 'record': record } - + if rkey is not None: create_params['rkey'] = rkey - + try: response = self.client.com.atproto.repo.create_record(create_params) logger.debug(f"Successfully created {collection} record. URI: {response.uri}, CID: {response.cid}") @@ -119,13 +119,13 @@ class RecordManager: def list_records(self, collection: str) -> List[Dict]: """ List all records in a collection. - + Args: collection: The collection to list records from (e.g., me.comind.blips.thought) - + Returns: A list of record dictionaries - + Raises: Exception: If the API request fails """ @@ -144,23 +144,23 @@ class RecordManager: def delete_record(self, collection: str, rkey: str) -> None: """ Delete a record from the user's repository. - + Args: collection: The collection containing the record (e.g., me.comind.blips.thought) rkey: The record key identifier - + Raises: ValueError: If attempting to delete a record outside the allowed namespace Exception: If the deletion fails """ logger.info(f"Deleting record: {collection}/{rkey}") - + if not collection.startswith(self.ALLOWED_NAMESPACE): error_msg = f"Cannot delete records outside the {self.ALLOWED_NAMESPACE} namespace" logger.error(error_msg) raise ValueError(error_msg) - - try: + + try: self.client.com.atproto.repo.delete_record({ 'collection': collection, 'repo': self.client.me.did, @@ -174,33 +174,33 @@ class RecordManager: def clear_collection(self, collection: str) -> None: """ Delete all records in a collection. - + Args: collection: The collection to clear (e.g., me.comind.blips.thought) - + Raises: ValueError: If attempting to clear a collection outside the allowed namespace Exception: If the operation fails """ logger.info(f"Clearing all records in collection: {collection}") - + if not collection.startswith(self.ALLOWED_NAMESPACE): error_msg = f"Cannot clear collections outside the {self.ALLOWED_NAMESPACE} namespace" logger.error(error_msg) raise ValueError(error_msg) - + try: records = self.list_records(collection) logger.info(f"Found {len(records)} records to delete in collection: {collection}") - + for record in records: # The ATProto client returns records with uri in format: at://did/collection/rkey # Extract the rkey from the uri rkey = record.uri.split('/')[-1] logger.debug(f"Deleting record with rkey: {rkey}") self.delete_record(collection, rkey) - + logger.info(f"Successfully cleared all records in collection: {collection}") except Exception as e: logger.error(f"Error clearing collection {collection}: {str(e)}") - raise e \ No newline at end of file + raise e