### Installing Python Dependencies Source: https://github.com/the-pocket/tutorial-codebase-knowledge/blob/main/README.md Installs the required Python packages listed in the `requirements.txt` file. This is a standard step for setting up a Python project. ```bash pip install -r requirements.txt ``` -------------------------------- ### Verifying LLM Setup Source: https://github.com/the-pocket/tutorial-codebase-knowledge/blob/main/README.md Runs the `utils/call_llm.py` script to test if the Language Model setup is correct and functional. This helps confirm that the API key and client initialization are working as expected. ```bash python utils/call_llm.py ``` -------------------------------- ### Basic MCP Server Implementation Source: https://github.com/the-pocket/tutorial-codebase-knowledge/blob/main/docs/MCP Python SDK/01_cli___mcp__command_.md Minimal example of a FastMCP server implementation showing basic server setup and execution ```python # We'll learn about FastMCP in the next chapter! # For now, just know this creates a basic server. from mcp.server.fastmcp import FastMCP # Create an instance of our server server = FastMCP(name="MyFirstServer") # This is a standard Python check to make sure # the script is being run directly if __name__ == "__main__": # Tell the server to start running print("Starting MyFirstServer...") server.run() print("MyFirstServer finished.") # You might not see this if the server runs forever ``` -------------------------------- ### Initializing Gemini AI Client Source: https://github.com/the-pocket/tutorial-codebase-knowledge/blob/main/README.md Initializes the `genai.Client` object using an API key. It attempts to get the key from the `GEMINI_API_KEY` environment variable, falling back to a placeholder if not found. This sets up the connection to the Gemini AI service. ```python client = genai.Client( api_key=os.getenv("GEMINI_API_KEY", "your-api_key") ) ``` -------------------------------- ### Celery Worker Startup Banner Output Source: https://github.com/the-pocket/tutorial-codebase-knowledge/blob/main/docs/Celery/05_worker.md Example console output when starting a Celery worker, showing configuration details including transport settings, concurrency level, and registered tasks. Demonstrates successful worker initialization and broker connection. ```text -------------- celery@yourhostname v5.x.x (stars) --- ***** ----- -- ******* ---- Linux-5.15.0...-generic-x86_64-with-... 2023-10-27 10:00:00 - *** --- * --- - ** ---------- [config] - ** ---------- .> app: tasks:0x7f... - ** ---------- .> transport: redis://localhost:6379/0 - ** ---------- .> results: redis://localhost:6379/0 - *** --- * --- .> concurrency: 8 (prefork) -- ******* ---- .> task events: OFF (enable -E to monitor tasks in this worker) --- ***** ----- -------------- [queues] .> celery exchange=celery(direct) key=celery [tasks] . tasks.add . tasks.send_welcome_email [2023-10-27 10:00:01,000: INFO/MainProcess] Connected to redis://localhost:6379/0 [2023-10-27 10:00:01,050: INFO/MainProcess] mingle: searching for neighbors [2023-10-27 10:00:02,100: INFO/MainProcess] mingle: all alone [2023-10-27 10:00:02,150: INFO/MainProcess] celery@yourhostname ready. ``` -------------------------------- ### Generating Tutorial in Chinese Source: https://github.com/the-pocket/tutorial-codebase-knowledge/blob/main/README.md Runs the main script (`main.py`) to analyze a GitHub repository and generate the codebase tutorial specifically in the Chinese language using the `--language` flag. ```bash python main.py --repo https://github.com/username/repo --language "Chinese" ``` -------------------------------- ### Implementing Basic MCP Client Using ClientSession Source: https://github.com/the-pocket/tutorial-codebase-knowledge/blob/main/docs/MCP Python SDK/08_client_server_sessions___clientsession____serversession__.md Example demonstrating how to create a client application that connects to an MCP server, performs initialization handshake, and executes a tool call. Shows core session lifecycle management and error handling patterns. ```python # --- Conceptual Client Code --- import anyio from mcp.client.session import ClientSession # Assume we have transport streams (read_stream, write_stream) # connected to the CalculatorServer (more in Chapter 9) async def run_client(): # 1. Create a ClientSession using the transport streams async with ClientSession(read_stream, write_stream) as session: try: # 2. Perform the initialization handshake init_result = await session.initialize() print(f"Connected to: {init_result.serverInfo.name}") # 3. Send a 'callTool' request using the session tool_result = await session.call_tool( name="add", arguments={"num1": 15, "num2": 27} ) # 4. Process the result (session handled matching response) # Assuming the result is simple text content if tool_result.content and tool_result.content[0].type == 'text': print(f"Server calculated: {tool_result.content[0].text}") # Expected: 42 except Exception as e: print(f"An error occurred: {e}") # In a real script, you'd set up the transport and run this async function # anyio.run(run_client) ``` -------------------------------- ### Implementing ToolAgent Execution Source: https://github.com/the-pocket/tutorial-codebase-knowledge/blob/main/docs/AutoGen Core/04_tool.md Complete example showing how to create and use a ToolAgent to execute tool requests and handle results. ```python import asyncio from autogen_core.tool_agent import ToolAgent from autogen_core.models import FunctionExecutionResult from create_date_tool import date_tool from tool_call_request import date_call_request tool_executor = ToolAgent( description="I can execute tools like getting the date.", tools=[date_tool] ) async def simulate_execution(): class MockContext: cancellation_token = None ctx = MockContext() print(f"ToolAgent received request: {date_call_request.name}") result: FunctionExecutionResult = await tool_executor.handle_function_call( message=date_call_request, ctx=ctx ) print(f"ToolAgent produced result: {result}") asyncio.run(simulate_execution()) ``` -------------------------------- ### Example Uvicorn Server Startup Output in Bash Source: https://github.com/the-pocket/tutorial-codebase-knowledge/blob/main/docs/FastAPI/01_fastapi_application___routing.md This snippet shows typical output in the terminal when Uvicorn successfully starts the FastAPI application. It indicates the server is running, the address (defaulting to http://127.0.0.1:8000), and that the reloader process is active. ```bash INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) INFO: Started reloader process [xxxxx] using StatReload INFO: Started server process [xxxxx] INFO: Waiting for application startup. INFO: Application startup complete. ``` -------------------------------- ### Asking Questions to an LLM with OpenManus Source: https://github.com/the-pocket/tutorial-codebase-knowledge/blob/main/docs/OpenManus/01_llm.md Demonstrates how to create an LLM interface, prepare a message containing a question, and asynchronously receive a response from the language model. This example shows the direct use of the LLM class, though usually this is handled by the agent automatically. ```python # Import necessary classes from app.llm import LLM from app.schema import Message import asyncio # Needed to run asynchronous code # Assume configuration is already loaded (API keys, model name, etc.) # Create an instance of the LLM class (using default settings) llm_interface = LLM() # Prepare the question as a list of messages # (We'll learn more about Messages in Chapter 2) conversation = [ Message.user_message("What is the capital of France?") ] # Define an async function to ask the question async def ask_question(): print("Asking the LLM...") # Use the 'ask' method to send the conversation response = await llm_interface.ask(messages=conversation) print(f"LLM Response: {response}") # Run the async function asyncio.run(ask_question()) ``` -------------------------------- ### Installing FastAPI and Uvicorn using pip in Bash Source: https://github.com/the-pocket/tutorial-codebase-knowledge/blob/main/docs/FastAPI/01_fastapi_application___routing.md This command uses the pip package installer to install the necessary libraries for running a FastAPI application. It installs `fastapi` itself and `uvicorn` along with its standard dependencies, which include libraries for parsing and serving web requests. ```bash pip install fastapi uvicorn[standard] ``` -------------------------------- ### Example LLM Response Output Source: https://github.com/the-pocket/tutorial-codebase-knowledge/blob/main/docs/OpenManus/01_llm.md Shows the expected console output when running the LLM query example. The response is a simple answer to the question about France's capital. ```plaintext Asking the LLM... LLM Response: The capital of France is Paris. ``` -------------------------------- ### Example Prompt Format for Completion Language Models Source: https://github.com/the-pocket/tutorial-codebase-knowledge/blob/main/docs/DSPy/09_adapter.md Illustrates the typical single-string prompt format expected by older completion-based Language Models (like GPT-3 davinci). This format combines instructions, field definitions, and the specific input instance into one text block, ending where the model should start its generation. The `${text}` and `${summary}` placeholders represent where DSPy would insert the input text and where the model should generate the output, respectively. ```text Summarize the given text. --- Follow the following format. Text: ${text} Summary: ${summary} --- Text: DSPy is a framework for programming foundation models... Summary: ``` -------------------------------- ### Analyzing GitHub Repository Source: https://github.com/the-pocket/tutorial-codebase-knowledge/blob/main/README.md Executes the main script (`main.py`) to analyze a specified GitHub repository. It includes options to filter files by patterns (`--include`, `--exclude`) and set a maximum file size (`--max-size`). ```bash python main.py --repo https://github.com/username/repo --include "*.py" "*.js" --exclude "tests/*" --max-size 50000 ``` -------------------------------- ### Analyzing Local Directory Source: https://github.com/the-pocket/tutorial-codebase-knowledge/blob/main/README.md Executes the main script (`main.py`) to analyze a local codebase directory. It allows specifying include and exclude patterns for files. ```bash python main.py --dir /path/to/your/codebase --include "*.py" --exclude "*test*" ``` -------------------------------- ### Implementing Calculator Server with FastMCP Tools Source: https://github.com/the-pocket/tutorial-codebase-knowledge/blob/main/docs/MCP Python SDK/04_fastmcp_tools___tool____toolmanager__.md Example of creating a FastMCP server that exposes an addition tool. Demonstrates tool registration using @server.tool decorator, type hints for parameter validation, and basic server setup. The tool accepts two integers and returns their sum. ```python # 1. Import FastMCP from mcp.server.fastmcp import FastMCP # 2. Create the server instance server = FastMCP(name="CalculatorServer") # 3. Use the @server.tool() decorator to define our tool @server.tool(name="add", description="Adds two numbers together.") def add_numbers(num1: int, num2: int) -> int: """ This function is registered as the 'add' tool. 'num1: int' and 'num2: int' tell FastMCP the tool expects two integer arguments named 'num1' and 'num2'. '-> int' tells FastMCP the tool will return an integer. """ print(f"Tool 'add' called with {num1} and {num2}") # Server-side log # 4. The function's logic performs the action result = num1 + num2 print(f"Returning result: {result}") return result # 5. Standard run block if __name__ == "__main__": print(f"Starting {server.name}...") server.run() # Start listening print(f"{server.name} finished.") ``` -------------------------------- ### OpenManus Configuration File Example in TOML Source: https://github.com/the-pocket/tutorial-codebase-knowledge/blob/main/docs/OpenManus/07_configuration__config_.md A simplified example of the config.toml file which defines settings for different components of the OpenManus application including LLM, sandbox, search, and browser configurations. ```toml # config/config.toml (Simplified Example) [llm] # Settings for the Large Language Model model = "gpt-4o" api_key = "YOUR_OPENAI_API_KEY_HERE" # Replace with your actual key base_url = "https://api.openai.com/v1" api_type = "openai" [sandbox] # Settings for the code execution sandbox use_sandbox = true image = "python:3.12-slim" memory_limit = "256m" [search_config] # Settings for web search engine = "DuckDuckGo" [browser_config] # Settings for the browser tool headless = false ``` -------------------------------- ### Initializing Basic FastMCP Server Source: https://github.com/the-pocket/tutorial-codebase-knowledge/blob/main/docs/MCP Python SDK/02_fastmcp_server___fastmcp__.md Demonstrates the minimum code required to create a FastMCP server. Shows server instantiation, naming, and basic startup logic. ```python # 1. Import the FastMCP class from mcp.server.fastmcp import FastMCP # 2. Create an instance of the FastMCP server # Give it a name clients might see. # Optionally, provide general instructions. server = FastMCP( name="MySimpleServer", instructions="This is a very simple example server." ) # 3. Add the standard Python block to run the server # when the script is executed directly. if __name__ == "__main__": print(f"Starting {server.name}...") # This tells FastMCP to start listening for connections server.run() print(f"{server.name} finished.") # Usually only seen after stopping (Ctrl+C) ``` -------------------------------- ### Starting Celery Worker from Command Line Source: https://github.com/the-pocket/tutorial-codebase-knowledge/blob/main/docs/Celery/05_worker.md Command to start a Celery worker process with basic configuration. Requires celery_app.py and tasks.py files, plus a running message broker. Sets logging level to info for monitoring task execution. ```bash celery -A celery_app worker --loglevel=info ``` -------------------------------- ### Creating Global Instructions for Codex Source: https://github.com/the-pocket/tutorial-codebase-knowledge/blob/main/docs/Codex/07_configuration_management.md Example Markdown file for global instructions that apply to all Codex runs. These instructions provide general guidelines for how the AI should respond, including a preference for step-by-step explanations, Python usage, and emoji inclusion. ```markdown # File: ~/.codex/instructions.md - Always explain your reasoning step-by-step before suggesting code or commands. - Prefer using Python for scripting tasks unless otherwise specified. - Use emojis in your responses! 🎉 ``` -------------------------------- ### Version Check Command Source: https://github.com/the-pocket/tutorial-codebase-knowledge/blob/main/docs/MCP Python SDK/01_cli___mcp__command_.md Command to verify MCP SDK installation and display version number ```bash mcp version ``` -------------------------------- ### Providing a Few-Shot Example to a DSPy Module in Python Source: https://github.com/the-pocket/tutorial-codebase-knowledge/blob/main/docs/DSPy/09_adapter.md Shows how to create a `dspy.Example` object containing a sample input (`text`) and its corresponding desired output (`summary`) to serve as a few-shot demonstration. The `.with_inputs("text")` method specifies which fields are inputs. This `demo` is then passed along with the actual input `long_text` when calling the `summarizer` module, potentially improving the LM's output quality by providing context. Requires the `dspy` library. ```python # Demo example demo = dspy.Example( text="Long article about cats.", summary="Cats are popular pets." ).with_inputs("text") # Call the summarizer with the demo result = summarizer(text=long_text, demos=[demo]) ``` -------------------------------- ### Implementing Current Date Function Tool Source: https://github.com/the-pocket/tutorial-codebase-knowledge/blob/main/docs/AutoGen Core/04_tool.md Basic Python function implementation to get the current date, which will be wrapped as a Tool. ```python import datetime def get_current_date() -> str: """Fetches the current date as a string.""" today = datetime.date.today() return today.isoformat() # Returns date like "2023-10-27" # Test the function print(f"Function output: {get_current_date()}") ``` -------------------------------- ### Simple Database Update Operations Source: https://github.com/the-pocket/tutorial-codebase-knowledge/blob/main/docs/LevelDB/05_writebatch.md Example showing basic database operations without atomic guarantees, demonstrating the potential consistency issues that can arise. ```text // Goal: Increase playerA score, decrease playerB score db->Put(options, "score_playerA", "101"); db->Put(options, "score_playerB", "49"); ``` -------------------------------- ### Example LLM Tool Parameter Output in JSON Source: https://github.com/the-pocket/tutorial-codebase-knowledge/blob/main/docs/OpenManus/04_tool___toolcollection.md This JSON snippet shows an example of the formatted output for a tool's parameters as provided to an LLM. It includes the tool's name, description, and required parameters. ```json { "type": "function", "function": { "name": "echo_message", "description": "Repeats back the text provided in the 'message' parameter.", "parameters": { "type": "object", "properties": { "message": { "type": "string", "description": "The text to be echoed back." } }, "required": [ "message" ] } } } ``` -------------------------------- ### Creating Basic FastMCP Resource Server - Initial Version Source: https://github.com/the-pocket/tutorial-codebase-knowledge/blob/main/docs/MCP Python SDK/03_fastmcp_resources___resource____resourcemanager__.md Demonstrates setting up a basic FastMCP server with a static welcome message resource. Shows initial implementation with separate getter function. ```python # 1. Import FastMCP from mcp.server.fastmcp import FastMCP # 2. Create the server instance server = FastMCP(name="LibraryServer") # 3. Define a function that returns our static data def get_welcome_message() -> str: """Returns a simple welcome string.""" return "Welcome to the Library Server!" # 4. Use the @server.resource() decorator to register the function's result # The URI "data://greeting" will be used by clients to access this. @server.resource(uri="data://greeting", description="A friendly greeting.") def welcome_resource(): # This function will be called *when a client reads* the resource. # It just returns the static message. return get_welcome_message() # Or simply: return "Welcome..." # Standard run block if __name__ == "__main__": print(f"Starting {server.name}...") server.run() print(f"{server.name} finished.") ``` -------------------------------- ### Supplying Few-Shot Examples to dspy.Predict in Python Source: https://github.com/the-pocket/tutorial-codebase-knowledge/blob/main/docs/DSPy/04_predict.md This snippet illustrates few-shot learning by constructing dspy.Example objects and passing them as demos to the Predict module. Dependencies: dspy and the earlier TranslateToFrench signature. Each example provides paired inputs/outputs to guide the LM. The code invokes the predictor with both the target input and the demos list, encouraging better LM response formatting. Inputs: input sentence, list of examples; Output: prediction object with the translated text. ```python # Create some example translations (from Chapter 3) demo1 = dspy.Example(english_sentence="Good morning!", french_sentence="Bonjour!") demo2 = dspy.Example(english_sentence="Thank you.", french_sentence="Merci.") # Our translator module (same as before) translator = dspy.Predict(TranslateToFrench) # Input we want to translate english_input = "See you later." # Call the predictor, this time providing demos result_with_demos = translator( english_sentence=english_input, demos=[demo1, demo2] # Pass our examples here! ) print(f"English: {english_input}") print(f"French (with demos): {result_with_demos.french_sentence}") ``` -------------------------------- ### Atomic Operations Using WriteBatch in LevelDB Source: https://github.com/the-pocket/tutorial-codebase-knowledge/blob/main/docs/LevelDB/05_writebatch.md Complete example demonstrating how to use WriteBatch to perform multiple operations atomically, including error handling and durability options. ```c++ #include "leveldb/write_batch.h" #include "leveldb/db.h" // ... assume db is an open LevelDB database ... leveldb::WriteOptions write_options; write_options.sync = true; // Ensure durability // 1. Create an empty WriteBatch leveldb::WriteBatch batch; // 2. Add changes to the batch (in memory) batch.Put("score_playerA", "101"); // Add 'Put playerA' to the list batch.Delete("old_temp_key"); // Add 'Delete old_temp_key' to the list batch.Put("score_playerB", "49"); // Add 'Put playerB' to the list // 3. Apply the entire batch atomically leveldb::Status status = db->Write(write_options, &batch); if (status.ok()) { // Success! Both score_playerA and score_playerB are updated, // and old_temp_key is deleted. } else { // Failure! The database state is unchanged. Neither score was updated, // and old_temp_key was not deleted. } ``` -------------------------------- ### Basic Celery App Configuration with Direct Parameters Source: https://github.com/the-pocket/tutorial-codebase-knowledge/blob/main/docs/Celery/02_configuration.md Creating a Celery app instance with broker and backend parameters passed directly to the constructor. This is the simplest approach for basic configurations. ```python # From Chapter 1 from celery import Celery app = Celery('tasks', broker='redis://localhost:6379/0', backend='redis://localhost:6379/0') ``` -------------------------------- ### Configuring AsyncWebCrawler with CrawlerRunConfig in Python Source: https://github.com/the-pocket/tutorial-codebase-knowledge/blob/main/docs/Crawl4AI/02_asyncwebcrawler.md Shows how to customize the behavior of AsyncWebCrawler for a specific crawl operation using CrawlerRunConfig. This example demonstrates setting the cache mode to bypass for fresh content fetching. ```python # chapter2_example_2.py import asyncio from crawl4ai import AsyncWebCrawler from crawl4ai import CrawlerRunConfig # Import configuration class from crawl4ai import CacheMode # Import cache options async def main(): async with AsyncWebCrawler() as crawler: print("Crawler is ready!") url_to_crawl = "https://httpbin.org/html" # Create a specific configuration for this run # Tell the crawler to BYPASS the cache (fetch fresh) run_config = CrawlerRunConfig( cache_mode=CacheMode.BYPASS ) print("Configuration: Bypass cache for this run.") # Pass the config object to the arun method result = await crawler.arun( url=url_to_crawl, config=run_config # Pass the specific instructions ) if result.success: print("\nSuccess! Crawler got fresh content (cache bypassed).") print(f"Page Title: {result.metadata.get('title', 'N/A')}") else: print(f"\nFailed to crawl: {result.error_message}") if __name__ == "__main__": asyncio.run(main()) ``` -------------------------------- ### NumPy Core Module Imports and Setup Source: https://github.com/the-pocket/tutorial-codebase-knowledge/blob/main/docs/NumPy Core/06_multiarray_module.md Simplified example of how NumPy's core module initializes and exposes functionality from the multiarray and umath modules, showing the import hierarchy that makes NumPy functions available. ```python # From numpy/core/numeric.py - Simplified from . import multiarray # Imports numpy/core/multiarray.py # multiarray.py itself imports from _multiarray_umath from .multiarray import ( array, asarray, zeros, empty, # Functions defined/re-exported # ... many others ... ) ``` -------------------------------- ### Conceptual Output of ChatAdapter Formatting for Chat Models Source: https://github.com/the-pocket/tutorial-codebase-knowledge/blob/main/docs/DSPy/09_adapter.md Illustrates the conceptual list of messages produced by the `ChatAdapter.format()` method when given a Signature, a demo example, and an input. It shows how instructions become the system message, the demo is split into user and assistant turns, and the final input forms another user turn. Note the use of specific field markers like `[[ ## field_name ## ]]` (mentioned in text) within the content to aid parsing later. This structure is sent to the chat LM. ```python # Conceptual Output of ChatAdapter.format() [ # 1. System message from Signature instructions {"role": "system", "content": "Summarize the given text.\n\n---\n\nFollow the following format.\n\nText: ${text}\nSummary: ${summary}\n\n---\n\n"}, # 2. User turn for the demo input {"role": "user", "content": "Text: Long article about cats.\nSummary:"}, # 3. Assistant turn for the demo output {"role": "assistant", "content": "Summary: Cats are popular pets."}, # (Might use special markers like [[ ## Summary ## ]]) # 4. User turn for the actual input {"role": "user", "content": "Text: DSPy is a framework for programming foundation models...\nSummary:"} ] ``` -------------------------------- ### Validating Entire Models with @model_validator in Python Source: https://github.com/the-pocket/tutorial-codebase-knowledge/blob/main/docs/Pydantic Core/04_custom_logic__decorators___annotated_helpers_.md Shows how to use the @model_validator decorator to implement validation logic that involves multiple fields in a Pydantic model. The example ensures that an end date is after a start date. ```python from datetime import date from pydantic import BaseModel, model_validator, ValidationError from typing import Self # Used for type hint in Python 3.11+ class Trip(BaseModel): start_date: date end_date: date destination: str # This method runs AFTER the model fields are validated individually @model_validator(mode='after') def check_dates(self) -> Self: # Use 'Self' or 'Trip' as return hint print(f"Checking dates: start={self.start_date}, end={self.end_date}") if self.start_date >= self.end_date: raise ValueError('End date must be after start date') # Return the validated model instance return self # --- Try it out --- # Valid dates trip_ok = Trip(start_date=date(2024, 7, 1), end_date=date(2024, 7, 10), destination='Beach') print(f"Valid trip: {trip_ok}") # Expected Output: # Checking dates: start=2024-07-01, end=2024-07-10 # Valid trip: start_date=datetime.date(2024, 7, 1) end_date=datetime.date(2024, 7, 10) destination='Beach' # Invalid dates try: Trip(start_date=date(2024, 7, 10), end_date=date(2024, 7, 1), destination='Mountains') except ValidationError as e: print(f"\nValidation Error:\n{e}") # Expected Output (simplified): # Checking dates: start=2024-07-10, end=2024-07-01 # Validation Error: # 1 validation error for Trip # Value error, End date must be after start date [type=value_error, ...] ``` -------------------------------- ### Implementing a Basic Agent for Browser Automation in Python Source: https://github.com/the-pocket/tutorial-codebase-knowledge/blob/main/docs/Browser Use/01_agent.md A simplified example demonstrating how to set up and use an Agent to perform an automated web task. The code initializes all necessary components (Browser, Controller, BrowserContext), creates an Agent instance, and runs it to execute a search task, with proper error handling and cleanup. ```python # --- Simplified Example --- # We need to import the necessary parts from the browser_use library from browser_use import Agent, Browser, Controller, BrowserConfig, BrowserContextConfig # Assume 'my_llm' is your configured Large Language Model (e.g., from OpenAI, Anthropic) from my_llm_setup import my_llm # Placeholder for your specific LLM setup # 1. Define the task for the Agent my_task = "Go to google.com, search for 'cute cat pictures', and click the first image result." # 2. Basic browser configuration (we'll learn more later) browser_config = BrowserConfig() # Default settings context_config = BrowserContextConfig() # Default settings # 3. Initialize the components the Agent needs # The Browser manages the underlying browser application browser = Browser(config=browser_config) # The Controller knows *how* to perform actions like 'click' or 'type' controller = Controller() async def main(): # The BrowserContext represents a single browser tab/window environment # It uses the Browser and its configuration async with BrowserContext(browser=browser, config=context_config) as browser_context: # 4. Create the Agent instance! agent = Agent( task=my_task, llm=my_llm, # The "brain" - the Language Model browser_context=browser_context, # The "eyes" - interacts with the browser tab controller=controller # The "hands" - executes actions # Many other settings can be configured here! ) print(f"Agent created. Starting task: {my_task}") # 5. Run the Agent! This starts the loop. # It will keep taking steps until the task is done or it hits the limit. history = await agent.run(max_steps=15) # Limit steps for safety # 6. Check the result if history.is_done() and history.is_successful(): print("✅ Agent finished the task successfully!") print(f"Final message from agent: {history.final_result()}") else: print("⚠️ Agent stopped. Maybe max_steps reached or task wasn't completed successfully.") # The 'async with' block automatically cleans up the browser_context await browser.close() # Close the browser application # Run the asynchronous function import asyncio asyncio.run(main()) ``` -------------------------------- ### Visualizing Click Framework Architecture with Mermaid Source: https://github.com/the-pocket/tutorial-codebase-knowledge/blob/main/docs/Click/index.md A flowchart diagram showing the relationships between key Click components including Context, Commands, Parameters, ParamType, Decorators, Terminal UI, and Exceptions. It illustrates how decorators configure commands and parameters, how context manages execution, and how components interact for validation and user interaction. ```mermaid flowchart TD A0["Context"] A1["Command / Group"] A2["Parameter (Option / Argument)"] A3["ParamType"] A4["Decorators"] A5["Term UI (Terminal User Interface)"] A6["Click Exceptions"] A4 -- "Creates/Configures" --> A1 A4 -- "Creates/Configures" --> A2 A0 -- "Manages execution of" --> A1 A0 -- "Holds parsed values for" --> A2 A2 -- "Uses for validation/conversion" --> A3 A3 -- "Raises on conversion error" --> A6 A1 -- "Uses for user interaction" --> A5 A0 -- "Handles/Raises" --> A6 A4 -- "Injects via @pass_context" --> A0 ``` -------------------------------- ### Celery Worker Task Execution Log Source: https://github.com/the-pocket/tutorial-codebase-knowledge/blob/main/docs/Celery/05_worker.md Example log output showing task execution progress including task receipt, execution, and completion with timing information. Demonstrates the worker's logging of task processing steps. ```text [2023-10-27 10:05:00,100: INFO/ForkPoolWorker-1] Task tasks.add[some-task-id] received Task 'add' starting with (5, 7) Task 'add' finished with result: 12 [2023-10-27 10:05:05,150: INFO/ForkPoolWorker-1] Task tasks.add[some-task-id] succeeded in 5.05s: 12 ``` -------------------------------- ### LLM Class Initialization Using Config Source: https://github.com/the-pocket/tutorial-codebase-knowledge/blob/main/docs/OpenManus/07_configuration__config_.md A simplified example of how the LLM class in OpenManus uses the Config system to obtain its settings during initialization, demonstrating the practical application of the configuration system. ```python # Simplified snippet from app/llm.py __init__ method from app.config import config, LLMSettings # Import config and the schema from typing import Optional class LLM: # ... other methods ... def __init__(self, config_name: str = "default", llm_config: Optional[LLMSettings] = None): # If specific llm_config isn't provided, get it from the global config if llm_config is None: # Ask the global 'config' object for the settings # corresponding to 'config_name' (e.g., "default") llm_settings = config.llm.get(config_name) if not llm_settings: # Handle case where the name doesn't exist llm_settings = config.llm.get("default") # Fallback to default else: # Use the provided config if given llm_settings = llm_config # Store the settings read from the config object self.model = llm_settings.model self.api_key = llm_settings.api_key self.base_url = llm_settings.base_url # ... store other settings like max_tokens, temperature ... print(f"LLM initialized with model: {self.model}") # Initialize the actual API client using these settings # self.client = AsyncOpenAI(api_key=self.api_key, base_url=self.base_url) # ... rest of initialization ... ``` -------------------------------- ### NumPy Array Print Output Examples - Python Source: https://github.com/the-pocket/tutorial-codebase-knowledge/blob/main/docs/NumPy Core/05_array_printing___arrayprint__.md This snippet shows example outputs when printing a NumPy array under different print option settings. It exemplifies the effects of changing threshold and precision, as well as summarization options, on the multiline string representation of arrays. The arrays illustrated contain random floating-point numbers, and the output demonstrates formatting differences like precision, line breaks, and the presence of ellipses for summarized content. ```python --- Setting threshold globally --- [[992.84337197 931.73648142 119.68616987 ... 305.61919366 516.97897205 707.69140878] [507.45895986 253.00740626 739.97091378 ... 755.69943511 813.11931119 19.84654589] [941.25264871 689.43209981 820.11954711 ... 709.83933545 192.49837505 609.30358618] ... [498.86686503 872.79555956 401.19333028 ... 552.97492858 303.59379464 308.61881807] [797.51920685 427.86020151 783.2019203 ... 511.63382762 322.52764881 778.22766019] [ 54.84391309 938.24403397 796.7431406 ... 495.90873227 267.16620292 409.51491904]] --- Setting precision temporarily --- [[992.84 931.74 119.69 ... 305.62 516.98 707.69] [507.46 253.01 739.97 ... 755.7 813.12 19.85] [941.25 689.43 820.12 ... 709.84 192.5 609.3 ] ... [498.87 872.8 401.19 ... 552.97 303.59 308.62] [797.52 427.86 783.2 ... 511.63 322.53 778.23] [ 54.84 938.24 796.74 ... 495.91 267.17 409.51]] --- Back to default precision --- [[992.84337197 931.73648142 119.68616987 ... 305.61919366 516.97897205 707.69140878] [507.45895986 253.00740626 739.97091378 ... 755.69943511 813.11931119 19.84654589] [941.25264871 689.43209981 820.11954711 ... 709.83933545 192.49837505 609.30358618] ... [498.86686503 872.79555956 401.19333028 ... 552.97492858 303.59379464 308.61881807] [797.51920685 427.86020151 783.2019203 ... 511.63382762 322.52764881 778.22766019] [ 54.84391309 938.24403397 796.7431406 ... 495.90873227 267.16620292 409.51491904]] --- Using array2string with summarization off --- [[992.8 931.7 119.7 922. 912.2 156.5 459.4 305.6 517. 707.7] [507.5 253. 740. 640.3 420.3 652.1 197. 755.7 813.1 19.8] [941.3 689.4 820.1 125.8 598.2 219.3 466.7 709.8 192.5 609.3] [ 32. 855.2 362.1 434.9 133.5 148.1 522.6 725.1 395.5 377.9] [332.7 782.2 587.3 320.3 905.5 412.8 378. 911.9 972.1 400.2] ... ``` -------------------------------- ### Creating a Simple Command with Click in Python Source: https://github.com/the-pocket/tutorial-codebase-knowledge/blob/main/docs/Click/01_command___group.md Demonstrates how to create a basic 'Hello World' command using Click. The code imports Click, defines a command function decorated with @click.command(), and includes a docstring for automatic help text generation. ```python # hello_app.py import click @click.command() def hello(): """A simple command that says Hello World""" print("Hello World!") if __name__ == '__main__': hello() ``` -------------------------------- ### Using the Config Singleton to Access Settings Source: https://github.com/the-pocket/tutorial-codebase-knowledge/blob/main/docs/OpenManus/07_configuration__config_.md Example of how different parts of OpenManus can access configuration settings through the singleton Config instance, demonstrating access to LLM, sandbox, search, and browser settings. ```python # Example of how another part of the code might use the config from app.config import config # Import the singleton instance # Access LLM settings default_llm_settings = config.llm.get("default") # Get the 'default' LLM config if default_llm_settings: model_name = default_llm_settings.model api_key = default_llm_settings.api_key print(f"LLM Model: {model_name}") # Don't print the API key in real code! This is just for illustration. # print(f"LLM API Key: {api_key[:4]}...{api_key[-4:]}") # Access Sandbox settings use_sandbox_flag = config.sandbox.use_sandbox sandbox_image = config.sandbox.image print(f"Use Sandbox: {use_sandbox_flag}") print(f"Sandbox Image: {sandbox_image}") # Access Search settings (check if it exists) if config.search_config: search_engine = config.search_config.engine print(f"Preferred Search Engine: {search_engine}") # Access Browser settings (check if it exists) if config.browser_config: run_headless = config.browser_config.headless print(f"Run Browser Headless: {run_headless}") ``` -------------------------------- ### Setting up and Running a MultiStepAgent in Python Source: https://github.com/the-pocket/tutorial-codebase-knowledge/blob/main/docs/SmolaAgents/01_multistepagent.md This code snippet demonstrates how to import necessary components, define tools, choose a language model, create a MultiStepAgent instance, and run a task. It showcases the basic setup for using the MultiStepAgent to solve a multi-step problem. ```python # --- File: basic_agent.py --- # Import necessary components (we'll explain these more in later chapters!) from smolagents import MultiStepAgent from smolagents.models import LiteLLMModel # A simple way to use various LLMs from smolagents.tools import SearchTool, WeatherTool # Example Tools # 1. Define the tools the agent can use # These are like specialized workers the agent can call upon. search_tool = SearchTool() # A tool to search the web (details in Chapter 3) weather_tool = WeatherTool() # A tool to get weather info (details in Chapter 3) # Note: Real tools might need API keys or setup! # 2. Choose a language model (the "brain") # We'll use LiteLLMModel here, connecting to a capable model. # Make sure you have 'litellm' installed: pip install litellm llm = LiteLLMModel(model_id="gpt-3.5-turbo") # Needs an API key set up # We'll cover models properly in Chapter 2 # 3. Create the MultiStepAgent instance # We pass the brain (llm) and the helpers (tools) agent = MultiStepAgent( model=llm, tools=[search_tool, weather_tool] # By default, a 'final_answer' tool is always added. ) print("Agent created!") # 4. Give the agent a task! task = "What is the capital of France, and what is its current weather?" print(f"Running agent with task: '{task}'") # The agent will now start its Think-Act-Observe cycle... final_answer = agent.run(task) # ... and eventually return the final result. print("-" * 20) print(f"Final Answer received: {final_answer}") ``` -------------------------------- ### Example JSON Response from FastAPI Root Endpoint Source: https://github.com/the-pocket/tutorial-codebase-knowledge/blob/main/docs/FastAPI/01_fastapi_application___routing.md This shows the JSON data returned by the basic FastAPI application when a GET request is made to the root path (`/`). FastAPI automatically converted the Python dictionary `{"message": "Hello World"}` returned by the `read_root` function into this JSON format. ```json {"message":"Hello World"} ``` -------------------------------- ### Creating and Executing a PlanningFlow in Python Source: https://github.com/the-pocket/tutorial-codebase-knowledge/blob/main/docs/OpenManus/05_baseflow.md This code snippet demonstrates how to set up a PlanningFlow with a Manus agent, define a goal, and execute the flow. It shows the process of importing necessary classes, creating agents, instantiating the flow, and running it asynchronously. ```python # Import necessary classes from app.agent.manus import Manus # A capable agent from app.flow.flow_factory import FlowFactory, FlowType import asyncio # Needed for async execution # 1. Create the agent(s) we want the flow to manage # We can give agents specific keys (names) within the flow agents_for_flow = { "research_writer": Manus() # Use Manus agent for all tasks } # 2. Create the flow using the factory # We specify the type (PLANNING) and provide the agents planning_flow_instance = FlowFactory.create_flow( flow_type=FlowType.PLANNING, agents=agents_for_flow, # Optional: specify which agent is primary (if not first) # primary_agent_key="research_writer" ) print(f"Created a {type(planning_flow_instance).__name__}") print(f"Primary agent: {planning_flow_instance.primary_agent.name}") # 3. Define the overall goal for the flow overall_goal = "Research the main benefits of solar power and write a short summary." # Define an async function to run the flow async def run_the_flow(): print(f"\nExecuting flow with goal: '{overall_goal}'") # 4. Execute the flow with the goal final_result = await planning_flow_instance.execute(overall_goal) print("\n--- Flow Execution Finished ---") print(f"Final Result:\n{final_result}") # Run the async function # asyncio.run(run_the_flow()) # Uncomment to run ``` -------------------------------- ### Creating and Accessing dspy.Example Instances in Python Source: https://github.com/the-pocket/tutorial-codebase-knowledge/blob/main/docs/DSPy/03_example.md Demonstrates how to instantiate a `dspy.Example` using keyword arguments that correspond to signature fields (`english_sentence`, `french_sentence`). It also shows accessing the stored values using attribute notation. This requires the `dspy` library. ```python import dspy # Create an example for our translation task example1 = dspy.Example( english_sentence="Hello, world!", french_sentence="Bonjour le monde!" ) # You can access the values like attributes print(f"English: {example1.english_sentence}") print(f"French: {example1.french_sentence}") ``` -------------------------------- ### Fetching a Webpage with Requests Functional API - Python Source: https://github.com/the-pocket/tutorial-codebase-knowledge/blob/main/docs/Requests/01_functional_api.md This snippet demonstrates how to perform a simple HTTP GET request using the Python Requests library's functional API. It imports the requests module, specifies a URL, and retrieves the response, printing both the status code and the first 200 characters of the response content. The script depends on having the requests library installed (pip install requests). The 'url' parameter specifies the target endpoint. Outputs include the HTTP status code and a portion of the returned data. Designed for basic, rapid retrieval tasks without advanced configuration. ```python import requests # Import the library # The URL we want to get data from url = 'https://httpbin.org/get' # A handy website for testing requests # Use the functional API 'get' function print(f"Fetching data from: {url}") response = requests.get(url) # Check if the request was successful (Status Code 200 means OK) print(f"Status Code: {response.status_code}") # Print the first 200 characters of the content we received print("Response Content (first 200 chars):") print(response.text[:200]) ```