### Complete Example: Record QueryBot Calls Source: https://github.com/ericmjl/llamabot/blob/main/docs/tutorials/recording_prompts.md A full example demonstrating the setup, interaction, and data retrieval using PromptRecorder with QueryBot. ```python from llamabot.recorder import PromptRecorder, autorecord from llamabot.bot.querybot import QueryBot system_message = "You are a helpful assistant that can answer questions based on the provided documents." model_name = "gpt-4" doc_paths = ["document1.txt", "document2.txt"] query_bot = QueryBot(system_message, model_name=model_name, document_paths=doc_paths) with PromptRecorder() as recorder: query = "What is the main idea of document1?" response = query_bot(query) print(response.content) query = "How does document2 support the main idea?" response = query_bot(query) print(response.content) print(recorder.dataframe()) recorder.panel().show() ``` -------------------------------- ### Install and Run Marimo Notebook Source: https://github.com/ericmjl/llamabot/blob/main/notebooks/README.md Install the Marimo library and run the ReAct AgentBot demo notebook. ```bash pip install marimo ``` ```bash marimo run notebooks/react-agentbot-demo.py ``` -------------------------------- ### Complete SimpleBot Example Source: https://github.com/ericmjl/llamabot/blob/main/docs/tutorials/simplebot.md A full example demonstrating the initialization and interaction with the SimpleBot class, including printing the response content. ```python from llamabot.bot.simplebot import SimpleBot # Initialize the SimpleBot system_prompt = "You are an AI assistant that helps users with their questions." bot = SimpleBot(system_prompt) # Interact with the SimpleBot human_message = "What is the capital of France?" response = bot(human_message) print(response.content) ``` -------------------------------- ### Install LlamaBot (All Dependencies) Source: https://github.com/ericmjl/llamabot/blob/main/README.md Install LlamaBot along with all optional dependencies for full functionality. ```python pip install "llamabot[all]" ``` -------------------------------- ### FastAPI Example with Async Endpoint Source: https://github.com/ericmjl/llamabot/blob/main/docs/releases/v0.3.1.md This snippet demonstrates how to create an asynchronous endpoint using FastAPI. Ensure FastAPI is installed. ```python from fastapi import FastAPI app = FastAPI() @app.get("/async-endpoint") async def async_endpoint(): return {"message": "This is an async endpoint"} ``` -------------------------------- ### Async Simple Bot Streaming Example Source: https://github.com/ericmjl/llamabot/blob/main/docs/reference/streaming_async.md This example demonstrates how to use AsyncSimpleBot for asynchronous streaming, typically used in environments supporting async/await like FastAPI or notebooks. Ensure llamabot is installed from the repository using PEP 723 for examples. ```python from llamabot.bot.async_simplebot import AsyncSimpleBot async def main(): bot = AsyncSimpleBot() async for delta in bot.stream_async("Hello world!"): print(delta, end="", flush=True) if __name__ == "__main__": import asyncio asyncio.run(main()) ``` -------------------------------- ### Few-Shot Prompting Example Source: https://github.com/ericmjl/llamabot/blob/main/docs/tutorials/prompts.md Include examples within the prompt template to guide the AI's response format and style, especially for classification tasks. ```python @prompt(role="user") def classification_with_examples(text, categories): """Classify the following text into one of these categories: {% for category in categories %} - {{ category }} {% endfor %} Examples: Text: "The weather is sunny today" Category: Weather Text: "I love this new restaurant" Category: Food Text: "{{ text }}" Category:""" ``` -------------------------------- ### SimpleBot Usage Examples Source: https://github.com/ericmjl/llamabot/blob/main/docs/reference/bots/simplebot.md Provides examples of how to use the SimpleBot class. ```APIDOC ## Usage Examples ### Basic Usage ```python import llamabot as lmb bot = lmb.SimpleBot( system_prompt="You are a helpful assistant.", model_name="gpt-4o-mini" ) response = bot("What is machine learning?") print(response.content) ``` ### With Chat Memory ```python import llamabot as lmb # Linear memory (fast, no LLM calls) memory = lmb.ChatMemory() ``` ``` -------------------------------- ### Serve Documentation Locally Source: https://github.com/ericmjl/llamabot/blob/main/docs/contributing/setup.md Start a local MkDocs server to preview the project documentation. The server typically runs at http://127.0.0.1:8000. ```bash pixi run docs ``` -------------------------------- ### Example: Basic Document Q&A with QueryBot Source: https://github.com/ericmjl/llamabot/blob/main/docs/reference/bots/querybot.md Demonstrates setting up a LanceDBDocStore, extending it with markdown files, and initializing QueryBot for Q&A. ```python import llamabot as lmb from pathlib import Path # Create a document store docstore = lmb.LanceDBDocStore(table_name="my_documents") # Add documents docs_paths = Path("docs").rglob("*.md") docs_texts = [p.read_text() for p in docs_paths] docstore.extend(docs_texts) # Create QueryBot bot = lmb.QueryBot( system_prompt="You are an expert on these documents.", docstore=docstore ) # Query the documents response = bot("What is the main topic of these documents?") ``` -------------------------------- ### Create AIMessage Instance Source: https://github.com/ericmjl/llamabot/blob/main/docs/reference/components/messages.md Example of how to instantiate an AIMessage with specific content. ```python from llamabot.components.messages import AIMessage msg = AIMessage(content="Python is a programming language.") ``` -------------------------------- ### Run Python Tutorial Notebook Source: https://github.com/ericmjl/llamabot/blob/main/tutorials/pydata-boston-2025/README.md Use 'uv run' to execute the main tutorial notebook. Ensure Python 3.13+ is installed. ```bash uv run backoffice.py ``` -------------------------------- ### Install Pre-commit Hooks Source: https://github.com/ericmjl/llamabot/blob/main/docs/contributing/setup.md Install pre-commit hooks globally and then install them for the current repository. These hooks automate code quality checks before commits. ```bash uv tool install pre-commit pre-commit install ``` -------------------------------- ### Install LlamaBot (Minimum Dependencies) Source: https://github.com/ericmjl/llamabot/blob/main/README.md Install LlamaBot with its essential dependencies using pip. ```python pip install llamabot==0.17.11 ``` -------------------------------- ### Install Dependencies with Pixi Source: https://github.com/ericmjl/llamabot/blob/main/docs/contributing/setup.md Install all project dependencies using pixi. This command creates a pixi environment with core, optional, and development dependencies. ```bash pixi install ``` -------------------------------- ### Install Dependencies Source: https://github.com/ericmjl/llamabot/blob/main/docs/tutorials/recording_prompts.md Install pandas and panel libraries using pip. ```bash pip install pandas panel ``` -------------------------------- ### Set Up Chat Interface Source: https://github.com/ericmjl/llamabot/blob/main/docs/tutorials/chat-ui/querybot.md Initializes the chat interface with a callback function and sends a welcome message. Use this to start the user interaction. ```python chat_interface = pn.chat.ChatInterface( callback=callback, callback_user="QueryBot", show_clear=False, ) chat_interface.send( "Send a message to get a reply from the bot!", user="System", respond=False, ) ``` -------------------------------- ### Basic Multi-Step Workflow Example Source: https://github.com/ericmjl/llamabot/blob/main/docs/reference/bots/agentbot.md Demonstrates a basic multi-step workflow with AgentBot, including defining custom tools and initiating a conversation. ```python import llamabot as lmb @lmb.tool def get_weather(city: str) -> str: """Get the current weather for a city. :param city: The name of the city :return: Weather information """ return f"The weather in {city} is sunny, 72°F" @lmb.tool(loopback_name=None) def respond_to_user(response: str) -> str: """Respond to the user.""" return response agent = lmb.AgentBot( tools=[get_weather, respond_to_user], model_name="gpt-4o-mini" ) result = agent("What's the weather in New York?") ``` -------------------------------- ### Summarize Command Output Example Source: https://github.com/ericmjl/llamabot/blob/main/docs/cli/blog.md This is an example of the output format you can expect when using the `summarize` command, including a generated blog title, SEMBR-formatted summary, and tags. ```text Here is your blog title: [Generated Blog Title] Applying SEMBR to your summary... Here is your blog summary: [Generated Blog Summary with SEMBR] Here are your blog tags: [Generated Blog Tags] ``` -------------------------------- ### Create SystemMessage Instance Source: https://github.com/ericmjl/llamabot/blob/main/docs/reference/components/messages.md Example of how to instantiate a SystemMessage with specific content. ```python from llamabot.components.messages import SystemMessage msg = SystemMessage(content="You are a helpful assistant.") ``` -------------------------------- ### Create ToolMessage Instance Source: https://github.com/ericmjl/llamabot/blob/main/docs/reference/components/messages.md Example of how to instantiate a ToolMessage with specific content. ```python from llamabot.components.messages import ToolMessage msg = ToolMessage(content="Tool execution result") ``` -------------------------------- ### Create DeveloperMessage Instance Source: https://github.com/ericmjl/llamabot/blob/main/docs/reference/components/messages.md Example of how to instantiate a DeveloperMessage with specific content. ```python from llamabot.components.messages import DeveloperMessage msg = DeveloperMessage(content="Add error handling to this function.") ``` -------------------------------- ### Example: QueryBot with Chat Memory Source: https://github.com/ericmjl/llamabot/blob/main/docs/reference/bots/querybot.md Shows how to integrate QueryBot with ChatMemory for conversational context. The bot will remember previous questions. ```python import llamabot as lmb docstore = lmb.LanceDBDocStore(table_name="my_docs") docstore.extend(documents) # Create chat memory for conversation context memory = lmb.ChatMemory() bot = lmb.QueryBot( system_prompt="You are an expert on these documents.", docstore=docstore, memory=memory ) # Bot remembers previous questions response1 = bot("What is authentication?") response2 = bot("How does it work?") # Bot remembers context ``` -------------------------------- ### LlamaBot CLI Logs Serve Source: https://context7.com/ericmjl/llamabot/llms.txt Start a web UI for viewing experiment logs using the LlamaBot CLI. ```bash llamabot logs serve ``` -------------------------------- ### Run Ollama with a Model Source: https://github.com/ericmjl/llamabot/blob/main/docs/tutorials/ollama.md Start the Ollama server with a specified model. Ensure you have adequate RAM for the model you are running. ```bash ollama run ``` ```bash ollama run vicuna ``` -------------------------------- ### Run Button Example Source: https://github.com/ericmjl/llamabot/blob/main/AGENTS.md Demonstrates the use of `mo.ui.run_button` to trigger actions. The code checks which button was pressed and prints a corresponding message. ```python import marimo as mo first_button = mo.ui.run_button(label="Option 1") second_button = mo.ui.run_button(label="Option 2") [first_button, second_button] if first_button.value: print("You chose option 1!") elif second_button.value: print("You chose option 2!") else: print("Click a button!") ``` -------------------------------- ### ToolBot Usage Source: https://github.com/ericmjl/llamabot/blob/main/docs/reference/components/tools.md Example of how to use ToolBot for single-turn tool execution, where a bot is initialized with a system prompt, model name, and a list of tools. ```APIDOC ## ToolBot Usage ### ToolBot ```python import llamabot as lmb @lmb.tool def calculate_sum(a: int, b: int) -> int: """Calculate the sum of two numbers.""" return a + b bot = lmb.ToolBot( system_prompt="You are a calculator.", model_name="gpt-4o-mini", tools=[calculate_sum] ) tool_calls = bot("Calculate 5 + 3") ``` ``` -------------------------------- ### Import ToolBot and write_and_execute_code Source: https://github.com/ericmjl/llamabot/blob/main/docs/tutorials/toolbot.md Import the necessary components from the llamabot library to get started with ToolBot. ```python from llamabot import ToolBot from llamabot.components.tools import write_and_execute_code ``` -------------------------------- ### Blog Post Summarization Prompt Source: https://github.com/ericmjl/llamabot/blob/main/docs/blog_text.txt Defines a prompt for an LLM to act as a blog post summarization bot. It includes examples of previous summaries to guide the tone and style, emphasizing enticing the reader and using emojis. ```python summarization_prompt = f"""You are a blog post summarization bot. Your take a blog post and write a summary of it. The summary is intended to hook a reader into the blog post and entice them to read it. You should add in emojis where appropriate. My previous summaries sounded like this: 1. I finally figured out how to programmatically create Google Docs using Python. Along the way, I figured out service accounts, special HTML tags, and how to set multi-line environment variables. Does that tickle your brain? 2. Here is my personal experience creating an app for translating Ark Channel devotionals using OpenAI's GPT-3. In here, I write about the challenges I faced and the lessons I learned! I hope it is informative for you! 3. I discuss two Twitter threads that outline potential business ideas that could be built on top of ChatGPT3, a chatbot-based language model. What's the tl;dr? As mankind has done over and over, we build machines to solve mundane and repetitive tasks, and ChatGPT3 and other generative models are no exception! The summary you generate should match the tone and style of the previously-generated ones. """ ``` -------------------------------- ### Initialize Partitioned LanceDBDocStore Source: https://github.com/ericmjl/llamabot/blob/main/docs/tutorials/querybot.md Sets up a LanceDBDocStore with partitioning enabled and a default partition specified. This allows for organized storage and retrieval of documents based on categories. ```python from llamabot.components.docstore import LanceDBDocStore from pathlib import Path # Create partitioned document store docstore = LanceDBDocStore( table_name="project-docs", enable_partitioning=True, default_partition="general", ) ``` -------------------------------- ### Using the --from-scratch Flag with llamabot docs write Source: https://github.com/ericmjl/llamabot/blob/main/docs/cli/docs.md Employ the `--from-scratch` flag to completely regenerate documentation, ignoring any existing content. This is useful for a fresh start. ```sh llamabot docs write --from-scratch ``` -------------------------------- ### Memory Initialization and Bot Configuration Source: https://github.com/ericmjl/llamabot/blob/main/docs/design/unified_chat_memory.md Demonstrates how to initialize different memory types and configure bots with them. ```APIDOC ## Memory Initialization and Bot Configuration ### Description This section shows how to create and use different memory configurations for Llamabot, including linear, threaded (graph), and custom memory setups. ### Code Examples **Linear Memory (Default):** ```python import llamabot as lmb # Default linear memory is fast and suitable for simple Q&A linear_memory = lmb.ChatMemory() simple_bot = lmb.SimpleBot( system_prompt="You are a helpful assistant.", memory=linear_memory ) ``` **Graph Memory (Threaded):** ```python # Graph memory with smart threading for complex conversations graph_memory = lmb.ChatMemory.threaded(model="gpt-4o-mini") query_bot = lmb.QueryBot( system_prompt="You are a helpful assistant.", memory=graph_memory ) ``` **Custom Memory:** ```python # Custom memory for specific performance or summarization needs custom_memory = lmb.ChatMemory( node_selector=lmb.LLMNodeSelector(model="gpt-4o-mini"), summarizer=None # Example: disabling summarization ) # Assuming StructuredBot is defined elsewhere # structured_bot = StructuredBot( # system_prompt="You are a helpful assistant.", # pydantic_model=SomeModel, # memory=custom_memory # ) ``` ``` -------------------------------- ### Install LlamaBot Source: https://github.com/ericmjl/llamabot/blob/main/docs/cli/notebook.md Install the llamabot package using pip. This is a prerequisite for using the CLI. ```bash pip install llamabot ``` -------------------------------- ### Basic Multi-Step Workflow Example Source: https://github.com/ericmjl/llamabot/blob/main/docs/reference/bots/agentbot.md Demonstrates a basic multi-step workflow using AgentBot, including defining custom tools and executing a user query. ```APIDOC ## Basic Multi-Step Workflow ### Example ```python import llamabot as lmb @lmb.tool def get_weather(city: str) -> str: """Get the current weather for a city. :param city: The name of the city :return: Weather information """ return f"The weather in {city} is sunny, 72°F" @lmb.tool(loopback_name=None) def respond_to_user(response: str) -> str: """Respond to the user.""" return response agent = lmb.AgentBot( tools=[get_weather, respond_to_user], model_name="gpt-4o-mini" ) result = agent("What's the weather in New York?") ``` ``` -------------------------------- ### Create and Use ToolBot Source: https://github.com/ericmjl/llamabot/blob/main/docs/reference/components/tools.md Illustrates setting up a ToolBot with a custom tool for calculations. The bot uses the provided tool to respond to user queries. ```python import llamabot as lmb @lmb.tool def calculate_sum(a: int, b: int) -> int: """Calculate the sum of two numbers.""" return a + b bot = lmb.ToolBot( system_prompt="You are a calculator.", model_name="gpt-4o-mini", tools=[calculate_sum] ) tool_calls = bot("Calculate 5 + 3") ``` -------------------------------- ### Retrieve from Specific Partition for Manual Prompting Source: https://github.com/ericmjl/llamabot/blob/main/docs/tutorials/querybot.md Demonstrates retrieving documents from a specific partition ('tutorials') to be manually used when constructing a prompt for an LLM. This offers fine-grained control over the context provided to the language model. ```python # To query only a specific partition, use docstore.retrieve() directly # and then manually construct your prompt with those results tutorial_only_results = docstore.retrieve( "getting started", partitions=["tutorials"] # Only tutorials partition ) # You can then use these results with your LLM of choice ``` -------------------------------- ### QueryBot Call Example Source: https://github.com/ericmjl/llamabot/blob/main/docs/reference/bots/querybot.md Example of calling the QueryBot with a specific query to retrieve information from its document store. ```python import llamabot as lmb docstore = lmb.LanceDBDocStore(table_name="my_docs") docstore.extend([doc1, doc2, doc3]) bot = lmb.QueryBot( system_prompt="You are an expert on these documents.", docstore=docstore ) response = bot("What does the documentation say about authentication?") print(response.content) ``` -------------------------------- ### Example: Generate Mermaid Diagram Source: https://github.com/ericmjl/llamabot/blob/main/docs/reference/components/chat_memory.md Example of generating a Mermaid diagram for a threaded ChatMemory instance after adding messages. ```python import llamabot as lmb memory = lmb.ChatMemory.threaded() # ... add messages ... mermaid_diagram = memory.to_mermaid() print(mermaid_diagram) ``` -------------------------------- ### Initialize SimpleBot Source: https://github.com/ericmjl/llamabot/blob/main/docs/tutorials/simplebot.md Create an instance of SimpleBot with a system prompt. Optional parameters like temperature and model_name can also be set. ```python system_prompt = "You are an AI assistant that helps users with their questions." bot = SimpleBot(system_prompt) ``` -------------------------------- ### Install Markdownlint Globally Source: https://github.com/ericmjl/llamabot/blob/main/docs/contributing/setup.md Install the markdownlint tool globally using pixi. This tool is used for linting markdown files. ```bash pixi global install markdownlint ``` -------------------------------- ### Initialize QueryBot Source: https://github.com/ericmjl/llamabot/blob/main/docs/tutorials/recording_prompts.md Create an instance of QueryBot with system message, model name, and document paths. ```python system_message = "You are a helpful assistant that can answer questions based on the provided documents." model_name = "gpt-4" doc_paths = ["document1.txt", "document2.txt"] query_bot = QueryBot(system_message, model_name=model_name, document_paths=doc_paths) ``` -------------------------------- ### Install Llamabot CLI Source: https://github.com/ericmjl/llamabot/blob/main/docs/cli/python.md Install the Llamabot Python CLI using pip. This command is required before using any of the CLI tools. ```bash pip install -U llamabot ``` -------------------------------- ### Set Up Widgets and Global Variables Source: https://github.com/ericmjl/llamabot/blob/main/docs/tutorials/chat-ui/querybot.md Configures a FileInput widget for PDF uploads, a LoadingSpinner for visual feedback, and initializes a global variable for the QueryBot instance. ```python file_input = pn.widgets.FileInput(mime_type=["application/pdf"]) spinner = pn.indicators.LoadingSpinner(value=False, width=30, height=30) global bot bot = None ``` -------------------------------- ### Run AsyncQueryBot Demo Source: https://github.com/ericmjl/llamabot/blob/main/docs/examples/async_querybot_htmx_assets/index.html Execute this command in your terminal to start the AsyncQueryBot demo. It uses uvicorn to run the application and enables hot-reloading for development. ```bash pixi run uvicorn docs.examples.async_querybot_htmx_demo:app --reload ``` -------------------------------- ### Example: Create Threaded Memory Source: https://github.com/ericmjl/llamabot/blob/main/docs/reference/components/chat_memory.md Example of creating a ChatMemory instance configured for threaded conversations using a specific LLM model. ```python import llamabot as lmb # Create threaded memory memory = lmb.ChatMemory.threaded(model="gpt-4o-mini") ``` -------------------------------- ### Verify Editable Installation Source: https://github.com/ericmjl/llamabot/blob/main/docs/contributing/setup.md Run this command to confirm that the llamabot package is installed in editable mode. This ensures that changes to the source code are immediately reflected. ```bash pixi run python -c "import llamabot; print(llamabot.__file__)" ``` -------------------------------- ### Initialize SimpleBot with API Provider Source: https://github.com/ericmjl/llamabot/blob/main/README.md Create a SimpleBot instance with a system prompt and specify an API model. Ensure the OPENAI_API_KEY environment variable is configured for OpenAI models. ```python import llamabot as lmb system_prompt = "You are Richard Feynman. You will be given a difficult concept, and your task is to explain it back." feynman = lmb.SimpleBot( system_prompt, model_name="gpt-4.1-mini" ) ``` -------------------------------- ### Complete Markdown Source File Example Source: https://github.com/ericmjl/llamabot/blob/main/docs/cli/docs.md An example of a Markdown file structured with the necessary frontmatter and initial content for the `llamabot docs write` command. ```markdown --- intents: - Provide an overview of the `llamabot docs write` command. - Explain the `--from-scratch` flag. - Describe the frontmatter key-value pairs needed to make it work. linked_files: - llamabot/cli/docs.py - pyproject.toml --- # CLI Documentation for `llamabot docs write` ``` -------------------------------- ### Build Project Documentation Source: https://github.com/ericmjl/llamabot/blob/main/docs/contributing/setup.md Generate the static documentation files for the project. This command is used for building the documentation for deployment or distribution. ```bash pixi run build-docs ``` -------------------------------- ### Install Git Commit Hook with LlamaBot Source: https://github.com/ericmjl/llamabot/blob/main/docs/cli/git.md Installs a Git commit hook to automatically generate commit messages using LlamaBot. Ensure you are in a Git repository. ```bash llamabot git hooks ``` -------------------------------- ### LanceDBDocStore With Partitioning Source: https://github.com/ericmjl/llamabot/blob/main/docs/reference/components/docstore.md Initializes LanceDBDocStore with partitioning enabled. Documents can be organized into logical groups. ```python import llamabot as lmb docstore = lmb.LanceDBDocStore( table_name="my_documents", enable_partitioning=True ) ``` -------------------------------- ### BM25DocStore Constructor Source: https://github.com/ericmjl/llamabot/blob/main/docs/reference/components/docstore.md Initializes the BM25DocStore. This store has no configuration parameters. ```python def __init__(self) -> None: ``` -------------------------------- ### Create RetrievedMessage Instance Source: https://github.com/ericmjl/llamabot/blob/main/docs/reference/components/messages.md Example of how to instantiate a RetrievedMessage with specific content. ```python from llamabot.components.messages import RetrievedMessage msg = RetrievedMessage(content="Retrieved document content") ``` -------------------------------- ### Initialize Panel Extension Source: https://github.com/ericmjl/llamabot/blob/main/docs/tutorials/chat-ui/simplebot-and-chatbot.md Initialize the Panel extension before using its components. This prepares the environment for Panel. ```python pn.extension() ``` -------------------------------- ### Create and Use LanceDBDocStore Source: https://context7.com/ericmjl/llamabot/llms.txt Demonstrates creating a persistent, vector-based document store, adding documents, and setting up a QueryBot for RAG. Ensure the embedding model is specified if not using the default. ```python import llamabot as lmb from pathlib import Path # Create a LanceDB document store (persistent, vector-based) docstore = lmb.LanceDBDocStore( table_name="my-knowledge-base", storage_path=Path.home() / ".llamabot" / "lancedb", # Default path embedding_model="minishlab/potion-base-8M" # Default embedding model ) # Add documents to the store docstore.extend([ "LlamaBot is a Pythonic interface to LLMs.", "SimpleBot is used for stateless interactions.", "QueryBot enables RAG with document retrieval.", "StructuredBot returns validated Pydantic models." ]) # Or add documents from files # docstore.add_documents([Path("doc1.txt"), Path("doc2.txt")]) # Create QueryBot with the document store bot = lmb.QueryBot( system_prompt="You are an expert on LlamaBot. Answer questions using the retrieved context.", docstore=docstore, model_name="gpt-4o-mini", temperature=0.0 ) # Query the documents response = bot("What is SimpleBot used for?", n_results=5) print(response.content) # Output will be based on retrieved documents ``` -------------------------------- ### Create HumanMessage Instance Source: https://github.com/ericmjl/llamabot/blob/main/docs/reference/components/messages.md Example of how to instantiate a HumanMessage with specific content. ```python from llamabot.components.messages import HumanMessage msg = HumanMessage(content="What is Python?") ``` -------------------------------- ### Import Necessary Classes Source: https://github.com/ericmjl/llamabot/blob/main/docs/tutorials/recording_prompts.md Import PromptRecorder and QueryBot from their respective modules. ```python from llamabot.recorder import PromptRecorder, autorecord from llamabot.bot.querybot import QueryBot ``` -------------------------------- ### Threaded Memory Usage Source: https://github.com/ericmjl/llamabot/blob/main/docs/reference/components/chat_memory.md Example of how to create and use Threaded Memory. ```APIDOC ## Threaded Memory Intelligent memory that connects related conversation topics: ```python import llamabot as lmb memory = lmb.ChatMemory.threaded(model="gpt-4o-mini") ``` **Characteristics:** - Uses LLM to connect related topics - Creates conversation threads - Semantic search for retrieval - Best for complex, multi-topic conversations ``` -------------------------------- ### Create QueryBot with System Prompt Source: https://github.com/ericmjl/llamabot/blob/main/docs/tutorials/querybot.md Initializes a QueryBot with a specific system prompt. This bot will use the provided docstore, and queries will be directed to it. Note that QueryBot itself searches all partitions by default unless filtered externally. ```python # Create separate docstores or filter results per partition tutorial_bot = QueryBot( system_prompt="You are a Python tutorial assistant.", docstore=docstore, # Same docstore, but filter in your queries ) ``` -------------------------------- ### Linear Memory Usage Source: https://github.com/ericmjl/llamabot/blob/main/docs/reference/components/chat_memory.md Example of how to create and use Linear Memory. ```APIDOC ## Linear Memory Simple, fast memory that stores messages in order: ```python import llamabot as lmb memory = lmb.ChatMemory() # Linear by default ``` **Characteristics:** - Fast (no LLM calls) - Stores messages sequentially - Retrieves most recent messages - Best for simple conversations ``` -------------------------------- ### Basic BM25DocStore Usage Source: https://github.com/ericmjl/llamabot/blob/main/docs/reference/components/docstore.md Demonstrates the basic usage of BM25DocStore, including initialization, adding documents using `append` and `extend`, and retrieving documents with keyword search. ```python import llamabot as lmb docstore = lmb.BM25DocStore() # Add documents docstore.append("Document 1 text") docstore.extend(["Document 2 text", "Document 3 text"]) # Retrieve using keyword search results = docstore.retrieve("keyword search", n_results=5) ```