from datetime import datetime import streamlit as st from _base_class import StreamlitBaseClass, BaseClass from _llm import LLM from prompts import * from colorprinter.print_color import * from ollama._types import Message as OllamaMessage from projects_page import Project from ollama_response_classes import QueryResponse class Chat(StreamlitBaseClass): """ A class to represent a chat session in a Streamlit application. Attributes: ----------- name : str The name of the chat. chat_history : list A list to store the chat history. role : str The role of the user in the chat. project : str The project associated with the chat. collection : str The collection associated with the chat. _key : str The unique key for the chat. Methods: -------- add_message(role, content): Adds a message to the chat history. to_dict(): Converts the chat object to a dictionary. update_in_arango(): Updates the chat object in the ArangoDB. set_name(user_input): Sets the name of the chat based on user input. show_title(title=None): Displays the title of the chat in the Streamlit application. from_dict(data): Creates a Chat object from a dictionary. chat_history2bot(n_messages=None, remove_system=False): Converts the chat history to a format suitable for a bot. """ def __init__( self, username=None, role=None, key=None, project=None, collection=None, **kwargs, ): super().__init__(username=username, **kwargs) self.name = kwargs.get("name", None) self.chat_history = kwargs.get("chat_history", []) self.role = role self.project = kwargs.get("project") if "project" in kwargs else project self.collection = ( kwargs.get("collection") if "collection" in kwargs else collection ) self._key = key def add_message(self, role, content): if isinstance(content, str): content = content.strip().strip('"') elif isinstance(content, dict): content = content["content"].strip().strip('"') else: try: content = content.get("content", "").strip().strip('"') except: content = content self.chat_history.append( { "role": role, "content": content, "role_type": self.role, } ) def to_dict(self): return { "_key": self._key, "name": self.name, "chat_history": self.chat_history, "role": self.role, "username": self.username, } def update_in_arango(self): self.last_updated = datetime.now().isoformat() self.user_arango.db.collection("chats").insert( self.to_dict(), overwrite=True, overwrite_mode="update" ) def set_name(self, user_input): llm = LLM( model="small", max_length_answer=50, temperature=0.4, system_message="You are a chatbot who will be chatting with a user", ) prompt = ( f'Give a short name to the chat based on this user input: "{user_input}" ' "No more than 30 characters. Answer ONLY with the name of the chat." ) name = llm.generate(prompt).content.strip('"') name = f'{name} - {datetime.now().strftime("%B %d")}' existing_chat = self.user_arango.db.aql.execute( f'FOR doc IN chats FILTER doc.name == "{name}" RETURN doc', count=True ) if existing_chat.count() > 0: name = f'{name} ({datetime.now().strftime("%H:%M")})' name += f" - [{self.role}]" self.name = name return name def show_title(self, title=None): title = ( title if title else ( self.project if self.project else self.collection if self.collection else "No title" ) ) st.markdown( f"""### Chat about *{title.strip()}* with *{self.role}*""", ) @classmethod def from_dict(cls, data): return cls( username=data.get("username"), name=data.get("name"), chat_history=data.get("chat_history", []), role=data.get("role", "Research Assistant"), _key=data.get("_key"), ) def chat_history2bot(self, n_messages: int = None, remove_system: bool = False): history = [ {"role": m["role"], "content": m["content"]} for m in self.chat_history ] if n_messages and len(history) > n_messages: history = history[-n_messages:] if ( all([history[0]["role"] == "system", remove_system]) or history[0]["role"] == "assistant" ): history = history[1:] return history class StreamlitChat(Chat): ''' A class to manage chat interactions within a Streamlit application. Inherits from the Chat class and provides additional functionality to handle chat history, user roles, and avatars within a Streamlit app context. Attributes: project (str): The project associated with the chat. collection (str): The collection associated with the chat. message_attachments (None): Placeholder for message attachments. last_updated (str): Timestamp of the last update in ISO format. _key (str): Unique identifier for the chat. role (str): The role of the user in the chat. username (str): The username of the user in the chat. name (str): The name of the chat. chat_history (list): List of messages in the chat history. Methods: show_chat_history(): get_avatar(message: dict = None, role=None) -> str: ''' def __init__(self, username: str, role: str, _key: str = None, **kwargs): super().__init__(username, role, _key, **kwargs) self.project = kwargs.get("project", None) self.collection = kwargs.get("collection", None) self.message_attachments = None self.last_updated = datetime.now().isoformat() self._key = _key self.role = role if self._key: chat = self.user_arango.db.collection("chats").get(self._key) if chat: self.name = chat.get("name") self.chat_history = chat.get("chat_history", []) self.role = chat.get("role") self.username = chat.get("username") else: self._key = self.user_arango.db.collection("chats").insert( { "name": self.name, "chat_history": self.chat_history, "role": self.role, "username": self.username, } )["_key"] def show_chat_history(self): """ Displays the chat history in the Streamlit app. Iterates through the chat history and displays messages from the user and assistant. Messages from other roles are ignored. Each message is displayed with an avatar. Returns: None """ for message in self.chat_history: if message["role"] not in ["user", "assistant"]: continue avatar = self.get_avatar(message) with st.chat_message(message["role"], avatar=avatar): if message["content"]: st.markdown(message["content"].strip('"')) def get_avatar(self, message: dict = None, role=None) -> str: """ Retrieves the avatar image path based on the message or role provided. Args: message (dict, optional): A dictionary containing message details, including the role. role (str, optional): The role of the user if the message is not provided. Returns: str: The file path to the avatar image. Raises: AssertionError: If neither message nor role is provided. """ assert message or role, "Either message or role must be provided" if message and message.get("role", None) == "user" or role == "user": avatar = st.session_state["settings"].get("avatar", "user") elif ( message and message.get("role", None) == "assistant" or role == "assistant" ): role_type = message.get("role_type", self.role) if message else self.role if role_type == "Research Assistant": avatar = "img/avatar_researcher.png" elif role_type == "Editor": avatar = "img/avatar_editor.png" elif role_type == "Host": avatar = "img/avatar_host.png" elif role_type == "Guest": avatar = "img/avatar_guest.png" else: avatar = None else: avatar = None return avatar class Bot(BaseClass): ''' A chatbot class that integrates with research tools and document retrieval systems. The Bot class provides an interface for conversational AI that can access and process various document sources, including scientific articles, user notes, and other documents. It initializes multiple specialized language models for different tasks, including regular conversation, query generation, and tool selection. Attributes: username (str): The username associated with this bot instance. chat (Chat): Chat instance for managing conversation history. project (Project, optional): Associated project for document context. collection (list, optional): Collections of documents to search within. arango_ids (list): List of document IDs in ArangoDB. chatbot (LLM): Main language bot for conversation. helperbot (LLM): Bot for generating queries. toolbot (LLM): Bot for selecting appropriate tools. tools (list): List of tool functions available to the bot. Methods: initiate_bots(): Initialize the different language model instances. get_chunks(): Retrieve relevant text chunks based on user input. answer_tool_call(): Process and execute tool calls from the AI. generate_from_notes(): Generate a response from user notes. generate_from_chunks(): Generate a response from document chunks. run(): Run the bot (implemented by subclasses). get_notes(): Retrieve notes from the database. fetch_science_articles_tool(): Retrieve scientific articles. fetch_other_documents_tool(): Retrieve non-scientific documents. fetch_science_articles_and_other_documents_tool(): Retrieve both document types. fetch_notes_tool(): Retrieve user notes. conversational_response_tool(): Generate a simple conversational response. ''' def __init__(self, username: str, chat: Chat = None, tools: list = None, **kwargs): super().__init__(username=username, **kwargs) # Use the passed in chat or create a new Chat self.chat = chat if chat else Chat(username=username, role="Research Assistant") # Store or set up project/collection if available self.project: Project = kwargs.get("project", None) self.collection = kwargs.get("collection", None) if self.collection and not isinstance(self.collection, list): self.collection = [self.collection] elif self.project: self.collection = self.project.collections # Load articles in the collections self.arango_ids = [] # Bots to be initiated later self.chatbot = None self.helperbot = None self.toolbot = None if self.collection: for c in self.collection: for _id in self.user_arango.db.aql.execute( """ FOR doc IN article_collections FILTER doc.name == @collection FOR article IN doc.articles RETURN article._id """, bind_vars={"collection": c}, ): self.arango_ids.append(_id) # Convert tool names to function references if tools: # Map tool names to functions tool_mapping = { "fetch_other_documents_tool": self.fetch_other_documents_tool, "fetch_science_articles_tool": self.fetch_science_articles_tool, "fetch_science_articles_and_other_documents_tool": self.fetch_science_articles_and_other_documents_tool, "fetch_notes_tool": self.fetch_notes_tool, "conversational_response_tool": self.conversational_response_tool, } self.tools = [ tool_mapping[tool] if isinstance(tool, str) else tool for tool in tools ] else: self.tools = None self.initiate_bots() # Store other kwargs for arg in kwargs: setattr(self, arg, kwargs[arg]) # # Initiate the bots # try: # self.initiate_bots() # except Exception as e: # print_red(f"Error initiating bots: {e}") def initiate_bots(self): """ Initialize the different bot instances used in the chatbot application. Creates three types of bots: 1. chatbot: A standard LLM for normal conversation with the user 2. helperbot: A specialized LLM with low temperature for generating concise queries or prompts 3. toolbot: A specialized LLM for selecting which tool to use when responding to user queries (only created if tools are provided) The toolbot is configured to prefer specialized tools over conversational responses when the user is seeking information rather than engaging in small talk. Note: - The chatbot uses the full chat history - The helperbot uses a limited chat history (last 4 messages) with system message removed - The toolbot uses a system message that lists all available tools """ # A standard LLM for normal chat self.chatbot = LLM(messages=self.chat.chat_history2bot()) # A helper bot for generating queries or short prompts self.helperbot = LLM( temperature=0, model="small", max_length_answer=500, system_message=get_query_builder_system_message(), messages=self.chat.chat_history2bot(n_messages=4, remove_system=True), ) # A specialized LLM picking which tool to use if self.tools: tools_names = [tool.__name__ for tool in self.tools] tools_name_string = "\n– ".join(tools_names) self.toolbot = LLM( temperature=0, system_message=f""" You are an helpful assistant with tools. The tools you can choose from are: {tools_name_string} Your task is to choose one or multiple tools to answering a user's query. DON'T come up with your own tools, only use the ones provided. """, # system_message='Use one of the provided tools to help the answering bot to answer the user. Do not answer directly. Use the "tool_calls" field in your answer.', chat=False, model="tools", ) if len(tools_names) > 1 and "conversational_response_tool" in tools_names: self.toolbot.system_message += "\n\nMake sure to only use the conversational response tool if the user is engaging in small talk. If the user is asking a question or looking for information, make sure to use one of the other tools!" def get_chunks( self, user_input, collections=["sci_articles", "other_documents"], n_results=7, n_sources=4, filter=True, ): """ Retrieves relevant text chunks from the vector database based on user input. This method: 1. Generates a vector query based on user input using the helper bot 2. Searches multiple collections in the vector database 3. Combines results and sorts them by relevance 4. Limits results to the specified number of unique sources 5. Cleans the text by removing footnote references 6. Enriches the chunks with detailed metadata from ArangoDB 7. Groups chunks by article title Parameters: ----------- user_input : str The user query to search for relevant documents collections : list, optional List of collection names to search in (default: ["sci_articles", "other_documents"]) n_results : int, optional Maximum number of results to return (default: 7) n_sources : int, optional Maximum number of unique document sources to include (default: 4) filter : bool, optional Whether to filter results by ArangoDB IDs (default: True) Returns: -------- dict A dictionary of grouped chunks where: - Keys are article titles - Values are dictionaries containing: - 'article_number': A sequential number for the article - 'chunks': A list of chunk dictionaries, each containing: - 'document': The document text - 'metadata': The document metadata - 'distance': The similarity distance (lower is better) - 'article_number': The sequential number of the article """ response = self.helperbot.generate( get_generate_vector_query_prompt(user_input, self.chat.role), format=QueryResponse.model_json_schema(), ) print(response) print_yellow("RESPONSE:", response.content) query_response = QueryResponse.model_validate_json(response.content) query = query_response.query_to_vector_database print_purple(f"Query for vector DB:\n {query}") combined_chunks = [] if collections: for collection in collections: if filter: where_filter = {"_id": {"$in": self.arango_ids}} chunks = self.get_chromadb().query( query=query, collection=collection, n_results=n_results, n_sources=n_sources, where=where_filter, max_retries=3, ) for doc, meta, dist in zip( chunks["documents"][0], chunks["metadatas"][0], chunks["distances"][0], ): combined_chunks.append( {"document": doc, "metadata": meta, "distance": dist} ) combined_chunks.sort(key=lambda x: x["distance"]) # Keep the best chunks according to n_sources sources = set() closest_chunks = [] for chunk in combined_chunks: source_id = chunk["metadata"].get("_id", "no_id") if source_id not in sources: sources.add(source_id) closest_chunks.append(chunk) if len(sources) >= n_sources: break if len(closest_chunks) < n_results: remaining_chunks = [c for c in combined_chunks if c not in closest_chunks] closest_chunks.extend(remaining_chunks[: n_results - len(closest_chunks)]) # Remove footnoot references like [\d+] from the text chunks for chunk in closest_chunks: chunk["document"] = re.sub(r"\[\d+\]", "", chunk["document"]) # Fetch real metadata from Arango for chunk in closest_chunks: _id = chunk["metadata"].get("_id") if not _id: continue if _id.startswith("sci_articles"): arango_doc = self.base_arango.db.document(_id) else: arango_doc = self.user_arango.db.document(_id) if arango_doc: arango_metadata = arango_doc.get("metadata", {}) # Possibly merge notes if "user_notes" in arango_doc: arango_metadata["user_notes"] = arango_doc["user_notes"] chunk["metadata"] = arango_metadata # Group by article title grouped_chunks = {} article_number = 1 for chunk in closest_chunks: title = chunk["metadata"].get("title", "No title") chunk["article_number"] = article_number if title not in grouped_chunks: grouped_chunks[title] = { "article_number": article_number, "chunks": [], } article_number += 1 grouped_chunks[title]["chunks"].append(chunk) return grouped_chunks def answer_tool_call(self, response, user_input): """ Process tool calls returned by the AI and execute the corresponding functions. This method evaluates tool calls in the AI response, executes the appropriate functions with the provided arguments, and collects the resulting responses. Parameters: ----------- response : dict The AI response containing potential tool_calls to be executed user_input : str The original user query that will be passed to tool functions Returns: -------- list A list of string responses generated from executing the tool calls. Returns an empty string if no tool calls are present. Notes: ------ Supported tool functions include: - fetch_other_documents_tool: Retrieves non-scientific documents - fetch_science_articles_tool: Retrieves scientific articles - fetch_science_articles_and_other_documents_tool: Retrieves both types of documents - fetch_notes_tool: Retrieves user notes - conversational_response_tool: Generates a conversational response """ bot_responses = [] # This method returns / stores responses (no Streamlit calls) if not response.get("tool_calls"): return "" for tool in response.get("tool_calls"): function_name = tool.function.get("name") arguments = tool.function.arguments arguments["query"] = user_input if hasattr(self, function_name): print_purple("Function name:", function_name) if function_name in [ "fetch_other_documents_tool", "fetch_science_articles_tool", "fetch_science_articles_and_other_documents_tool", ]: chunks = getattr(self, function_name)(**arguments) bot_responses.append(self.generate_from_chunks(user_input, chunks)) elif function_name == "fetch_notes_tool": notes = getattr(self, function_name)() bot_responses.append(self.generate_from_notes(user_input, notes)) elif function_name == "conversational_response_tool": response: OllamaMessage = getattr(self, function_name)(user_input) print_green("Conversation response:", response) bot_responses.append(response.content.strip('"')) return bot_responses # def process_user_input(self, user_input, content_attachment=None): # # Add user message # self.chat.add_message("user", user_input) # print('content_attachment', content_attachment) # if not content_attachment: # prompt = get_tools_prompt(user_input) # print('TOOLS PROMOT:', prompt) # print_red('\nToolbot system message:', self.toolbot.system_message) # response = self.toolbot.generate(prompt, tools=self.tools, stream=False) # print_rainbow(response) # if response.get("tool_calls"): # bot_response = self.answer_tool_call(response, user_input) # else: # # Just respond directly # bot_response = response.content.strip('"') # else: # # If there's an attachment, do something minimal # bot_response = "Content attachment received (Base Bot)." # # Add assistant message # if self.chat.chat_history[-1]["role"] != "assistant": # self.chat.add_message("assistant", bot_response) # # Update in Arango # self.chat.update_in_arango() # return bot_response def generate_from_notes(self, user_input, notes): """ Generate a response based on user input and a collection of notes. This method takes a user query and relevant notes, formats the notes into a string, creates a prompt with the formatted notes and user input, and generates a streamed response. Parameters ---------- user_input : str The user's query or message to respond to notes : list of dict A list of note dictionaries, where each note has 'title' and 'content' keys Returns ------- generator A generator that streams the AI-generated response Notes ----- This method does not make any Streamlit calls and is safe to use outside of the Streamlit context. The notes are formatted with titles and content separated by horizontal rules. """ # No Streamlit calls notes_string = "" for note in notes: notes_string += ( f"\n# {note.get('title','No title')}\n{note.get('content','')}\n---\n" ) prompt = get_chat_prompt( user_input, content_string=notes_string, role=self.chat.role ) return self.chatbot.generate(prompt, stream=True) def generate_from_chunks(self, user_input, chunks): """ Generate a response based on user input and retrieved document chunks. This method formats the retrieved document chunks into a structured string, combines it with the user's input in a prompt, and generates a streaming response using the chatbot. Parameters: ----------- user_input : str The user's query or message to respond to. chunks : dict A dictionary containing document chunks organized by title. Expected structure: { "title1": { "chunks": [ { "document": "content...", "metadata": { "user_notes": "optional notes..." } }, ... ], "article_number": int }, ... } Returns: -------- generator A streaming generator of the chatbot's response. Notes: ------ - This method does not make any Streamlit API calls. - User notes are included in the formatted content if available. - The formatted content includes titles, article numbers, and document text. """ # No Streamlit calls chunks_string = "" for title, group in chunks.items(): user_notes_string = "" if "user_notes" in group["chunks"][0]["metadata"]: notes = group["chunks"][0]["metadata"]["user_notes"] user_notes_string = f'\n\nUser notes:\n"""\n{notes}\n"""\n\n' docs = "\n(...)\n".join([c["document"] for c in group["chunks"]]) chunks_string += f"\n# {title}\n## Article #{group['article_number']}\n{user_notes_string}{docs}\n---\n" prompt = get_chat_prompt( user_input, content_string=chunks_string, role=self.chat.role ) return self.chatbot.generate(prompt, stream=True) def run(self): # Base Bot has no Streamlit run loop pass def get_notes(self): # Minimal note retrieval notes = self.user_arango.db.aql.execute( f'FOR doc IN notes FILTER doc.project == "{self.project.name if self.project else ""}" RETURN doc' ) return list(notes) def fetch_science_articles_tool(self, query: str, n_documents: int = 6): """ "Fetches information from scientific articles. Use this tool when the user is looking for information from scientific articles." Parameters: query (str): The search query to find relevant scientific articles. n_documents (int): How many documents to fetch. A complex query may require more documents. Min: 3, Max: 10. Returns: list: A list of chunks containing information from the fetched scientific articles. """ print_purple("Query:", query) n_documents = int(n_documents) if n_documents < 3: n_documents = 3 elif n_documents > 10: n_documents = 10 return self.get_chunks( query, collections=["sci_articles"], n_results=n_documents ) def fetch_other_documents_tool(self, query: str, n_documents: int = 6): """ Fetches information from other documents based on the user's query. This method retrieves information from various types of documents such as reports, news articles, and other texts. It should be used only when it is clear that the user is not seeking scientific articles. Args: query (str): The search query provided by the user. n_documents (int): How many documents to fetch. A complex query may require more documents. Min: 2, Max: 10. Returns: list: A list of document chunks that match the query. """ assert isinstance(self, Bot), "The first argument must be a Bot object." n_documents = int(n_documents) if n_documents < 2: n_documents = 2 elif n_documents > 10: n_documents = 10 return self.get_chunks( query, collections=[f"{self.username}__other_documents"], n_results=n_documents, ) def fetch_science_articles_and_other_documents_tool( self, query: str, n_documents: int ): """ Fetches information from both scientific articles and other documents. This method is often used when the user hasn't specified what kind of sources they are interested in. Args: query (str): The search query to fetch information for. n_documents (int): How many documents to fetch. A complex query may require more documents. Min: 3, Max: 10. Returns: list: A list of document chunks that match the search query. """ assert isinstance(self, Bot), "The first argument must be a Bot object." n_documents = int(n_documents) if n_documents < 3: n_documents = 3 elif n_documents > 10: n_documents = 10 return self.get_chunks( query, collections=["sci_articles", f"{self.username}__other_documents"], n_results=n_documents, ) def fetch_notes_tool(bot): """ Fetches information from the project notes when you as an editor need context from the project notes to understand other information. ONLY use this together with other tools! No arguments needed. Returns: list: A list of notes. """ assert isinstance(bot, Bot), "The first argument must be a Bot object." return bot.get_notes() def conversational_response_tool(self, query: str): """ Generate a conversational response to a user's query. This method is designed to provide a short and conversational response without fetching additional data. It should be used ONLY when it is clear that the user is engaging in small talk (like saying 'hi'). Args: query (str): The user's message to which the bot should respond. Returns: str: The generated conversational response. """ query = f""" User message: "{query}". Make your answer short and conversational. Don't answer with anything you're not sure of! """ return self.chatbot.generate(query, stream=False) class StreamlitBot(Bot): def __init__( self, username: str, chat: StreamlitChat = None, tools: list = None, **kwargs ): super().__init__(username=username, chat=chat, tools=tools, **kwargs) # For Streamlit, we can override or add attributes if "llm_chosen_backend" not in st.session_state: st.session_state["llm_chosen_backend"] = None self.chatbot.chosen_backend = st.session_state["llm_chosen_backend"] if not st.session_state["llm_chosen_backend"]: st.session_state["llm_chosen_backend"] = self.chatbot.chosen_backend settings = self.get_settings() if settings.get("use_reasoning_model", False): self.chatbot.model = self.chatbot.get_model("reasoning") print_rainbow(settings) print('MODEL', self.chatbot.model) def run(self): # Example Streamlit run loop title = ( self.project.name if self.project else self.collection.name if self.collection else None ) self.chat.show_title(title=title) self.chat.show_chat_history() if user_input := st.chat_input("Write your message here...", accept_file=True): text_input = user_input.text.replace('"""', "---") if len(user_input.files) > 1: st.error("Please upload only one file at a time.") return attached_file = user_input.files[0] if user_input.files else None content_attachment = None if attached_file: if attached_file.type == "application/pdf": import fitz pdf_document = fitz.open( stream=attached_file.read(), filetype="pdf" ) pdf_text = "" for page_num in range(len(pdf_document)): page = pdf_document.load_page(page_num) pdf_text += page.get_text() content_attachment = pdf_text elif attached_file.type in ["image/png", "image/jpeg"]: self.chat.message_attachments = "image" content_attachment = attached_file.read() with st.chat_message( "user", avatar=self.chat.get_avatar(role="user") ): st.image(content_attachment) with st.chat_message("user", avatar=self.chat.get_avatar(role="user")): st.write(text_input) if not self.chat.name: self.chat.set_name(text_input) self.chat.last_updated = datetime.now().isoformat() self.chat.saved = False self.user_arango.db.collection("chats").insert( self.chat.to_dict(), overwrite=True, overwrite_mode="update" ) self.process_user_input(text_input, content_attachment) def get_settings(self): return self.user_arango.db.document("settings/settings") def process_user_input(self, user_input, content_attachment=None): # We override to show messages in Streamlit instead of just storing self.chat.add_message("user", user_input) # Remove conversational response tool if there are more than 2 messages if len(self.chat.chat_history) > 2 and len(self.tools) > 1: for tool in self.tools: if tool.__name__ == "conversational_response_tool": self.tools.remove(tool) break if not content_attachment: prompt = get_tools_prompt(user_input) response = self.toolbot.generate(prompt, tools=self.tools, stream=False) if response.get("tool_calls"): bot_response = self.answer_tool_call(response, user_input) else: bot_response = response.content.strip('"') # with st.chat_message( # "assistant", avatar=self.chat.get_avatar(role="assistant") # ): # st.write(bot_response) else: with st.chat_message( "assistant", avatar=self.chat.get_avatar(role="assistant") ): with st.spinner("Reading the content..."): if self.chat.message_attachments == "image": prompt = get_chat_prompt( user_input, role=self.chat.role, image_attachment=True ) bot_resp = self.chatbot.generate( prompt, stream=False, images=[content_attachment], model="vision", ) if isinstance(bot_resp, dict): bot_resp = bot_resp.get("content", "") elif isinstance(bot_resp, OllamaMessage): bot_resp = bot_resp.content st.write(bot_resp) bot_response = bot_resp else: prompt = get_chat_prompt( user_input, content_attachment=content_attachment, role=self.chat.role, ) response = self.chatbot.generate(prompt, stream=True) bot_response = st.write_stream(response) if self.chat.chat_history[-1]["role"] != "assistant": self.chat.add_message("assistant", bot_response) self.chat.update_in_arango() def answer_tool_call( self, response, user_input ): #! This should be in the Base ChatBot? bot_responses = [] tools_response = response.get("tool_calls", []) for tool in tools_response: function_name = tool.function.get("name") if len(tools_response) > 1: # Don't use conversational response tool if there are other tools if function_name == "conversational_response_tool": continue arguments = tool.function.arguments arguments["query"] = user_input print("Function name:", function_name) with st.chat_message( "assistant", avatar=self.chat.get_avatar(role="assistant") ): if function_name in [ "fetch_other_documents_tool", "fetch_science_articles_tool", "fetch_science_articles_and_other_documents_tool", ]: chunks = getattr(self, function_name)(**arguments) response_text = self.generate_from_chunks(user_input, chunks) # Separate thinking chunk and normal chunk print_red("Model:", self.chatbot.model) if self.chatbot.model == "reasoning": bot_response = self.write_reasoning(response_text) else: bot_response = self.write_normal(response_text) bot_responses.append(bot_response) if chunks: sources = "###### Sources:\n" for title, group in chunks.items(): j = group["chunks"][0]["metadata"].get( "journal", "No Journal" ) d = group["chunks"][0]["metadata"].get( "published_date", "No Date" ) sources += f"[{group['article_number']}] **{title}** :gray[*{j}* ({d})] \n" st.markdown(sources) bot_response += f"\n\n{sources}" bot_responses.append(bot_response) elif function_name == "fetch_notes_tool": notes = getattr(self, function_name)() response_text = self.generate_from_notes(user_input, notes) bot_responses.append(st.write_stream(response_text).strip('"')) elif function_name == "conversational_response_tool": response_text = getattr(self, function_name)(user_input) print( "###", response_text, ) if self.chatbot.call_model == self.chatbot.get_model("reasoning"): print_blue("REASONING MODEL!") bot_response = self.write_reasoning(response_text).strip('"') else: if isinstance(response_text, OllamaMessage): response_text = response_text.content elif isinstance(response_text, dict): response_text = response_text.get("content", "") bot_response = self.write_normal(response_text).strip('"') return "\n\n".join(bot_responses) def write_reasoning(self, response_text): chunks_iter = iter(response_text) # convert generator to iterator try: first_mode, first_text = next(chunks_iter) # get first chunk except StopIteration: # no chunks at all first_mode, first_text = None, None print_purple("FIRST MODE:", first_mode, first_text) # if it's thinking, show that in an expander if first_mode == "thinking": with st.expander("How the bot has been reasoning"): st.write(first_text.replace("", "").replace("", "")) # define a generator for the rest def rest_gen(): for _, text in chunks_iter: yield text bot_response = st.write_stream(rest_gen()) return bot_response else: def full_gen(): if first_mode: yield (first_mode, first_text) for mode, text in chunks_iter: yield (mode, text) bot_response = st.write_stream(full_gen()).strip('"') def write_normal(self, response_text): chunks_iter = iter(response_text) # convert generator to iterator def full_gen(): for chunk in chunks_iter: if isinstance(chunk, tuple) and len(chunk) == 2: _, text = chunk yield text else: yield chunk bot_response = st.write_stream(full_gen()).strip('"') return bot_response def generate_from_notes(self, user_input, notes): with st.spinner("Reading project notes..."): return super().generate_from_notes(user_input, notes) def generate_from_chunks(self, user_input, chunks): # For reading articles with a spinner magazines = set() for group in chunks.values(): j = group["chunks"][0]["metadata"].get("journal", "No Journal") magazines.add(f"*{j}*") s = ( f"Reading articles from {', '.join(list(magazines)[:-1])} and {list(magazines)[-1]}..." if len(magazines) > 1 else "Reading articles..." ) with st.spinner(s): return super().generate_from_chunks(user_input, chunks) def sidebar_content(self): with st.sidebar: st.write("---") st.markdown(f'#### {self.chat.name if self.chat.name else ""}') st.button("Delete this chat", on_click=self.delete_chat) def delete_chat(self): self.user_arango.db.collection("chats").delete_match( filters={"name": self.chat.name} ) self.chat = Chat() def get_notes(self): # We can show a spinner or messages too with st.spinner("Fetching notes..."): return super().get_notes() class EditorBot(StreamlitBot): def __init__(self, username: str, chat: Chat, **kwargs): super().__init__(username=username, chat=chat, **kwargs) self.role = "Editor" self.tools = [self.fetch_notes_tool, self.fetch_other_documents_tool] # self.chatbot = LLM( # system_message=get_editor_prompt(kwargs.get("project")), # messages=self.chat.chat_history2bot(), # chosen_backend=kwargs.get("chosen_backend"), # ) print_purple("MODEL FOR EDITOR BOT:", self.chatbot.model) class ResearchAssistantBot(StreamlitBot): def __init__(self, username: str, chat: Chat, **kwargs): super().__init__(username=username, chat=chat, **kwargs) self.role = "Research Assistant" # self.chatbot = LLM( # system_message=get_assistant_prompt(), # temperature=0.1, # messages=self.chat.chat_history2bot(), # ) self.tools = [ self.fetch_science_articles_tool, self.fetch_science_articles_and_other_documents_tool, self.conversational_response_tool, ] class PodBot(StreamlitBot): """Two LLM agents construct a conversation using material from science articles.""" def __init__( self, username: str, chat: Chat, subject: str, instructions: str = None, **kwargs, ): super().__init__(username=username, chat=chat, **kwargs) self.subject = subject self.instructions = instructions self.guest_name = kwargs.get("name_guest", "Merit") self.hostbot = HostBot( Chat(username=self.username, role="Host"), subject, username, instructions=instructions, **kwargs, ) self.guestbot = GuestBot( Chat(username=self.username, role="Guest"), subject, username, name_guest=self.guest_name, **kwargs, ) def run(self): notes = self.get_notes() notes_string = "" if self.instructions: instructions_string = f''' These are the instructions for the podcast from the producer: """ {self.instructions} """ ''' else: instructions_string = "" for note in notes: notes_string += f"\n# {note['title']}\n{note['content']}\n---\n" a = f'''You will make a podcast interview with {self.guest_name}, an expert on "{self.subject}". {instructions_string} Below are notes on the subject that you can use to ask relevant questions: """ {notes_string} """ Say hello to the expert and start the interview. Remember to keep the interview to the subject of {self.subject} throughout the conversation. ''' # Stop button for the podcast with st.sidebar: stop = st.button("Stop podcast", on_click=self.stop_podcast) while st.session_state["make_podcast"]: # Stop the podcast if there are more than 14 messages in the chat self.chat.show_chat_history() if len(self.chat.chat_history) == 14: result = self.hostbot.generate( "The interview has ended. Say thank you to the expert and end the conversation." ) self.chat.add_message("Host", result) with st.chat_message( "assistant", avatar=self.chat.get_avatar(role="assistant") ): st.write(result.strip('"')) st.stop() _q = self.hostbot.toolbot.generate( query=f"{self.guest_name} has answered: {a}. You have to choose a tool to help the host continue the interview.", tools=self.hostbot.tools, temperature=0.6, stream=False, ) if "tool_calls" in _q: q = self.hostbot.answer_tool_call(_q, a) else: q = _q self.chat.add_message("Host", q) _a = self.guestbot.toolbot.generate( f'The podcast host has asked: "{q}" Choose a tool to help the expert answer with relevant facts and information.', tools=self.guestbot.tools, ) if "tool_calls" in _a: print_yellow("Tool call response (guest)", _a) print_yellow(self.guestbot.chat.role) a = self.guestbot.answer_tool_call(_a, q) else: a = _a self.chat.add_message("Guest", a) self.update_session_state() def stop_podcast(self): st.session_state["make_podcast"] = False self.update_session_state() self.chat.show_chat_history() class HostBot(StreamlitBot): def __init__( self, chat: Chat, subject: str, username: str, instructions: str, **kwargs ): super().__init__(chat=chat, username=username, **kwargs) self.chat.role = kwargs.get("role", "Host") self.tools = [self.fetch_notes_tool, self.conversational_response_tool] self.instructions = instructions self.llm = LLM( system_message=f''' You are the host of a podcast and an expert on {subject}. You will ask one question at a time about the subject, and then wait for the guest to answer. Don't ask the guest to talk about herself/himself, only about the subject. Make your questions short and clear, only if necessary add a brief context to the question. These are the instructions for the podcast from the producer: """ {self.instructions} """ If the experts' answer is complicated, try to make a very brief summary of it for the audience to understand. You can also ask follow-up questions to clarify the answer, or ask for examples. ''', messages=self.chat.chat_history2bot(), ) self.toolbot = LLM( temperature=0, system_message=""" You are assisting a podcast host in asking questions to an expert. Choose one or many tools to use in order to assist the host in asking relevant questions. Often "conversational_response_tool" is enough, but sometimes project notes are needed. Make sure to read the description of the tools carefully!""", chat=False, model="tools", ) def generate(self, query): return self.llm.generate(query) class GuestBot(StreamlitBot): def __init__(self, chat: Chat, subject: str, username: str, **kwargs): super().__init__(chat=chat, username=username, **kwargs) self.chat.role = kwargs.get("role", "Guest") self.tools = [ self.fetch_notes_tool, self.fetch_science_articles_tool, ] self.llm = LLM( system_message=f""" You are {kwargs.get('name', 'Merit')}, an expert on {subject}. Today you are a guest in a podcast about {subject}. A host will ask you questions about the subject and you will answer by using scientific facts and information. When answering, don't say things like "based on the documents" or alike, as neither the host nor the audience can see the documents. Act just as if you were talking to someone in a conversation. Try to be concise when answering, and remember that the audience of the podcast is not expert on the subject, so don't complicate things too much. It's very important that you answer in a "spoken" way, as if you were talking to someone in a conversation. That means you should avoid using scientific jargon and complex terms, too many figures or abstract concepts. Lists are also not recommended, instead use "for the first reason", "secondly", etc. Instead, use "..." to indicate a pause, "-" to indicate a break in the sentence, as if you were speaking. """, messages=self.chat.chat_history2bot(), ) self.toolbot = LLM( temperature=0, system_message=f"You are an assistant to an expert on {subject}. Choose one or many tools to use in order to assist the expert in answering questions. Make sure to read the description of the tools carefully.", chat=False, model="tools", ) def generate(self, query): return self.llm.generate(query)