|
| 1 | +import asyncio |
| 2 | +import logging |
| 3 | +import sys |
| 4 | +from typing import Any, Optional |
| 5 | + |
| 6 | +from hamilton import base |
| 7 | +from hamilton.async_driver import AsyncDriver |
| 8 | +from haystack.components.builders.prompt_builder import PromptBuilder |
| 9 | +from langfuse.decorators import observe |
| 10 | + |
| 11 | +from src.core.pipeline import BasicPipeline |
| 12 | +from src.core.provider import LLMProvider |
| 13 | +from src.pipelines.common import clean_up_new_lines |
| 14 | +from src.utils import trace_cost |
| 15 | +from src.web.v1.services.ask import AskHistory |
| 16 | + |
| 17 | +logger = logging.getLogger("wren-ai-service") |
| 18 | + |
| 19 | + |
| 20 | +user_clarification_assistance_system_prompt = """ |
| 21 | +""" |
| 22 | + |
| 23 | +user_clarification_assistance_user_prompt_template = """ |
| 24 | +""" |
| 25 | + |
| 26 | + |
| 27 | +## Start of Pipeline |
| 28 | +@observe(capture_input=False) |
| 29 | +def prompt( |
| 30 | + query: str, |
| 31 | + db_schemas: list[str], |
| 32 | + language: str, |
| 33 | + histories: list[AskHistory], |
| 34 | + prompt_builder: PromptBuilder, |
| 35 | + custom_instruction: str, |
| 36 | +) -> dict: |
| 37 | + previous_query_summaries = ( |
| 38 | + [history.question for history in histories] if histories else [] |
| 39 | + ) |
| 40 | + query = "\n".join(previous_query_summaries) + "\n" + query |
| 41 | + |
| 42 | + _prompt = prompt_builder.run( |
| 43 | + query=query, |
| 44 | + db_schemas=db_schemas, |
| 45 | + language=language, |
| 46 | + custom_instruction=custom_instruction, |
| 47 | + ) |
| 48 | + return {"prompt": clean_up_new_lines(_prompt.get("prompt"))} |
| 49 | + |
| 50 | + |
| 51 | +@observe(as_type="generation", capture_input=False) |
| 52 | +@trace_cost |
| 53 | +async def user_clarification_assistance( |
| 54 | + prompt: dict, generator: Any, query_id: str, generator_name: str |
| 55 | +) -> dict: |
| 56 | + return await generator( |
| 57 | + prompt=prompt.get("prompt"), |
| 58 | + query_id=query_id, |
| 59 | + ), generator_name |
| 60 | + |
| 61 | + |
| 62 | +## End of Pipeline |
| 63 | + |
| 64 | + |
| 65 | +class UserClarificationAssistance(BasicPipeline): |
| 66 | + def __init__( |
| 67 | + self, |
| 68 | + llm_provider: LLMProvider, |
| 69 | + **kwargs, |
| 70 | + ): |
| 71 | + self._user_queues = {} |
| 72 | + self._components = { |
| 73 | + "generator": llm_provider.get_generator( |
| 74 | + system_prompt=user_clarification_assistance_system_prompt, |
| 75 | + streaming_callback=self._streaming_callback, |
| 76 | + ), |
| 77 | + "generator_name": llm_provider.get_model(), |
| 78 | + "prompt_builder": PromptBuilder( |
| 79 | + template=user_clarification_assistance_user_prompt_template |
| 80 | + ), |
| 81 | + } |
| 82 | + |
| 83 | + super().__init__( |
| 84 | + AsyncDriver({}, sys.modules[__name__], result_builder=base.DictResult()) |
| 85 | + ) |
| 86 | + |
| 87 | + def _streaming_callback(self, chunk, query_id): |
| 88 | + if query_id not in self._user_queues: |
| 89 | + self._user_queues[ |
| 90 | + query_id |
| 91 | + ] = asyncio.Queue() # Create a new queue for the user if it doesn't exist |
| 92 | + # Put the chunk content into the user's queue |
| 93 | + asyncio.create_task(self._user_queues[query_id].put(chunk.content)) |
| 94 | + if chunk.meta.get("finish_reason"): |
| 95 | + asyncio.create_task(self._user_queues[query_id].put("<DONE>")) |
| 96 | + |
| 97 | + async def get_streaming_results(self, query_id): |
| 98 | + async def _get_streaming_results(query_id): |
| 99 | + return await self._user_queues[query_id].get() |
| 100 | + |
| 101 | + if query_id not in self._user_queues: |
| 102 | + self._user_queues[ |
| 103 | + query_id |
| 104 | + ] = asyncio.Queue() # Ensure the user's queue exists |
| 105 | + while True: |
| 106 | + try: |
| 107 | + # Wait for an item from the user's queue |
| 108 | + self._streaming_results = await asyncio.wait_for( |
| 109 | + _get_streaming_results(query_id), timeout=120 |
| 110 | + ) |
| 111 | + if ( |
| 112 | + self._streaming_results == "<DONE>" |
| 113 | + ): # Check for end-of-stream signal |
| 114 | + del self._user_queues[query_id] |
| 115 | + break |
| 116 | + if self._streaming_results: # Check if there are results to yield |
| 117 | + yield self._streaming_results |
| 118 | + self._streaming_results = "" # Clear after yielding |
| 119 | + except TimeoutError: |
| 120 | + break |
| 121 | + |
| 122 | + @observe(name="User Clarification Assistance") |
| 123 | + async def run( |
| 124 | + self, |
| 125 | + query: str, |
| 126 | + db_schemas: list[str], |
| 127 | + language: str, |
| 128 | + query_id: Optional[str] = None, |
| 129 | + histories: Optional[list[AskHistory]] = None, |
| 130 | + custom_instruction: Optional[str] = None, |
| 131 | + ): |
| 132 | + logger.info("User Clarification Assistance pipeline is running...") |
| 133 | + return await self._pipe.execute( |
| 134 | + ["user_clarification_assistance"], |
| 135 | + inputs={ |
| 136 | + "query": query, |
| 137 | + "db_schemas": db_schemas, |
| 138 | + "language": language, |
| 139 | + "query_id": query_id or "", |
| 140 | + "histories": histories or [], |
| 141 | + "custom_instruction": custom_instruction or "", |
| 142 | + **self._components, |
| 143 | + }, |
| 144 | + ) |
0 commit comments