|
| 1 | +from lib.vcon_redis import VconRedis |
| 2 | +from lib.logging_utils import init_logger |
| 3 | +import logging |
| 4 | +import json |
| 5 | +from openai import OpenAI |
| 6 | +from tenacity import ( |
| 7 | + retry, |
| 8 | + stop_after_attempt, |
| 9 | + wait_exponential, |
| 10 | + before_sleep_log, |
| 11 | +) # for exponential backoff |
| 12 | +from lib.metrics import init_metrics, stats_gauge, stats_count |
| 13 | +import time |
| 14 | +from lib.links.filters import is_included, randomly_execute_with_sampling |
| 15 | + |
| 16 | +init_metrics() |
| 17 | + |
| 18 | +logger = init_logger(__name__) |
| 19 | + |
| 20 | +default_options = { |
| 21 | + "prompt": "Analyze this transcript and provide a list of relevant labels for categorization. Return your response as a JSON object with a single key 'labels' containing an array of strings.", |
| 22 | + "analysis_type": "labeled_analysis", |
| 23 | + "model": "gpt-4-turbo", |
| 24 | + "sampling_rate": 1, |
| 25 | + "temperature": 0.2, |
| 26 | + "source": { |
| 27 | + "analysis_type": "transcript", |
| 28 | + "text_location": "body.paragraphs.transcript", |
| 29 | + }, |
| 30 | + "response_format": {"type": "json_object"} |
| 31 | +} |
| 32 | + |
| 33 | + |
| 34 | +def get_analysis_for_type(vcon, index, analysis_type): |
| 35 | + for a in vcon.analysis: |
| 36 | + if a["dialog"] == index and a["type"] == analysis_type: |
| 37 | + return a |
| 38 | + return None |
| 39 | + |
| 40 | + |
| 41 | +@retry( |
| 42 | + wait=wait_exponential(multiplier=2, min=1, max=65), |
| 43 | + stop=stop_after_attempt(6), |
| 44 | + before_sleep=before_sleep_log(logger, logging.INFO), |
| 45 | +) |
| 46 | +def generate_analysis_with_labels(transcript, prompt, model, temperature, client, response_format) -> dict: |
| 47 | + messages = [ |
| 48 | + {"role": "system", "content": "You are a helpful assistant that analyzes text and provides relevant labels."}, |
| 49 | + {"role": "user", "content": prompt + "\n\n" + transcript}, |
| 50 | + ] |
| 51 | + |
| 52 | + response = client.chat.completions.create( |
| 53 | + model=model, |
| 54 | + messages=messages, |
| 55 | + temperature=temperature, |
| 56 | + response_format=response_format |
| 57 | + ) |
| 58 | + |
| 59 | + return response.choices[0].message.content |
| 60 | + |
| 61 | + |
| 62 | +def run( |
| 63 | + vcon_uuid, |
| 64 | + link_name, |
| 65 | + opts=default_options, |
| 66 | +): |
| 67 | + module_name = __name__.split(".")[-1] |
| 68 | + logger.info(f"Starting {module_name}: {link_name} plugin for: {vcon_uuid}") |
| 69 | + merged_opts = default_options.copy() |
| 70 | + merged_opts.update(opts) |
| 71 | + opts = merged_opts |
| 72 | + |
| 73 | + vcon_redis = VconRedis() |
| 74 | + vCon = vcon_redis.get_vcon(vcon_uuid) |
| 75 | + |
| 76 | + if not is_included(opts, vCon): |
| 77 | + logger.info(f"Skipping {link_name} vCon {vcon_uuid} due to filters") |
| 78 | + return vcon_uuid |
| 79 | + |
| 80 | + if not randomly_execute_with_sampling(opts): |
| 81 | + logger.info(f"Skipping {link_name} vCon {vcon_uuid} due to sampling") |
| 82 | + return vcon_uuid |
| 83 | + |
| 84 | + client = OpenAI(api_key=opts["OPENAI_API_KEY"], timeout=120.0, max_retries=0) |
| 85 | + source_type = navigate_dict(opts, "source.analysis_type") |
| 86 | + text_location = navigate_dict(opts, "source.text_location") |
| 87 | + |
| 88 | + for index, dialog in enumerate(vCon.dialog): |
| 89 | + source = get_analysis_for_type(vCon, index, source_type) |
| 90 | + if not source: |
| 91 | + logger.warning("No %s found for vCon: %s", source_type, vCon.uuid) |
| 92 | + continue |
| 93 | + source_text = navigate_dict(source, text_location) |
| 94 | + if not source_text: |
| 95 | + logger.warning("No source_text found at %s for vCon: %s", text_location, vCon.uuid) |
| 96 | + continue |
| 97 | + analysis = get_analysis_for_type(vCon, index, opts["analysis_type"]) |
| 98 | + |
| 99 | + # See if it already has the analysis |
| 100 | + if analysis: |
| 101 | + logger.info( |
| 102 | + "Dialog %s already has a %s in vCon: %s", |
| 103 | + index, |
| 104 | + opts["analysis_type"], |
| 105 | + vCon.uuid, |
| 106 | + ) |
| 107 | + continue |
| 108 | + |
| 109 | + logger.info( |
| 110 | + "Analysing dialog %s with options: %s", |
| 111 | + index, |
| 112 | + {k: v for k, v in opts.items() if k != "OPENAI_API_KEY"}, |
| 113 | + ) |
| 114 | + start = time.time() |
| 115 | + try: |
| 116 | + # Get the structured analysis with labels |
| 117 | + analysis_json_str = generate_analysis_with_labels( |
| 118 | + transcript=source_text, |
| 119 | + prompt=opts["prompt"], |
| 120 | + model=opts["model"], |
| 121 | + temperature=opts["temperature"], |
| 122 | + client=client, |
| 123 | + response_format=opts.get("response_format", {"type": "json_object"}) |
| 124 | + ) |
| 125 | + |
| 126 | + # Parse the response to get labels |
| 127 | + try: |
| 128 | + analysis_data = json.loads(analysis_json_str) |
| 129 | + labels = analysis_data.get("labels", []) |
| 130 | + |
| 131 | + # Add the structured analysis to the vCon |
| 132 | + vendor_schema = {} |
| 133 | + vendor_schema["model"] = opts["model"] |
| 134 | + vendor_schema["prompt"] = opts["prompt"] |
| 135 | + vCon.add_analysis( |
| 136 | + type=opts["analysis_type"], |
| 137 | + dialog=index, |
| 138 | + vendor="openai", |
| 139 | + body=analysis_json_str, |
| 140 | + encoding="json", |
| 141 | + extra={ |
| 142 | + "vendor_schema": vendor_schema, |
| 143 | + }, |
| 144 | + ) |
| 145 | + |
| 146 | + # Apply each label as a tag |
| 147 | + for label in labels: |
| 148 | + vCon.add_tag(tag_name=label, tag_value=label) |
| 149 | + logger.info(f"Applied label as tag: {label}") |
| 150 | + |
| 151 | + stats_gauge( |
| 152 | + "conserver.link.openai.labels_added", |
| 153 | + len(labels), |
| 154 | + tags=[f"analysis_type:{opts['analysis_type']}"], |
| 155 | + ) |
| 156 | + |
| 157 | + except json.JSONDecodeError as e: |
| 158 | + logger.error(f"Failed to parse JSON response for vCon {vcon_uuid}: {e}") |
| 159 | + stats_count( |
| 160 | + "conserver.link.openai.json_parse_failures", |
| 161 | + tags=[f"analysis_type:{opts['analysis_type']}"], |
| 162 | + ) |
| 163 | + # Add the raw text anyway as the analysis |
| 164 | + vCon.add_analysis( |
| 165 | + type=opts["analysis_type"], |
| 166 | + dialog=index, |
| 167 | + vendor="openai", |
| 168 | + body=analysis_json_str, |
| 169 | + encoding="none", |
| 170 | + extra={ |
| 171 | + "vendor_schema": { |
| 172 | + "model": opts["model"], |
| 173 | + "prompt": opts["prompt"], |
| 174 | + "parse_error": str(e) |
| 175 | + }, |
| 176 | + }, |
| 177 | + ) |
| 178 | + |
| 179 | + except Exception as e: |
| 180 | + logger.error( |
| 181 | + "Failed to generate analysis for vCon %s after multiple retries: %s", |
| 182 | + vcon_uuid, |
| 183 | + e, |
| 184 | + ) |
| 185 | + stats_count( |
| 186 | + "conserver.link.openai.analysis_failures", |
| 187 | + tags=[f"analysis_type:{opts['analysis_type']}"], |
| 188 | + ) |
| 189 | + raise e |
| 190 | + |
| 191 | + stats_gauge( |
| 192 | + "conserver.link.openai.analysis_time", |
| 193 | + time.time() - start, |
| 194 | + tags=[f"analysis_type:{opts['analysis_type']}"], |
| 195 | + ) |
| 196 | + |
| 197 | + vcon_redis.store_vcon(vCon) |
| 198 | + logger.info(f"Finished analyze_and_label - {module_name}:{link_name} plugin for: {vcon_uuid}") |
| 199 | + |
| 200 | + return vcon_uuid |
| 201 | + |
| 202 | + |
| 203 | +def navigate_dict(dictionary, path): |
| 204 | + keys = path.split(".") |
| 205 | + current = dictionary |
| 206 | + for key in keys: |
| 207 | + if key in current: |
| 208 | + current = current[key] |
| 209 | + else: |
| 210 | + return None |
| 211 | + return current |
0 commit comments