File size: 1,690 Bytes
561f679
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
import logging
import os
import random
from datetime import datetime
from functools import lru_cache
from typing import Sequence
from zoneinfo import ZoneInfo

import langsmith
from langchain_core.documents import Document
from langchain_community.document_transformers import LongContextReorder
from langchain.retrievers.document_compressors import FlashrankRerank

logging.basicConfig(level=logging.ERROR)


class DocumentFormatter:
    def __init__(self, prefix: str):
        self.prefix = prefix

    def __call__(self, docs: list[Document]) -> str:
        return "\n---\n".join(
            [
                f"- {self.prefix} {i+1}:\n\n\t" + d.page_content
                for i, d in enumerate(docs)
            ]
        )


def get_datetime() -> str:
    return datetime.now(ZoneInfo("America/Vancouver")).strftime("%A, %Y-%b-%d %H:%M:%S")


def reorder_documents(docs: list[Document]) -> Sequence[Document]:
    return LongContextReorder().transform_documents(docs)


def randomize_documents(documents: list[Document]) -> list[Document]:
    random.shuffle(documents)
    return documents


def create_langsmith_client():
    os.environ["LANGCHAIN_TRACING_V2"] = "true"
    os.environ["LANGCHAIN_PROJECT"] = "talltree-ai-assistant"
    os.environ["LANGCHAIN_ENDPOINT"] = "https://api.smith.langchain.com"
    langsmith_api_key = os.getenv("LANGCHAIN_API_KEY")
    if not langsmith_api_key:
        raise EnvironmentError("Missing environment variable: LANGCHAIN_API_KEY")
    return langsmith.Client()


@lru_cache(maxsize=1)
def get_reranker(
    top_n: int = 3, model: str = "ms-marco-MiniLM-L-12-v2"
) -> FlashrankRerank:
    return FlashrankRerank(top_n=top_n, model=model)