File size: 5,693 Bytes
3484e05
 
 
 
 
d946da4
3484e05
 
 
 
 
9dffb9c
 
 
 
 
 
3484e05
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0cc0e0f
3484e05
7423671
3484e05
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fc55946
 
3484e05
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0a25259
3484e05
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8bd1b8f
3484e05
cb897de
3484e05
 
 
 
 
a863d90
 
 
 
 
 
3484e05
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
25bde0e
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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
import argparse
import logging
from pathlib import Path
from threading import Thread
from typing import List
import os
import gradio as gr

logger = logging.getLogger(__name__)


open_api_key = os.getenv("COMET_API_KEY")
open_api_key = os.getenv("COMET_WORKSPACE")
open_api_key = os.getenv("COMET_PROJECT_NAME")
open_api_key = os.getenv("QDRANT_URL")
open_api_key = os.getenv("QDRANT_API_KEY")

def parseargs() -> argparse.Namespace:
    """
    Parses command line arguments for the Financial Assistant Bot.

    Returns:
        argparse.Namespace: An object containing the parsed arguments.
    """

    parser = argparse.ArgumentParser(description="Financial Assistant Bot")

    parser.add_argument(
        "--env-file-path",
        type=str,
        default=".env",
        help="Path to the environment file",
    )

    parser.add_argument(
        "--logging-config-path",
        type=str,
        default="logging.yaml",
        help="Path to the logging configuration file",
    )

    parser.add_argument(
        "--model-cache-dir",
        type=str,
        default="./model_cache",
        help="Path to the directory where the model cache will be stored",
    )

    parser.add_argument(
        "--embedding-model-device",
        type=str,
        default="cuda:0",
        help="Device to use for the embedding model (e.g. 'cpu', 'cuda:0', etc.)",
    )

    parser.add_argument(
        "--debug",
        action="store_true",
        default=False,
        help="Enable debug mode",
    )

    return parser.parse_args()


args = parseargs()


# === Load Bot ===


def load_bot(
#    env_file_path: str = ".env",
    logging_config_path: str = "logging.yaml",
    model_cache_dir: str = "./model_cache",
    embedding_model_device: str = "cuda:0",
    debug: bool = False,
):
    """
    Load the financial assistant bot in production or development mode based on the `debug` flag

    In DEV mode the embedding model runs on CPU and the fine-tuned LLM is mocked.
    Otherwise, the embedding model runs on GPU and the fine-tuned LLM is used.

    Args:
        env_file_path (str): Path to the environment file.
        logging_config_path (str): Path to the logging configuration file.
        model_cache_dir (str): Path to the directory where the model cache is stored.
        embedding_model_device (str): Device to use for the embedding model.
        debug (bool): Flag to indicate whether to run the bot in debug mode or not.

    Returns:
        FinancialBot: An instance of the FinancialBot class.
    """

    from financial_bot import initialize

    # Be sure to initialize the environment variables before importing any other modules.
    # initialize(logging_config_path=logging_config_path, env_file_path=env_file_path)
    initialize(logging_config_path=logging_config_path)

    from financial_bot import utils
    from financial_bot.langchain_bot import FinancialBot

    logger.info("#" * 100)
    utils.log_available_gpu_memory()
    utils.log_available_ram()
    logger.info("#" * 100)

    bot = FinancialBot(
        model_cache_dir=Path(model_cache_dir) if model_cache_dir else None,
        embedding_model_device=embedding_model_device,
        streaming=True,
        debug=debug,
    )

    return bot


bot = load_bot(
#    env_file_path=args.env_file_path,
    logging_config_path=args.logging_config_path,
    model_cache_dir=args.model_cache_dir,
    embedding_model_device=args.embedding_model_device,
    debug=args.debug,
)


# === Gradio Interface ===


def predict(message: str, history: List[List[str]], about_me: str) -> str:
    """
    Predicts a response to a given message using the financial_bot Gradio UI.

    Args:
        message (str): The message to generate a response for.
        history (List[List[str]]): A list of previous conversations.
        about_me (str): A string describing the user.

    Returns:
        str: The generated response.
    """

    generate_kwargs = {
        "about_me": about_me,
        "question": message,
        "to_load_history": history,
    }

    if bot.is_streaming:
        t = Thread(target=bot.answer, kwargs=generate_kwargs)
        t.start()

        for partial_answer in bot.stream_answer():
            yield partial_answer
    else:
        yield bot.answer(**generate_kwargs)


demo = gr.ChatInterface(
    predict,
    textbox=gr.Textbox(
        placeholder="Ask me a financial question",
        label="Financial question",
        container=False,
        scale=7,
    ),
    additional_inputs=[
        gr.Textbox(
            "I am a student and I have some money that I want to invest.",
            label="About me",
        )
    ],
    title="Your Personal Financial Assistant",
    description="Ask me any financial or crypto market questions, and I will do my best to answer them.",
    theme="soft",
    examples=[
        [
            "What's your opinion on investing in startup companies?",
            "I am a 30 year old graphic designer. I want to invest in something with potential for high returns.",
        ],
        [
            "What's your opinion on investing in AI-related companies?",
            "I'm a 25 year old entrepreneur interested in emerging technologies. \
             I'm willing to take calculated risks for potential high returns.",
        ],
        [
            "Do you think advancements in gene therapy are impacting biotech company valuations?",
            "I'm a 31 year old scientist. I'm curious about the potential of biotech investments.",
        ],
    ],
    cache_examples=False,
    retry_btn=None,
    undo_btn=None,
    clear_btn="Clear",
)


if __name__ == "__main__":
    demo.queue().launch()