|
| 1 | +""" |
| 2 | +Link Product to Pipeline Item Tool |
| 3 | +
|
| 4 | +Lets the agent record a sale during the conversation by linking a product |
| 5 | +(optionally a variant + quantity + notes) to the pipeline_item attached to |
| 6 | +the conversation. The CRM endpoint snapshots the price at link time, so |
| 7 | +later changes to Product.default_price never alter recorded sales. |
| 8 | +
|
| 9 | +Backend endpoint: |
| 10 | + POST /api/v1/pipeline_items/{pipeline_item_id}/products |
| 11 | +
|
| 12 | +Body: |
| 13 | + { product_id, product_variant_id?, quantity, notes?, |
| 14 | + created_by_type: "AiAgent", created_by_id: <agent_id> } |
| 15 | +""" |
| 16 | + |
| 17 | +from typing import Any, Dict, Optional |
| 18 | + |
| 19 | +from google.adk.tools import FunctionTool, ToolContext |
| 20 | + |
| 21 | +from src.services.adk.tools.evo_crm.base import EvoCrmClient |
| 22 | +from src.utils.logger import setup_logger |
| 23 | + |
| 24 | +logger = setup_logger(__name__) |
| 25 | + |
| 26 | + |
| 27 | +def _extract_pipeline_item_id(tool_context: Optional[ToolContext]) -> Optional[str]: |
| 28 | + """Extract pipeline_item_id from tool_context.state. |
| 29 | +
|
| 30 | + Looked up in order: |
| 31 | + - evoai_crm_data.pipeline_item_id |
| 32 | + - evoai_crm_data.pipeline_item.id |
| 33 | + - pipeline_item_id (direct) |
| 34 | + - pipelineItemId (camelCase) |
| 35 | + """ |
| 36 | + if not tool_context or not hasattr(tool_context, "state"): |
| 37 | + return None |
| 38 | + |
| 39 | + state = tool_context.state |
| 40 | + |
| 41 | + evoai_crm_data = state.get("evoai_crm_data", {}) |
| 42 | + if isinstance(evoai_crm_data, dict): |
| 43 | + direct = evoai_crm_data.get("pipeline_item_id") |
| 44 | + if direct: |
| 45 | + return str(direct) |
| 46 | + |
| 47 | + pipeline_item = evoai_crm_data.get("pipeline_item", {}) |
| 48 | + if isinstance(pipeline_item, dict): |
| 49 | + value = pipeline_item.get("id") |
| 50 | + if value: |
| 51 | + return str(value) |
| 52 | + |
| 53 | + for key in ("pipeline_item_id", "pipelineItemId"): |
| 54 | + if key in state: |
| 55 | + return str(state[key]) |
| 56 | + |
| 57 | + return None |
| 58 | + |
| 59 | + |
| 60 | +def _extract_agent_id(tool_context: Optional[ToolContext]) -> Optional[str]: |
| 61 | + """Best-effort lookup for the AI agent id so the sale row records the actor.""" |
| 62 | + if not tool_context or not hasattr(tool_context, "state"): |
| 63 | + return None |
| 64 | + |
| 65 | + state = tool_context.state |
| 66 | + for key in ("agent_id", "ai_agent_id", "agentId"): |
| 67 | + if key in state: |
| 68 | + return str(state[key]) |
| 69 | + |
| 70 | + evoai_crm_data = state.get("evoai_crm_data", {}) |
| 71 | + if isinstance(evoai_crm_data, dict): |
| 72 | + for key in ("agent_id", "ai_agent_id"): |
| 73 | + if key in evoai_crm_data: |
| 74 | + return str(evoai_crm_data[key]) |
| 75 | + |
| 76 | + return None |
| 77 | + |
| 78 | + |
| 79 | +def create_link_product_to_pipeline_item_tool() -> FunctionTool: |
| 80 | + """Factory for the link_product_to_pipeline_item tool.""" |
| 81 | + |
| 82 | + client = EvoCrmClient() |
| 83 | + |
| 84 | + async def link_product_to_pipeline_item( |
| 85 | + product_id: str, |
| 86 | + quantity: int = 1, |
| 87 | + product_variant_id: Optional[str] = None, |
| 88 | + notes: Optional[str] = None, |
| 89 | + pipeline_item_id: Optional[str] = None, |
| 90 | + tool_context: Optional[ToolContext] = None, |
| 91 | + ) -> Dict[str, Any]: |
| 92 | + """Link a product (optionally a variant) to the current pipeline item. |
| 93 | +
|
| 94 | + Use this tool when the user has confirmed they will purchase one or |
| 95 | + more of the catalog products listed in the <product-catalog> block of |
| 96 | + your instruction. It registers the sale on the pipeline card so a |
| 97 | + human can pick up follow-up actions. The unit price is locked at the |
| 98 | + moment of the call — do NOT call this tool just because the user |
| 99 | + asked about a product; only call it when the purchase intent is |
| 100 | + clear. |
| 101 | +
|
| 102 | + Args: |
| 103 | + product_id: UUID of the product to link. Required. |
| 104 | + quantity: How many units. Must be a positive integer. Defaults to 1. |
| 105 | + product_variant_id: Optional UUID of the variant (e.g. size/color). |
| 106 | + notes: Optional free-form note recorded with the sale. |
| 107 | + pipeline_item_id: Optional UUID; auto-extracted from context when |
| 108 | + omitted (the conversation's pipeline_item). |
| 109 | + tool_context: Provided automatically by the runtime. |
| 110 | +
|
| 111 | + Returns: |
| 112 | + Dictionary with status, the created link details and a |
| 113 | + human-readable message. |
| 114 | + """ |
| 115 | + effective_pi_id = pipeline_item_id |
| 116 | + if not effective_pi_id and tool_context: |
| 117 | + effective_pi_id = _extract_pipeline_item_id(tool_context) |
| 118 | + if effective_pi_id: |
| 119 | + logger.info(f"Extracted pipeline_item_id from context: {effective_pi_id}") |
| 120 | + |
| 121 | + if not effective_pi_id: |
| 122 | + return { |
| 123 | + "status": "error", |
| 124 | + "message": ( |
| 125 | + "pipeline_item_id is required. It should be auto-extracted from the " |
| 126 | + "conversation context; provide it explicitly only if the conversation " |
| 127 | + "is not attached to a pipeline." |
| 128 | + ), |
| 129 | + "pipeline_item_id": None, |
| 130 | + } |
| 131 | + |
| 132 | + if not product_id: |
| 133 | + return { |
| 134 | + "status": "error", |
| 135 | + "message": "product_id is required.", |
| 136 | + "pipeline_item_id": effective_pi_id, |
| 137 | + } |
| 138 | + |
| 139 | + try: |
| 140 | + qty = int(quantity) |
| 141 | + except (TypeError, ValueError): |
| 142 | + return { |
| 143 | + "status": "error", |
| 144 | + "message": "quantity must be a positive integer.", |
| 145 | + "pipeline_item_id": effective_pi_id, |
| 146 | + } |
| 147 | + |
| 148 | + if qty < 1: |
| 149 | + return { |
| 150 | + "status": "error", |
| 151 | + "message": "quantity must be at least 1.", |
| 152 | + "pipeline_item_id": effective_pi_id, |
| 153 | + } |
| 154 | + |
| 155 | + agent_id = _extract_agent_id(tool_context) |
| 156 | + |
| 157 | + payload: Dict[str, Any] = { |
| 158 | + "product_id": str(product_id), |
| 159 | + "quantity": qty, |
| 160 | + "created_by_type": "AiAgent", |
| 161 | + } |
| 162 | + if product_variant_id: |
| 163 | + payload["product_variant_id"] = str(product_variant_id) |
| 164 | + if notes: |
| 165 | + payload["notes"] = str(notes) |
| 166 | + if agent_id: |
| 167 | + payload["created_by_id"] = agent_id |
| 168 | + |
| 169 | + endpoint = f"/pipeline_items/{effective_pi_id}/products" |
| 170 | + |
| 171 | + try: |
| 172 | + response = await client.post(endpoint=endpoint, json_data=payload) |
| 173 | + except Exception as api_error: |
| 174 | + error_message = str(api_error) |
| 175 | + if "404" in error_message or "not found" in error_message.lower(): |
| 176 | + error_message = ( |
| 177 | + f"Pipeline item {effective_pi_id} or product {product_id} not found." |
| 178 | + ) |
| 179 | + elif "401" in error_message or "unauthorized" in error_message.lower(): |
| 180 | + error_message = ( |
| 181 | + "Authentication failed. Check EVOAI_CRM_API_TOKEN configuration." |
| 182 | + ) |
| 183 | + elif "422" in error_message or "unprocessable" in error_message.lower(): |
| 184 | + error_message = ( |
| 185 | + "The CRM rejected the link payload (validation error). " |
| 186 | + "Double-check product_id, product_variant_id (must belong to the product) " |
| 187 | + "and quantity (>0)." |
| 188 | + ) |
| 189 | + |
| 190 | + logger.error(f"link_product_to_pipeline_item failed: {error_message}") |
| 191 | + return { |
| 192 | + "status": "error", |
| 193 | + "message": error_message, |
| 194 | + "pipeline_item_id": effective_pi_id, |
| 195 | + "product_id": product_id, |
| 196 | + "error": str(api_error), |
| 197 | + } |
| 198 | + |
| 199 | + data = response.get("data") if isinstance(response, dict) else None |
| 200 | + product_summary = data.get("product") if isinstance(data, dict) else None |
| 201 | + product_name = ( |
| 202 | + product_summary.get("name") if isinstance(product_summary, dict) else None |
| 203 | + ) or product_id |
| 204 | + |
| 205 | + logger.info( |
| 206 | + f"Linked product {product_id} (qty={qty}) to pipeline_item {effective_pi_id}" |
| 207 | + ) |
| 208 | + |
| 209 | + return { |
| 210 | + "status": "success", |
| 211 | + "message": f"Recorded {qty}x {product_name} on the pipeline card.", |
| 212 | + "pipeline_item_id": effective_pi_id, |
| 213 | + "product_id": product_id, |
| 214 | + "product_variant_id": product_variant_id, |
| 215 | + "quantity": qty, |
| 216 | + "details": data, |
| 217 | + } |
| 218 | + |
| 219 | + link_product_to_pipeline_item.__name__ = "link_product_to_pipeline_item" |
| 220 | + |
| 221 | + return FunctionTool(func=link_product_to_pipeline_item) |
0 commit comments