|
| 1 | +# Intercom API helper functions for handling conversations and replies |
| 2 | +import os |
| 3 | +import requests |
| 4 | +import hashlib |
| 5 | +from flask import jsonify |
| 6 | +from html.parser import HTMLParser |
| 7 | + |
| 8 | +import logging |
| 9 | +logger = logging.getLogger(__name__) |
| 10 | + |
| 11 | +from utils import generate |
| 12 | + |
| 13 | +class BodyHTMLParser(HTMLParser): |
| 14 | + def __init__(self): |
| 15 | + super().__init__() |
| 16 | + self.text = [] |
| 17 | + |
| 18 | + def handle_data(self, data): |
| 19 | + self.text.append(data) |
| 20 | + |
| 21 | + def get_text(self): |
| 22 | + return ''.join(self.text) |
| 23 | + |
| 24 | +# Retrieve a conversation from Intercom API by its ID |
| 25 | +def fetch_intercom_conversation(conversation_id): |
| 26 | + # Sanitize conversation_id to allow only digits (Intercom conversation IDs are numeric) |
| 27 | + if not conversation_id.isdigit(): |
| 28 | + logger.error(f"Invalid conversation_id: {conversation_id}") |
| 29 | + return jsonify({"error": f"Invalid conversation_id: {conversation_id}"}), 400 |
| 30 | + |
| 31 | + url = "https://api.intercom.io/conversations/" + conversation_id |
| 32 | + token = os.getenv('INTERCOM_TOKEN') |
| 33 | + if not token: |
| 34 | + return jsonify({"error": "Intercom token not set"}), 500 |
| 35 | + |
| 36 | + headers = { |
| 37 | + "Content-Type": "application/json", |
| 38 | + "Intercom-Version": "2.13", |
| 39 | + "Authorization": "Bearer " + token |
| 40 | + } |
| 41 | + |
| 42 | + response = requests.get(url, headers=headers) |
| 43 | + if response.status_code != 200: |
| 44 | + logger.error(f"Failed to fetch conversation {conversation_id} from Intercom; status code: {response.status_code}, response: {response.text}") |
| 45 | + return jsonify({"error": "Failed to fetch conversation from Intercom"}), response.status_code |
| 46 | + |
| 47 | + return response, response.status_code |
| 48 | + |
| 49 | +# Determines the user query from the Intercom conversation response |
| 50 | +def get_user_query(response, conversation_id): |
| 51 | + # Extract conversation parts from an Intercom request response |
| 52 | + result = extract_conversation_parts(response) |
| 53 | + logger.info(f"Extracted {len(result)} parts from conversation {conversation_id}") |
| 54 | + |
| 55 | + # Get and join the latest user messages from the conversation parts |
| 56 | + joined_text = extract_latest_user_messages(result) |
| 57 | + if not joined_text: |
| 58 | + return "No entries made by user found.", 204 |
| 59 | + return joined_text, 200 |
| 60 | + |
| 61 | +# Extract conversation parts into a simplified JSON format |
| 62 | +def extract_conversation_parts(response): |
| 63 | + data = response.json() |
| 64 | + parts = data.get('conversation_parts', {}).get('conversation_parts', []) |
| 65 | + extracted_parts = [] |
| 66 | + for part in parts: |
| 67 | + body = part.get('body', '') |
| 68 | + if not body: |
| 69 | + continue |
| 70 | + author = part.get('author', {}) |
| 71 | + created_at = part.get('created_at') |
| 72 | + extracted_parts.append({'body': body, 'author': author, 'created_at': created_at}) |
| 73 | + return extracted_parts |
| 74 | + |
| 75 | +# Joins the latest user entries in the conversation starting from the last non-user (i.e. admin) entry |
| 76 | +def extract_latest_user_messages(conversation_parts): |
| 77 | + # Find the index of the last non-user entry |
| 78 | + last_non_user_idx = None |
| 79 | + for idx in range(len(conversation_parts) - 1, -1, -1): |
| 80 | + if conversation_parts[idx].get('author', {}).get('type') != 'user': |
| 81 | + last_non_user_idx = idx |
| 82 | + break |
| 83 | + |
| 84 | + # Collect user entries after the last non-user entry |
| 85 | + if last_non_user_idx is not None: |
| 86 | + last_user_entries = [ |
| 87 | + part for part in conversation_parts[last_non_user_idx + 1 :] |
| 88 | + if part.get('author', {}).get('type') == 'user' |
| 89 | + ] |
| 90 | + else: |
| 91 | + # If there is no non-user entry, include all user entries |
| 92 | + last_user_entries = [ |
| 93 | + part for part in conversation_parts if part.get('author', {}).get('type') == 'user' |
| 94 | + ] |
| 95 | + |
| 96 | + # If no user entries found, return None |
| 97 | + if not last_user_entries: |
| 98 | + return None |
| 99 | + |
| 100 | + # Only keep the 'body' field from each user entry |
| 101 | + bodies = [part['body'] for part in last_user_entries if 'body' in part] |
| 102 | + |
| 103 | + # Parse and concatenate all user message bodies as plain text |
| 104 | + parsed_bodies = [] |
| 105 | + for html_body in bodies: |
| 106 | + parsed_bodies.append(parse_html_to_text(html_body)) |
| 107 | + |
| 108 | + # Join all parsed user messages into a single string |
| 109 | + joined_text = " ".join(parsed_bodies) |
| 110 | + return joined_text |
| 111 | + |
| 112 | +# Helper function to parse HTML into plain text |
| 113 | +def parse_html_to_text(html_content): |
| 114 | + parser = BodyHTMLParser() |
| 115 | + parser.feed(html_content) |
| 116 | + return parser.get_text() |
| 117 | + |
| 118 | +# Store conversation ID in persistent storage |
| 119 | +def set_conversation_human_replied(conversation_id, redis_client): |
| 120 | + try: |
| 121 | + # Use a Redis set to avoid duplicates |
| 122 | + redis_client.set(conversation_id, '1', ex=60*60*24) # Set TTL expiration to 1 day |
| 123 | + logger.info(f"Added conversation_id {conversation_id} to Redis set admin_replied_conversations") |
| 124 | + except Exception as e: |
| 125 | + logger.error(f"Error adding conversation_id to Redis: {e}") |
| 126 | + |
| 127 | +# Check if a conversation is already marked as replied by a human admin |
| 128 | +def is_conversation_human_replied(conversation_id, redis_client): |
| 129 | + try: |
| 130 | + return redis_client.exists(conversation_id) |
| 131 | + except Exception as e: |
| 132 | + logger.error(f"Error checking conversation_id in Redis: {e}") |
| 133 | + return False |
| 134 | + |
| 135 | +# Post a reply to a conversation through Intercom API |
| 136 | +def post_intercom_reply(conversation_id, response_text): |
| 137 | + url = f"https://api.intercom.io/conversations/{conversation_id}/reply" |
| 138 | + token = os.getenv('INTERCOM_TOKEN') |
| 139 | + if not token: |
| 140 | + return jsonify({"error": "Intercom token not set"}), 500 |
| 141 | + |
| 142 | + headers = { |
| 143 | + "Content-Type": "application/json", |
| 144 | + "Authorization": "Bearer " + token |
| 145 | + } |
| 146 | + |
| 147 | + payload = { |
| 148 | + "message_type": "comment", |
| 149 | + "type": "admin", |
| 150 | + "admin_id": int(os.getenv('INTERCOM_ADMIN_ID')), |
| 151 | + "body": response_text |
| 152 | + } |
| 153 | + |
| 154 | + response = requests.post(url, json=payload, headers=headers) |
| 155 | + logger.info(f"Posted reply to Intercom; response status code: {response.status_code}") |
| 156 | + |
| 157 | + return response.json(), response.status_code |
| 158 | + |
| 159 | + |
| 160 | +# Returns a generated LLM answer to the Intercom conversation based on previous user message history |
| 161 | +def answer_intercom_conversation(conversation_id): |
| 162 | + logger.info(f"Received request to get conversation {conversation_id}") |
| 163 | + # Retrieves the history of the conversation thread in Intercom |
| 164 | + conversation, status_code = fetch_intercom_conversation(conversation_id) |
| 165 | + if status_code != 200: |
| 166 | + return jsonify(conversation), status_code |
| 167 | + |
| 168 | + # Extracts the user query (which are latest user messages joined into a single string) from conversation history |
| 169 | + user_query, status_code = get_user_query(conversation, conversation_id) |
| 170 | + if status_code != 200: |
| 171 | + return jsonify(user_query), status_code |
| 172 | + |
| 173 | + logger.info(f"Joined user messages: {user_query}") |
| 174 | + |
| 175 | + # Use a deterministic, non-reversible hash for anonymous_id for Intercom conversations |
| 176 | + anon_hash = hashlib.sha256(f"intercom-{conversation_id}".encode()).hexdigest() |
| 177 | + |
| 178 | + # Generate the exact response using the RAG system |
| 179 | + llm_response = "".join(generate(user_query, 'Intercom Conversation', anon_hash)) |
| 180 | + llm_response = llm_response + " 🤖" # Add a marker to indicate the end of the response |
| 181 | + |
| 182 | + logger.info(f"LLM response: {llm_response}") |
| 183 | + |
| 184 | + return post_intercom_reply(conversation_id, llm_response) |
| 185 | + |
| 186 | +def check_intercom_ip(request): |
| 187 | + # Restrict webhook access to a list of allowed IP addresses |
| 188 | + INTERCOM_ALLOWED_IPS = [ |
| 189 | + "34.231.68.152", |
| 190 | + "34.197.76.213", |
| 191 | + "35.171.78.91", |
| 192 | + "35.169.138.21", |
| 193 | + "52.70.27.159", |
| 194 | + "52.44.63.161" |
| 195 | + ] |
| 196 | + remote_ip = request.headers.get('X-Forwarded-For', request.remote_addr) |
| 197 | + # X-Forwarded-For may contain a comma-separated list; take the first IP |
| 198 | + remote_ip = remote_ip.split(',')[0].strip() if remote_ip else None |
| 199 | + |
| 200 | + if remote_ip not in INTERCOM_ALLOWED_IPS: |
| 201 | + # logger.info(f"Rejected webhook from unauthorized IP: {remote_ip}") |
| 202 | + return False |
| 203 | + |
| 204 | + return True |
0 commit comments