### Install Adalflow with OpenAI, Groq, and FAISS Source: https://github.com/sylphai-inc/adalflow/blob/main/use_cases/question_answering/chatbot.ipynb Installs the Adalflow library with specified optional dependencies for OpenAI, Groq, and FAISS. It also clears the output after the installation process is complete. ```python from IPython.display import clear_output !pip install -U adalflow[openai,groq,faiss-cpu] clear_output() ``` -------------------------------- ### Install Optional Dependencies with Poetry Source: https://github.com/sylphai-inc/adalflow/blob/main/adalflow/PACKAGING.md Installs the Adalflow package with specified optional dependencies using Poetry. This command allows for flexible installation based on required features. Multiple sets of extras can be installed sequentially. ```bash poetry install --extras "openai groq faiss" ``` ```bash poetry install --extras "anthropic cohere google-generativeai pgvector" ``` -------------------------------- ### Install Adalflow with RAG Dependencies Source: https://github.com/sylphai-inc/adalflow/blob/main/notebooks/tutorials/adalflow_logger.ipynb Installs the Adalflow library with necessary dependencies for OpenAI, Groq, and FAISS (CPU version) using pip. It also clears the output after installation. ```python from IPython.display import clear_output !pip install -U adalflow[openai,groq,faiss-cpu] clear_output() ``` -------------------------------- ### Start MLflow Server for Tracing Source: https://github.com/sylphai-inc/adalflow/blob/main/docs/source/new_tutorials/tracing.md Provides the bash commands to install AdalFlow and start the MLflow server. The MLflow server is a prerequisite for using AdalFlow's MLflow integration for tracing, and must be running before executing tracing examples. ```bash # Install MLflow if not already installed poetry add adalflow # Start MLflow server (required before running tracing examples) mlflow server --host 127.0.0.1 --port 8000 # Access MLflow UI at: http://localhost:8000 ``` -------------------------------- ### Verify Poetry Setup Source: https://github.com/sylphai-inc/adalflow/blob/main/docs/README.md Checks if all project dependencies installed via Poetry are valid and correctly configured. This command helps confirm a successful setup. ```bash poetry check ``` -------------------------------- ### Install Adalflow with OpenAI, Groq, and FAISS Source: https://github.com/sylphai-inc/adalflow/blob/main/notebooks/tutorials/adalflow_rag_playbook.ipynb Installs the Adalflow library with support for OpenAI, Groq, and FAISS integrations using pip. It also clears the output after installation. ```Python from IPython.display import clear_output !pip install -U adalflow[openai,groq,faiss-cpu] clear_output() ``` -------------------------------- ### Serve Documentation Locally Source: https://github.com/sylphai-inc/adalflow/blob/main/docs/README.md Starts a simple HTTP server in the build directory to view the generated HTML documentation in a web browser, useful for bypassing browser security restrictions on local files. ```bash cd docs/build/html python -m http.server ``` -------------------------------- ### Example: Convert README.md to introduction.rst Source: https://github.com/sylphai-inc/adalflow/blob/main/docs/README.md An example command showing how to convert a specific Markdown file (README.md) into a reStructuredText file (introduction.rst) within the project's documentation source directory. ```bash pandoc -s README.md -o docs/source/get_started/introduction.rst ``` -------------------------------- ### Install AdalFlow Source: https://github.com/sylphai-inc/adalflow/blob/main/docs/source/index.rst Installs the AdalFlow library using pip. This is the first step to start using AdalFlow for building LLM workflows. ```bash pip install -U adalflow ``` -------------------------------- ### AdalFlow OpenAIClient Direct Usage Example Source: https://github.com/sylphai-inc/adalflow/blob/main/docs/source/tutorials/model_client.rst Provides a practical example of using OpenAIClient directly to interact with an LLM model. It includes setup, client instantiation, and defining the model type for a query. ```python from adalflow.components.model_client import OpenAIClient from adalflow.core.types import ModelType from adalflow.utils import setup_env setup_env() openai_client = OpenAIClient() query = "What is the capital of France?" # try LLM model model_type = ModelType.LLM ``` -------------------------------- ### Setup AdalFlow and Dependencies in IPython Source: https://github.com/sylphai-inc/adalflow/blob/main/notebooks/tutorials/adalflow_rag_optimization.ipynb Installs AdalFlow, dspy, and datasets packages, followed by clearing the output. This sequence is typically executed in an interactive Python environment like Jupyter notebooks to prepare the workspace. ```python from IPython.display import clear_output !pip install -U adalflow[openai] # also install the package for the model client you'll use !pip install dspy !pip install datasets clear_output() ``` -------------------------------- ### Print Transformed Items and Setups Source: https://github.com/sylphai-inc/adalflow/blob/main/tutorials/database.ipynb Displays the transformed items stored under a specific key in `LocalDB`, along with the configurations for the transformer and mapper setups used for that key. This helps in debugging and understanding the transformation process. ```python # Assuming LocalDB and key are defined # class LocalDB: pass # dialog_turn_db: LocalDB # key: str print(dialog_turn_db.transformed_items[key]) print(dialog_turn_db.transformer_setups[key]) print(dialog_turn_db.mapper_setups[key]) ``` -------------------------------- ### Install Adalflow Dependencies with Poetry Source: https://github.com/sylphai-inc/adalflow/blob/main/adalflow/tests/README.md Installs all project dependencies, including those required for testing, using the poetry package manager. This command ensures the development environment is correctly set up. ```shell poetry install --with test ``` -------------------------------- ### Adalflow ReActAgent with Examples Source: https://github.com/sylphai-inc/adalflow/blob/main/tutorials/react_note.ipynb Illustrates using the Adalflow ReActAgent with explicit examples provided during initialization. This enhances the agent's ability to follow specific output formats or reasoning patterns, demonstrated with a multiplication example. ```python from adalflow.components.agent import ReActAgent from adalflow.core import ModelClientType, ModelClient from adalflow.utils import setup_env from adalflow.core.types import FunctionExpression # Assume multiply function is defined as in the previous snippet def multiply(a: int, b: int) -> int: """ Multiply two numbers. """ return a * b # Assume model_kwargs are defined as in the previous snippet llama3_model_kwargs = { "model": "llama3-8b-8192", "temperature": 0.0, } def test_react_agent_use_examples(model_client: ModelClient, model_kwargs: dict): tools = [multiply] # Simplified tools for this example queries = [ "What is the capital of France? and what is 465 times 321 then add 95297 and then divide by 13.2?", ] # add examples for the output format str example_using_multiply = FunctionExpression.from_function( func=multiply, thought="Now, let's multiply two numbers.", a=3, b=4, ) react = ReActAgent( max_steps=6, add_llm_as_fallback=True, tools=tools, model_client=model_client, model_kwargs=model_kwargs, examples=[example_using_multiply], ) print(react) # see the output format react.planner.print_prompt() for query in queries: print(f"Query: {query}") agent_response = react.call(query) print(f"Agent response: {agent_response}") print("") if __name__ == "__main__": # Assuming setup_env() and other necessary imports are done test_react_agent_use_examples(ModelClientType.GROQ(), llama3_model_kwargs) ``` -------------------------------- ### Install Adalflow with Dependencies Source: https://github.com/sylphai-inc/adalflow/blob/main/notebooks/tutorials/adalflow_function_calls.ipynb Installs the Adalflow library along with optional dependencies for OpenAI, Groq, and FAISS CPU. `clear_output()` is used to clean up the display after installation. ```python from IPython.display import clear_output !pip install -U adalflow[openai,groq,faiss-cpu] clear_output() ``` -------------------------------- ### Load and Inspect Dataset Source: https://github.com/sylphai-inc/adalflow/blob/main/notebooks/tutorials/adalflow_classification_optimization.ipynb Loads training, validation, and testing datasets and prints the first example from the training set. This snippet demonstrates basic data loading and access. ```python train_dataset, val_dataset, test_dataset = load_datasets() example = train_dataset[0] print(example) ``` -------------------------------- ### Install Adalflow with OpenAI and Groq Support Source: https://github.com/sylphai-inc/adalflow/blob/main/notebooks/tutorials/adalflow_classification_optimization.ipynb Installs the adalflow Python package using pip, including optional dependencies for OpenAI and Groq. This command ensures that the necessary libraries for interacting with these specific AI models are included. ```bash pip install adalflow[openai,groq] ``` -------------------------------- ### Install Adalflow and Datasets in Python Environment Source: https://github.com/sylphai-inc/adalflow/blob/main/notebooks/tutorials/adalflow_classification_optimization.ipynb Installs or upgrades the adalflow package with OpenAI support and the datasets library within a Python environment, likely a Jupyter Notebook or similar. It also clears the output before proceeding. ```python from IPython.display import clear_output !pip install -U adalflow[openai] # also install the package for the model client you'll use !pip install datasets clear_output() ``` -------------------------------- ### Setting Up Pre-commit Hooks Source: https://github.com/sylphai-inc/adalflow/blob/main/docs/source/contributor/contribution.rst Steps to install Poetry, set up the project's Python dependencies, activate the virtual environment, and install pre-commit hooks for code quality. ```bash pip install poetry poetry install poetry shell pre-commit install ``` -------------------------------- ### Redis Sorted Set Commands Source: https://github.com/sylphai-inc/adalflow/blob/main/notebooks/tutorials/adalflow_classification_optimization.ipynb Comprehensive documentation for Redis sorted set commands, including ZREM and ZRANGE. It provides details on parameters, return values, and usage examples. ```APIDOC ZREM key member [member ...] - Removes members from a sorted set - Parameters: - key: The sorted set key - member: Members to remove - Returns: Number of members removed ZRANGE key start stop [BYSCORE|BYLEX] [REV] [LIMIT offset count] [WITHSCORES] - Returns a range of members - Parameters: ... (Details omitted for brevity) ``` -------------------------------- ### Initialize and Query RAG System Source: https://github.com/sylphai-inc/adalflow/blob/main/notebooks/tutorials/adalflow_rag_playbook.ipynb Demonstrates the initial setup of the RAG system. This includes preparing documents, creating a FAISS index, initializing the RAG object, and performing an initial query. ```python # Prepare initial documents doc1 = Document( meta_data={"title": "Li Yin's profile"}, text="My name is Li Yin, I love rock climbing" + "lots of nonsense text" * 500, id="doc1", ) doc2 = Document( meta_data={"title": "Interviewing Li Yin"}, text="lots of more nonsense text" * 250 + "Li Yin is an AI researcher and a software engineer" + "lots of more nonsense text" * 250, id="doc2", ) # Prepare the database (only runs once) prepare_database_with_index([doc1, doc2], index_file="index.faiss") # Initialize RAG rag = RAG(index_file="index.faiss") print(rag) # Query the RAG system query = "What is Li Yin's hobby and profession?" response = rag.call(query) print(f"Response: {response}") ``` -------------------------------- ### Set Environment Variables Source: https://github.com/sylphai-inc/adalflow/blob/main/notebooks/tutorials/adalflow_classification_optimization.ipynb Sets the OPENAI_API_KEY environment variable using the provided API key. This is a common setup step for applications interacting with OpenAI services. ```python os.environ["OPENAI_API_KEY"] = openai_api_key print("API keys have been set.") ``` -------------------------------- ### Redis Sorted Set Commands Source: https://github.com/sylphai-inc/adalflow/blob/main/notebooks/tutorials/adalflow_classification_optimization.ipynb Comprehensive documentation for Redis sorted set commands, including ZREM and ZRANGE. Provides details on parameters, return values, and usage examples. ```APIDOC ZREM key member [member ...] - Removes members from a sorted set - Parameters: - key: The sorted set key - member: Members to remove - Returns: Number of members removed ZRANGE key start stop [BYSCORE|BYLEX] [REV] [LIMIT offset count] [WITHSCORES] - Returns a range of members - Parameters: ... (Details omitted for brevity) ``` -------------------------------- ### Add Notebook for Tutorial Source: https://github.com/sylphai-inc/adalflow/blob/main/docs/source/contributor/contribution.rst Guidance on adding a new notebook for tutorials, use cases, or benchmarks, referencing the README in the notebooks directory. ```text For how to add a new notebook, please follow the `README.md `_ in the `notebooks` directory. ``` -------------------------------- ### Install AdalFlow and Setup Environment (Python) Source: https://github.com/sylphai-inc/adalflow/blob/main/notebooks/use_cases/adalflow_rag_optimization.ipynb Installs the AdalFlow package and clears the output, preparing the environment for subsequent operations. This is a common setup step in interactive environments like Jupyter notebooks. ```python from IPython.display import clear_output !pip install -U adalflow[openai,together] clear_output() ``` -------------------------------- ### Adalflow Training Function Source: https://github.com/sylphai-inc/adalflow/blob/main/notebooks/tutorials/adalflow_classification_optimization.ipynb The main training function that orchestrates the Adalflow process. It configures models, initializes the ADAL component and trainer, loads datasets, and starts the training loop. It includes error handling for the training process. ```python def train( model_client: adal.ModelClient, model_kwargs: Dict, train_batch_size=4, raw_shots: int = 0, bootstrap_shots: int = 1, max_steps=12, num_workers=4, strategy="constrained", optimization_order="sequential", debug=False, ): print("Starting training process...") # Define the model configuration for all components gpt_4o_model = { "model_client": OpenAIClient(), "model_kwargs": { "model": "gpt-4o-mini", "temperature": 1, "top_p": 0.99, "max_tokens": 1000, # "frequency_penalty": 1, # high for nto repeating prompt }, } print(f"Component model configuration: {gpt_4o_model}") try: print("Initializing ADAL component...") adal_component = TrecClassifierAdal( model_client=model_client, model_kwargs=model_kwargs, text_optimizer_model_config=gpt_4o_model, backward_engine_model_config=gpt_4o_model, teacher_model_config=gpt_4o_model, ) print("ADAL component initialized successfully") print("Initializing trainer...") trainer = adal.Trainer( train_batch_size=train_batch_size, adaltask=adal_component, strategy=strategy, max_steps=max_steps, num_workers=num_workers, raw_shots=raw_shots, bootstrap_shots=bootstrap_shots, debug=debug, weighted_sampling=True, optimization_order=optimization_order, exclude_input_fields_from_bootstrap_demos=True, ) print("Trainer initialized successfully") print("Loading datasets...") train_dataset, val_dataset, test_dataset = load_datasets() print( f"Datasets loaded - Train size: {len(train_dataset)}, Val size: {len(val_dataset)}, Test size: {len(test_dataset)}" ) print("Starting model training...") trainer.fit( train_dataset=train_dataset, val_dataset=val_dataset, test_dataset=test_dataset, debug=debug, ) print("Training completed successfully") except Exception as e: print(f"Error occurred: {str(e)}") raise ``` -------------------------------- ### Set Up AdalFlow Dev Environment with Poetry Source: https://github.com/sylphai-inc/adalflow/blob/main/docs/source/contributor/contribute_to_code.rst Navigates into the `adalflow` subdirectory, installs project dependencies using Poetry, and activates the virtual environment. This prepares the specific AdalFlow package environment. ```bash cd adalflow poetry install poetry shell ``` -------------------------------- ### Initialize ReActAgent with Tools and Models in Python Source: https://github.com/sylphai-inc/adalflow/blob/main/docs/source/tutorials/agent.rst This Python snippet shows the setup for testing the `ReActAgent`. It imports necessary components, defines sample tools (`multiply`, `add`, `divide`), configures model arguments for different LLMs (Groq's Llama3 and OpenAI's GPT-3.5), and prepares queries for testing. It also sets up a baseline comparison with a vanilla LLM. ```python from adalflow.components.agent import ReActAgent from adalflow.core import Generator, ModelClientType, ModelClient from adalflow.utils import setup_env setup_env() # Define tools def multiply(a: int, b: int) -> int: """ Multiply two numbers. """ return a * b def add(a: int, b: int) -> int: """ Add two numbers. """ return a + b def divide(a: float, b: float) -> float: """ Divide two numbers. """ return float(a) / b lama3_model_kwargs = { "model": "llama3-70b-8192", # llama3 70b works better than 8b here. "temperature": 0.0, } gpt_model_kwargs = { "model": "gpt-3.5-turbo", "temperature": 0.0, } def test_react_agent(model_client: ModelClient, model_kwargs: dict): tools = [multiply, add, divide] queries = [ "What is the capital of France? and what is 465 times 321 then add 95297 and then divide by 13.2?", "Give me 5 words rhyming with cool, and make a 4-sentence poem using them", ] # define a generator without tools for comparison generator = Generator( model_client=model_client, model_kwargs=model_kwargs, ) ``` -------------------------------- ### Groq LLM Client Initialization and Setup Source: https://github.com/sylphai-inc/adalflow/blob/main/docs/source/tutorials/model_client.rst Initializes the GroqAPIClient and sets up sample parameters including a prompt and model keyword arguments for API calls. ```python import asyncio import time from adalflow.components.model_client import ( GroqAPIClient, ) # Assuming GroqAPI with .call() and .acall() is available from adalflow.core.types import ModelType # Initialize the Groq client groq_client = GroqAPIClient() # Sample prompt for testing prompt = "Tell me a joke." model_kwargs = {"model": "llama3-8b-8192", "temperature": 0.5, "max_tokens": 100} ``` -------------------------------- ### Configure API Keys Source: https://github.com/sylphai-inc/adalflow/blob/main/docs/source/contributor/contribute_to_code.rst Copies the example environment file to `.env` and prompts the user to add necessary API keys. This step is crucial for running features that rely on external services. ```bash cp .env.example .env # example API keys: # OPENAI_API_KEY=YOUR_API_KEY_IF_YOU_USE_OPENAI # GROQ_API_KEY=YOUR_API_KEY_IF_YOU_USE_GROQ # ANTHROPIC_API_KEY=YOUR_API_KEY_IF_YOU_USE_ANTHROPIC # GOOGLE_API_KEY=YOUR_API_KEY_IF_YOU_USE_GOOGLE # COHERE_API_KEY=YOUR_API_KEY_IF_YOU_USE_COHERE # HF_TOKEN=YOUR_API_KEY_IF_YOU_USE_HF ``` -------------------------------- ### Install Poetry Source: https://github.com/sylphai-inc/adalflow/blob/main/docs/README.md Installs the Poetry dependency manager using pip. Poetry is required for managing project dependencies in AdalFlow. ```bash pip install poetry ``` -------------------------------- ### API Reference Configuration Example Source: https://github.com/sylphai-inc/adalflow/blob/main/docs/source/contributor/contribution.rst Example of how to add a new client to the API reference documentation by updating the Sphinx configuration file. ```text components.model_client.ollama_client ``` -------------------------------- ### Execute Basic Example Source: https://github.com/sylphai-inc/adalflow/blob/main/notebooks/tutorials/adalflow_dataclasses.ipynb Calls the `run_basic_example` function to execute the demonstration of the AdalFlow QA component with a Groq LLM. ```python run_basic_example() ``` -------------------------------- ### Install AdalFlow and Clear Output Source: https://github.com/sylphai-inc/adalflow/blob/main/notebooks/integration/sambanova_integration.ipynb Installs the AdalFlow library using pip and clears the output from the IPython environment. This is a common setup step for new projects. ```python from IPython.display import clear_output !pip install -U adalflow clear_output() ``` -------------------------------- ### Install Project Dependencies with Poetry Source: https://github.com/sylphai-inc/adalflow/blob/main/docs/README.md Installs all necessary project dependencies using the Poetry package manager. This command should be run from the root of the cloned repository. ```bash poetry install ``` -------------------------------- ### Start FastAPI Permission Server Source: https://github.com/sylphai-inc/adalflow/blob/main/docs/design/api_approval_examples.md Instructions to start the FastAPI permission server by running a test script and selecting an option for interactive API approval. ```bash python test_fastapi_permission.py # Select option 1 for interactive API approval ``` -------------------------------- ### Install Adalflow with OpenAI, Groq, and FAISS Source: https://github.com/sylphai-inc/adalflow/blob/main/notebooks/tutorials/adalflow_text_splitter.ipynb Installs the Adalflow library along with optional dependencies for OpenAI, Groq, and FAISS CPU support. This command is typically executed in a terminal or notebook environment to set up the necessary components. ```shell !pip install adalflow[openai,groq,faiss-cpu] ``` -------------------------------- ### Few-Shot Prompt Engineering Examples Source: https://github.com/sylphai-inc/adalflow/blob/main/use_cases/agent/react_agent_hotpot_qa.ipynb Demonstrates few-shot prompt engineering techniques using a series of question-answering examples. Each example includes a question, a step-by-step thought process, actions taken (like searching or looking up information), observations, and a final answer. These examples are designed to guide AI models through complex reasoning tasks. ```python examples = [ """Question: What is the elevation range for the area that the eastern sector of the Colorado orogeny extends into?\nThought 1: I need to search Colorado orogeny, find the area that the eastern sector of the Colorado orogeny extends into, then find the elevation range of the area.\nAction 1: search(\"Colorado orogeny\")\nObservation 1: The Colorado orogeny was an episode of mountain building (an orogeny) in Colorado and surrounding areas.\nThought 2: It does not mention the eastern sector. So I need to look up eastern sector.\nAction 2: lookup(\"eastern sector\")\nObservation 2: (Result 1 / 1) The eastern sector extends into the High Plains and is called the Central Plains orogeny.\nThought 3: The eastern sector of Colorado orogeny extends into the High Plains. So I need to search High Plains and find its elevation range.\nAction 3: search(\"High Plains\")\nObservation 3: High Plains refers to one of two distinct land regions:\nThought 4: I need to instead search High Plains (United States).\nAction 4: search(\"High Plains (United States)\")\nObservation 4: The High Plains are a subregion of the Great Plains. From east to west, the High Plains rise in elevation from around 1,800 to 7,000 ft (550 to 2,130 m).[3]\nThought 5: High Plains rise in elevation from around 1,800 to 7,000 ft, so the answer is 1,800 to 7,000 ft.\nAction 5: finish(\"1,800 to 7,000 ft\")""", """Question: Musician and satirist Allie Goertz wrote a song about the \"The Simpsons\" character Milhouse, who Matt Groening named after who?\nThought 1: The question simplifies to \"The Simpsons\" character Milhouse is named after who. I only need to search Milhouse and find who it is named after.\nAction 1: search(\"Milhouse\")\nObservation 1: Milhouse Mussolini Van Houten is a recurring character in the Fox animated television series The Simpsons voiced by Pamela Hayden and created by Matt Groening.\nThought 2: The paragraph does not tell who Milhouse is named after, maybe I can look up \"named after\".\nAction 2: lookup(\"named after\")\nObservation 2: (Result 1 / 1) Milhouse was named after U.S. president Richard Nixon, whose middle name was Milhous. \nThought 3: Milhouse was named after U.S. president Richard Nixon, so the answer is Richard Nixon.\nAction 3: finish(\"Richard Nixon\")""", """Question: Which documentary is about Finnish rock groups, Adam Clayton Powell or The Saimaa Gesture?\nThought 1: I need to search Adam Clayton Powell and The Saimaa Gesture, and find which documentary is about Finnish rock groups.\nAction 1: search(\"Adam Clayton Powell\")\nObservation 1: Could not find [\"Adam Clayton Powell\"]. Similar: [\'Adam Clayton Powell III\', \'Seventh Avenue (Manhattan)\', \'Adam Clayton Powell Jr. State Office Building\', \'Isabel Washington Powell\', \'Adam Powell\', \'Adam Clayton Powell (film)\', \'Giancarlo Esposito\'].\nThought 2: To find the documentary, I can search Adam Clayton Powell (film).\nAction 2: search(\"Adam Clayton Powell (film)\")\nObservation 2: Adam Clayton Powell is a 1989 American documentary film directed by Richard Kilberg.\nThe film is about the rise and fall of influential African-American politician Adam Clayton Powell Jr.[3][4] It was later aired as part of the PBS series The American Experience.\nThought 3: Adam Clayton Powell (film) is a documentary about an African-American politician, not Finnish rock groups. So the documentary about Finnish rock groups must instead be The Saimaa Gesture.\nAction 3: finish(\"The Saimaa Gesture\")""", """Question: What profession does Nicholas Ray and Elia Kazan have in common?\nThought 1: I need to search Nicholas Ray and Elia Kazan, find their professions, then find the profession they have in common.\nAction 1: search(\"Nicholas Ray\")\nObservation 1: Nicholas Ray (born Raymond Nicholas Kienzle Jr., August 7, 1911 – June 16, 1979) was an American film director, screenwriter, and actor best known for the 1955 film Rebel Without a Cause.\nThought 2: Professions of Nicholas Ray are director, screenwriter, and actor. I need to search Elia Kazan next and find his professions.\nAction 2: search(\"Elia Kazan\")\nObservation 2: Elia Kazan was an American film and theatre director, producer, screenwriter and actor.\nThought 3: Professions of Elia Kazan are director, producer, screenwriter, and actor. So profession Nicholas Ray and Elia Kazan have in common is director, screenwriter, and actor.\nAction 3: finish(\"director, screenwriter, actor\")""", """Question: Which magazine was started first Arthur's Magazine or First for Women?\nThought 1: I need to search Arthur's Magazine and First for Women, and find which was started first.\nAction 1: search(\"Arthur's Magazine\")\nObservation 1: Arthur's Magazine (1844-€“1846) was an American literary periodical published in Philadelphia in the 19th century. """ ] } ``` -------------------------------- ### Initialize and Load LocalDB Source: https://github.com/sylphai-inc/adalflow/blob/main/docs/source/tutorials/db.rst Demonstrates how to create an instance of the LocalDB class, load a list of items into it, and print the database's state before and after loading. ```python from adalflow.core.db import LocalDB dialog_turn_db = LocalDB('dialog_turns') print(dialog_turn_db) dialog_turn_db.load(dialog_turns) print(dialog_turn_db) ``` -------------------------------- ### Install AdalFlow and Clear Output in Python Source: https://github.com/sylphai-inc/adalflow/blob/main/notebooks/tutorials/adalflow_embedder.ipynb Installs the AdalFlow package and its dependencies using pip within a Python environment, followed by clearing the output. This is a common setup step in interactive notebooks. ```python from IPython.display import clear_output !pip install -U adalflow[openai,groq,faiss-cpu] clear_output() ``` -------------------------------- ### Instantiate and Call the QA Component Source: https://github.com/sylphai-inc/adalflow/blob/main/adalflow/README.md Demonstrates how to instantiate the QA component and call it with a query. Prints the component and the output of the query. ```python qa = QA() print(qa) # call output = qa("What is LLM?") print(output) ``` -------------------------------- ### Install Pandoc with Homebrew Source: https://github.com/sylphai-inc/adalflow/blob/main/docs/README.md Command to install the Pandoc document converter utility using the Homebrew package manager. Pandoc is used for converting between various markup formats, including Markdown and reStructuredText. ```bash brew install pandoc ``` -------------------------------- ### Create a Basic AdalFlow Agent and Runner Source: https://github.com/sylphai-inc/adalflow/blob/main/README.md Demonstrates creating a simple AdalFlow Agent with an OpenAI model client and running a prompt. It shows how to initialize an Agent and use a Runner to get a response, highlighting the basic interaction flow. ```python from adalflow import Agent, Runner from adalflow.components.model_client.openai_client import OpenAIClient # Create a simple agent agent = Agent( name="Assistant", model_client=OpenAIClient(), model_kwargs={"model": "gpt-4o", "temperature": 0.3} ) runner = Runner(agent=agent) result = runner.call(prompt_kwargs={"input_str": "Write a haiku about AI and coding"}) print(result.answer) ``` -------------------------------- ### Model Configuration Examples Source: https://github.com/sylphai-inc/adalflow/blob/main/docs/source/new_tutorials/agents_runner.md Demonstrates how to configure different language model clients, including OpenAI and Anthropic, along with their respective keyword arguments for model selection and parameters. ```python model_client = OpenAIClient() model_kwargs = {"model": "gpt-4o", "temperature": 0.7} ``` ```python from adalflow.components.model_client.anthropic_client import AnthropicAPIClient model_client = AnthropicAPIClient() model_kwargs = {"model": "claude-3-sonnet-20240229"} ``` -------------------------------- ### ReActAgent Initialization and Query Execution Source: https://github.com/sylphai-inc/adalflow/blob/main/docs/source/tutorials/agent.rst Demonstrates how to initialize a ReActAgent with specific parameters like max_steps and fallback options, and how to use it to process a list of queries. It shows the agent's response alongside a direct LLM response. ```python react = ReActAgent( max_steps=6, add_llm_as_fallback=True, tools=tools, model_client=model_client, model_kwargs=model_kwargs, ) # print(react) for query in queries: print(f"Query: {query}") agent_response = react.call(query) llm_response = generator.call(prompt_kwargs={"input_str": query}) print(f"Agent response: {agent_response}") print(f"LLM response: {llm_response}") print("") ``` -------------------------------- ### Example .gitignore Entry Source: https://github.com/sylphai-inc/adalflow/blob/main/docs/README.md Specifies files and directories that should be ignored by Git, preventing unnecessary or generated files from being committed to the repository. ```plaintext docs/build ``` -------------------------------- ### Instantiate and Run ChatBot Source: https://github.com/sylphai-inc/adalflow/blob/main/use_cases/question_answering/chatbot.ipynb Creates an instance of the ChatBot class and initiates the conversational loop by calling its `call` method. This starts the interactive chat session. ```python chatbot = ChatBot() print(chatbot) chatbot.call() ``` -------------------------------- ### Build Documentation with Sphinx-Build Source: https://github.com/sylphai-inc/adalflow/blob/main/docs/README.md Builds HTML documentation using the sphinx-build command, offering more control over build options like verbose output. ```bash sphinx-build -b html source build -v ``` -------------------------------- ### Configure httpx and anyio versions Source: https://github.com/sylphai-inc/adalflow/blob/main/notebooks/tutorials/adalflow_rag_playbook.ipynb Uninstalls existing httpx and anyio packages and installs specific compatible versions to resolve potential dependency conflicts. ```Python !pip uninstall httpx anyio -y !pip install "anyio>=3.1.0,<4.0" !pip install httpx==0.24.1 ``` -------------------------------- ### Set Up Root Dev Environment with Poetry Source: https://github.com/sylphai-inc/adalflow/blob/main/docs/source/contributor/contribute_to_code.rst Installs dependencies for the root directory using Poetry and activates the virtual environment. This ensures that use cases, tutorials, and benchmarks can utilize the development version of AdalFlow. ```bash poetry install poetry shell ``` -------------------------------- ### Securely Get API Keys Source: https://github.com/sylphai-inc/adalflow/blob/main/notebooks/tutorials/adalflow_rag_playbook.ipynb Prompts the user to securely enter their OpenAI and Groq API keys using the getpass function, which hides input. ```Python import os from getpass import getpass # Prompt user to enter their API keys securely openai_api_key = getpass("Please enter your OpenAI API key: ") groq_api_key = getpass("Please enter your GROQ API key: ") ``` -------------------------------- ### Initialize and Load LocalDB Source: https://github.com/sylphai-inc/adalflow/blob/main/tutorials/database.ipynb Shows how to initialize a `LocalDB` instance with a specified name and load data into it. The `LocalDB` is used for in-memory data management, tracking pipelines, and storage. ```python # Assuming LocalDB and dialog_turns are defined # from adalflow.core.db import LocalDB # dialog_turns: list # create a db for the dialog_turns dialog_turn_db = LocalDB("dialog_turns") print(dialog_turn_db) dialog_turn_db.load(dialog_turns) print(dialog_turn_db) ``` -------------------------------- ### Adalflow Function Expression and Parser Setup Source: https://github.com/sylphai-inc/adalflow/blob/main/docs/source/tutorials/tool_helper.rst Python code demonstrating how to create a `FunctionExpression` object using `FunctionExpression.from_function` and how to initialize a `JsonOutputParser` with this example for parsing LLM outputs. ```python example = FunctionExpression.from_function( func=add_points, p1=Point(x=1, y=2), p2=Point(x=3, y=4) ) func_parser = JsonOutputParser( data_class=FunctionExpression, examples=[example] ) ``` -------------------------------- ### Initialize OpenAI Client and Prompt Source: https://github.com/sylphai-inc/adalflow/blob/main/docs/source/tutorials/model_client.rst Sets up the necessary components for benchmarking OpenAI API calls. This includes initializing the `OpenAIClient`, defining a sample prompt, and specifying model arguments like model name, temperature, and max tokens. ```python # Initialize the OpenAI client openai_client = OpenAIClient() # Sample prompt for testing prompt = "Tell me a joke." model_kwargs = {"model": "gpt-3.5-turbo", "temperature": 0.5, "max_tokens": 100} ``` -------------------------------- ### AdalFlow Training Run Output Files Source: https://github.com/sylphai-inc/adalflow/blob/main/docs/source/use_cases/question_answering.rst Lists example filenames for training run outputs, categorized by strategy (random, constrained) and including identifiers for the run and configuration. These files are typically saved in the `.adalflow/ckpt/` directory. ```bash .adalflow/ ├── ckpt/ │ └── ObjectCountAdalComponent/ │ random_max_steps_8_bb908_run_1.json # The last training run for random strategy │ constrained_max_steps_8_a1754_run_1.json # The last training run for constrained strategy ```