code: """The lambda function for the Bolt app."""
  import json
  import logging
  import os
  import re
  import time
  from typing import Any
  
  import lancedb
  import slack_bolt
  from langchain.chains.conversational_retrieval.base import ConversationalRetrievalChain
  from langchain.memory.buffer import ConversationBufferMemory
  from langchain_community.chat_message_histories import DynamoDBChatMessageHistory
  from langchain_community.chat_models import ChatOpenAI
  from langchain_community.vectorstores.lancedb import LanceDB
  from langchain_core.callbacks.base import BaseCallbackHandler
  from langchain_core.outputs.llm_result import LLMResult
  from langchain_openai.embeddings import OpenAIEmbeddings
  from slack_bolt import Ack, BoltContext, Say
  from slack_bolt.adapter.aws_lambda import SlackRequestHandler
  from slack_sdk.models.blocks import (
      ContextBlock,
      DividerBlock,
      MarkdownTextObject,
      SectionBlock,
  )
  
  INITIAL_CHAT_UPDATE_INTERVAL_SEC = 1
  
  SlackRequestHandler.clear_all_log_handlers()
  logging.basicConfig(
      format="%(levelname)s %(message)s",
      level=logging.INFO,
  )
  logger = logging.getLogger(__name__)
  
  
  def initialize_conversation_memory(id_ts: str) -> ConversationBufferMemory:
      """Initialize the conversation memory.
  
      Parameters
      ----------
      id_ts: str
          The ID timestamp.
  
      Returns
      -------
      ConversationBufferMemory
          The initialized conversation memory.
      """
      history = DynamoDBChatMessageHistory(
          table_name=os.environ["CHAT_HISTORY_TABLE"],
          session_id=id_ts,
      )
      return ConversationBufferMemory(
          chat_memory=history,
          memory_key="chat_history",
          return_messages=True,
      )
  
  
  def initialize_vector_store() -> LanceDB:
      """Initialize the vector store.
  
      Returns
      -------
      LanceDB
          The initialized vector store.
      """
      db = lancedb.connect(os.environ["LANCEDB_DB"])
      table = db.open_table(os.environ["LANCEDB_TABLE"])
      embeddings = OpenAIEmbeddings()
      return LanceDB(
          table,
          embeddings,
      )
  
  
  app = slack_bolt.App(
      signing_secret=os.environ["SLACK_SIGNING_SECRET"],
      token=os.environ["SLACK_BOT_TOKEN"],
      process_before_response=True,
  )
  
  
  class SlackStreamingCallbackHandler(BaseCallbackHandler):
      """Handles callbacks for Slack streaming."""
  
      last_send_time = time.time()
      message = ""
  
      def __init__(self: "SlackStreamingCallbackHandler", channel: str, ts: str) -> None:
          """Initialize the SlackStreamingCallbackHandler.
  
          Parameters
          ----------
          channel : str
              The channel to send updates to.
          ts : str
              The timestamp of the message to update.
  
          Returns
          -------
          None
              This is a constructor method and does not return anything.
          """
          self.channel = channel
          self.ts = ts
          self.interval = INITIAL_CHAT_UPDATE_INTERVAL_SEC
          self.update_count = 0
  
      def on_llm_new_token(
          self: "SlackStreamingCallbackHandler",
          token: str,
          **kwargs: Any,  # noqa: ARG002
      ) -> None:
          """Handle the new token received during the LLM process.
  
          Parameters
          ----------
          token : str
              The new token received.
          kwargs : Any
              Additional keyword arguments.
  
          Returns
          -------
          None
              Nothing to return.
          """
          self.message += token
  
          now = time.time()
          if now - self.last_send_time > self.interval:
              app.client.chat_update(
                  channel=self.channel,
                  ts=self.ts,
                  text=f"{self.message}\n\nTyping...",
              )
              self.last_send_time = now
              self.update_count += 1
  
              if self.update_count / 10 > self.interval:
                  self.interval = self.interval * 2
  
      def on_llm_end(
          self: "SlackStreamingCallbackHandler",
          response: LLMResult,  # noqa: ARG002
          **kwargs: Any,  # noqa: ARG002
      ) -> None:
          """Handle the end of the LLM process.
  
          This method is called when the LLM process is completed.
  
          Parameters
          ----------
          response : LLMResult
              The response of the LLM process.
          kwargs : Any
              Additional keyword arguments.
  
          Returns
          -------
          None
              This method does not return anything.
          """
          message_context = f"Generated by {os.environ['OPENAI_API_MODEL']}"
          message_blocks = [
              SectionBlock(text=MarkdownTextObject(text=self.message)),
              DividerBlock(),
              ContextBlock(elements=[MarkdownTextObject(text=message_context)]),
          ]
  
          app.client.chat_update(
              channel=self.channel,
              ts=self.ts,
              text=self.message,
              blocks=message_blocks,
          )
  
  
  def handle_mention(event: dict, say: Say) -> None:
      """Handle the mention event.
  
      Parameters
      ----------
      event : dict
          The mention event.
      say : Say
          The say function.
  
      Returns
      -------
      None
          This function does not return anything.
      """
      channel = event["channel"]
      thread_ts = event["ts"]
      message = re.sub(r"<@.*>", "", event["text"]).strip()
  
      id_ts = event["ts"]
      if "thread_ts" in event:
          id_ts = event["thread_ts"]
  
      result = say("\n\nTyping...", thread_ts=thread_ts)
      ts = result["ts"]
  
      memory = initialize_conversation_memory(id_ts)
      vector_store = initialize_vector_store()
  
      slack_callback = SlackStreamingCallbackHandler(channel, ts)
  
      llm = ChatOpenAI(
          model=os.environ["OPENAI_API_MODEL"],
          temperature=float(os.environ["OPENAI_API_TEMPERATURE"]),
          streaming=True,
          callbacks=[slack_callback],
      )
  
      condense_question_llm = ChatOpenAI(
          model=os.environ["OPENAI_API_MODEL"],
          temperature=float(os.environ["OPENAI_API_TEMPERATURE"]),
      )
  
      cr_chain = ConversationalRetrievalChain.from_llm(
          llm=llm,
          retriever=vector_store.as_retriever(),
          memory=memory,
          condense_question_llm=condense_question_llm,
      )
  
      cr_chain.run(message)
  
  
  def just_ack(ack: Ack) -> None:
      """Just acknowledge the request.
  
      Parameters
      ----------
      ack : Ack
          The acknowledgement function.
  
      Returns
      -------
      None
          This function does not return anything.
      """
      ack()
  
  
  app.event("app_mintion")(
      ack=just_ack,
      lazy=[handle_mention],
  )
  
  
  def lambda_handler(event: dict, context: BoltContext) -> dict:
      """Handle the Lambda function.
  
      Parameters
      ----------
      event : dict
          The event dictionary.
      context : BoltContext
          The Bolt context.
  
      Returns
      -------
      dict
          The response dictionary.
      """
      headers = event["headers"]
      logger.info(json.dumps(headers))
  
      if "x-slack-retry-num" in headers:
          logger.info("SKIP > %s", headers["x-slack-retry-num"])
          return {"statusCode": 200, "body": json.dumps({"message": "ok"})}
  
      slack_handler = SlackRequestHandler(app=app)
      return slack_handler.handle(event, context)
  
apis: lancedb.connect
extract_api: [((946, 990), 'slack_bolt.adapter.aws_lambda.SlackRequestHandler.clear_all_log_handlers', 'SlackRequestHandler.clear_all_log_handlers', ([], {}), '()\n', (988, 990), False, 'from slack_bolt.adapter.aws_lambda import SlackRequestHandler\n'), ((991, 1066), 'logging.basicConfig', 'logging.basicConfig', ([], {'format': '"""%(levelname)s %(message)s"""', 'level': 'logging.INFO'}), "(format='%(levelname)s %(message)s', level=logging.INFO)\n", (1010, 1066), False, 'import logging\n'), ((1087, 1114), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (1104, 1114), False, 'import logging\n'), ((2053, 2190), 'slack_bolt.App', 'slack_bolt.App', ([], {'signing_secret': "os.environ['SLACK_SIGNING_SECRET']", 'token': "os.environ['SLACK_BOT_TOKEN']", 'process_before_response': '(True)'}), "(signing_secret=os.environ['SLACK_SIGNING_SECRET'], token=os.\n    environ['SLACK_BOT_TOKEN'], process_before_response=True)\n", (2067, 2190), False, 'import slack_bolt\n'), ((1429, 1522), 'langchain_community.chat_message_histories.DynamoDBChatMessageHistory', 'DynamoDBChatMessageHistory', ([], {'table_name': "os.environ['CHAT_HISTORY_TABLE']", 'session_id': 'id_ts'}), "(table_name=os.environ['CHAT_HISTORY_TABLE'],\n    session_id=id_ts)\n", (1455, 1522), False, 'from langchain_community.chat_message_histories import DynamoDBChatMessageHistory\n'), ((1553, 1651), 'langchain.memory.buffer.ConversationBufferMemory', 'ConversationBufferMemory', ([], {'chat_memory': 'history', 'memory_key': '"""chat_history"""', 'return_messages': '(True)'}), "(chat_memory=history, memory_key='chat_history',\n    return_messages=True)\n", (1577, 1651), False, 'from langchain.memory.buffer import ConversationBufferMemory\n'), ((1851, 1892), 'lancedb.connect', 'lancedb.connect', (["os.environ['LANCEDB_DB']"], {}), "(os.environ['LANCEDB_DB'])\n", (1866, 1892), False, 'import lancedb\n'), ((1965, 1983), 'langchain_openai.embeddings.OpenAIEmbeddings', 'OpenAIEmbeddings', ([], {}), '()\n', (1981, 1983), False, 'from langchain_openai.embeddings import OpenAIEmbeddings\n'), ((1995, 2021), 'langchain_community.vectorstores.lancedb.LanceDB', 'LanceDB', (['table', 'embeddings'], {}), '(table, embeddings)\n', (2002, 2021), False, 'from langchain_community.vectorstores.lancedb import LanceDB\n'), ((2332, 2343), 'time.time', 'time.time', ([], {}), '()\n', (2341, 2343), False, 'import time\n'), ((7110, 7138), 'slack_bolt.adapter.aws_lambda.SlackRequestHandler', 'SlackRequestHandler', ([], {'app': 'app'}), '(app=app)\n', (7129, 7138), False, 'from slack_bolt.adapter.aws_lambda import SlackRequestHandler\n'), ((3454, 3465), 'time.time', 'time.time', ([], {}), '()\n', (3463, 3465), False, 'import time\n'), ((6891, 6910), 'json.dumps', 'json.dumps', (['headers'], {}), '(headers)\n', (6901, 6910), False, 'import json\n'), ((4615, 4629), 'slack_sdk.models.blocks.DividerBlock', 'DividerBlock', ([], {}), '()\n', (4627, 4629), False, 'from slack_sdk.models.blocks import ContextBlock, DividerBlock, MarkdownTextObject, SectionBlock\n'), ((5251, 5285), 're.sub', 're.sub', (['"""<@.*>"""', '""""""', "event['text']"], {}), "('<@.*>', '', event['text'])\n", (5257, 5285), False, 'import re\n'), ((7058, 7087), 'json.dumps', 'json.dumps', (["{'message': 'ok'}"], {}), "({'message': 'ok'})\n", (7068, 7087), False, 'import json\n'), ((4563, 4600), 'slack_sdk.models.blocks.MarkdownTextObject', 'MarkdownTextObject', ([], {'text': 'self.message'}), '(text=self.message)\n', (4581, 4600), False, 'from slack_sdk.models.blocks import ContextBlock, DividerBlock, MarkdownTextObject, SectionBlock\n'), ((4666, 4706), 'slack_sdk.models.blocks.MarkdownTextObject', 'MarkdownTextObject', ([], {'text': 'message_context'}), '(text=message_context)\n', (4684, 4706), False, 'from slack_sdk.models.blocks import ContextBlock, DividerBlock, MarkdownTextObject, SectionBlock\n')]