|
| 1 | +import json |
| 2 | +import logging |
| 3 | + |
| 4 | +from redis_memory_server.models import ( |
| 5 | + AnthropicClientWrapper, |
| 6 | + MemoryMessage, |
| 7 | + OpenAIClientWrapper, |
| 8 | +) |
| 9 | + |
| 10 | + |
| 11 | +logger = logging.getLogger(__name__) |
| 12 | + |
| 13 | +EXTRACTION_PROMPT = """Analyze the following message and extract: |
| 14 | +1. Key topics (as single words or short phrases) |
| 15 | +2. Named entities (people, places, organizations, etc.) |
| 16 | +
|
| 17 | +Message: {message} |
| 18 | +
|
| 19 | +Respond in JSON format: |
| 20 | +{{ |
| 21 | + "topics": ["topic1", "topic2", ...], |
| 22 | + "entities": ["entity1", "entity2", ...] |
| 23 | +}} |
| 24 | +
|
| 25 | +Keep topics and entities concise and relevant.""" |
| 26 | + |
| 27 | + |
| 28 | +async def extract_topics_and_entities( |
| 29 | + message: str, |
| 30 | + model_client: OpenAIClientWrapper | AnthropicClientWrapper, |
| 31 | +) -> tuple[list[str], list[str]]: |
| 32 | + """ |
| 33 | + Extract topics and entities from a message using the LLM. |
| 34 | +
|
| 35 | + Args: |
| 36 | + message: The message to analyze |
| 37 | + model_client: The LLM client to use |
| 38 | +
|
| 39 | + Returns: |
| 40 | + Tuple of (topics, entities) lists |
| 41 | + """ |
| 42 | + try: |
| 43 | + # Get LLM response |
| 44 | + response = await model_client.create_chat_completion( |
| 45 | + "gpt-4o-mini", # TODO: Make configurable |
| 46 | + EXTRACTION_PROMPT.format(message=message), |
| 47 | + ) |
| 48 | + |
| 49 | + # Parse JSON response from content field |
| 50 | + content = response.choices[0]["message"]["content"].strip() |
| 51 | + result = json.loads(content) |
| 52 | + |
| 53 | + # Extract and validate topics and entities |
| 54 | + topics = result.get("topics", []) |
| 55 | + entities = result.get("entities", []) |
| 56 | + |
| 57 | + # Ensure we have lists |
| 58 | + if not isinstance(topics, list) or not isinstance(entities, list): |
| 59 | + logger.error("Invalid extraction response format") |
| 60 | + return [], [] |
| 61 | + |
| 62 | + return topics, entities |
| 63 | + |
| 64 | + except Exception as e: |
| 65 | + logger.error(f"Error in topic/entity extraction: {e}") |
| 66 | + return [], [] |
| 67 | + |
| 68 | + |
| 69 | +async def handle_extraction( |
| 70 | + message: MemoryMessage, |
| 71 | + model_client: OpenAIClientWrapper | AnthropicClientWrapper, |
| 72 | +) -> MemoryMessage: |
| 73 | + """ |
| 74 | + Handle topic and entity extraction for a message. |
| 75 | +
|
| 76 | + Args: |
| 77 | + message: The message to process |
| 78 | + model_client: The LLM client to use |
| 79 | +
|
| 80 | + Returns: |
| 81 | + Updated message with extracted topics and entities |
| 82 | + """ |
| 83 | + # Skip if message already has both topics and entities |
| 84 | + if message.topics and message.entities: |
| 85 | + return message |
| 86 | + |
| 87 | + # Extract topics and entities |
| 88 | + extracted_topics, extracted_entities = await extract_topics_and_entities( |
| 89 | + message.content, model_client |
| 90 | + ) |
| 91 | + |
| 92 | + # Merge with existing topics and entities |
| 93 | + message.topics = ( |
| 94 | + list(set(message.topics + extracted_topics)) |
| 95 | + if message.topics |
| 96 | + else extracted_topics |
| 97 | + ) |
| 98 | + message.entities = ( |
| 99 | + list(set(message.entities + extracted_entities)) |
| 100 | + if message.entities |
| 101 | + else extracted_entities |
| 102 | + ) |
| 103 | + |
| 104 | + return message |
0 commit comments