### Example Server Run Script Source: https://github.com/nirdiamant/agents-towards-production/blob/main/tutorials/a2a/a2a_tutorial.ipynb Illustrates how to structure a separate Python file (e.g., run_events_agent.py) to run the EventsInfoAgent server by including class definitions and server setup code. ```python # Example for run_events_agent.py: # """ # Copy the EventsInfoAgent, EventsInfoAgentExecutor class definitions, and the server setup code above into it. # """ # ```python ``` -------------------------------- ### Install and Run Local Redis Stack Server Source: https://github.com/nirdiamant/agents-towards-production/blob/main/tutorials/agent-memory-with-redis/agent_memory_tutorial.ipynb Installs Redis Stack server locally using shell commands. Ensure you have curl and apt-get available. This command downloads the GPG key, adds the Redis repository, updates package lists, installs the server, and starts it in the background. ```shell curl -fsSL https://packages.redis.io/gpg | sudo gpg --dearmor -o /usr/share/keyrings/redis-archive-keyring.gpg echo "deb [signed-by=/usr/share/keyrings/redis-archive-keyring.gpg] https://packages.redis.io/deb $(lsb_release -cs) main" | sudo tee /etc/apt/sources.list.d/redis.list sudo apt-get update > /dev/null 2>&1 sudo apt-get install redis-stack-server > /dev/null 2>&1 redis-stack-server --daemonize yes ``` -------------------------------- ### Install Python Packages Source: https://github.com/nirdiamant/agents-towards-production/blob/main/tutorials/agent-security-apex/README.md Install necessary Python packages for the tutorial. Ensure you have pip, openai, python-dotenv, and pandas installed. ```bash pip install openai python-dotenv pandas ``` -------------------------------- ### Install Dependencies Source: https://github.com/nirdiamant/agents-towards-production/blob/main/README.md Navigate to a specific tutorial directory and install its Python dependencies using pip. ```bash # Example: Multi-tool agent orchestration cd tutorials/agentic-applications-by-xpander.ai pip install -r meeting-recorder-agent/requirements.txt ``` -------------------------------- ### Download and Serve Ollama Source: https://github.com/nirdiamant/agents-towards-production/blob/main/tutorials/on-prem-llm-ollama/ollama_tutorial.ipynb Use `ollama pull` to download models and `ollama serve` to start the local REST service. Note that on Windows, Ollama may start automatically after installation. ```bash ollama pull ``` ```bash ollama serve ``` -------------------------------- ### Dockerfile Example: Python with Curl Source: https://github.com/nirdiamant/agents-towards-production/blob/main/tutorials/docker-intro/README.md Imports the official Python 3.10 image, sets labels and environment variables, and installs the curl library using apt-get. ```Dockerfile FROM python:3.10 LABEL example=1 ENV PYTHON_VER=3.10 RUN apt-get update && apt-get install -y --no-install-recommends curl ``` -------------------------------- ### Install Mem0 and Dependencies Source: https://github.com/nirdiamant/agents-towards-production/blob/main/tutorials/agent-memory-with-mem0/mem0_tutorial.ipynb Installs the Mem0 library, OpenAI client, and other necessary Python packages. Use this command to set up your environment for the tutorial. ```python !pip install -q mem0ai openai python-dotenv neo4j ``` -------------------------------- ### Navigate to Project Directory Source: https://github.com/nirdiamant/agents-towards-production/blob/main/tutorials/kotlin-agent-with-koog/tutorial.md Change to the tutorial directory within the cloned repository. This directory contains the Gradle project setup. ```bash cd tutorials/kotlin-agent-with-koog ``` -------------------------------- ### Install FastAPI and Uvicorn Source: https://github.com/nirdiamant/agents-towards-production/blob/main/tutorials/fastapi-agent/fastapi-agent-tutorial.ipynb Install the necessary packages for building FastAPI applications. Use `sse-starlette` if streaming functionality is required. ```python !pip install fastapi uvicorn pydantic ``` ```python !pip install sse-starlette ``` -------------------------------- ### Clone Project and Set Up Environment Source: https://github.com/nirdiamant/agents-towards-production/blob/main/tutorials/kotlin-agent-with-koog/README.md Clone the repository, navigate to the tutorial directory, and set your OpenAI API key. This is the initial setup for running the tutorial. ```bash git clone https://github.com/NirDiamant/agents-towards-production.git cd agents-towards-production/tutorials/kotlin-agent-with-koog export OPENAI_API_KEY="sk-..." ``` -------------------------------- ### Define Assistant Tools with Annotations Source: https://github.com/nirdiamant/agents-towards-production/blob/main/tutorials/kotlin-agent-with-koog/tutorial.md Implement the `ToolSet` interface and annotate methods with `@Tool` and `@LLMDescription` to make them available to the AI agent. Use parameter-level descriptions to guide the LLM in providing correct arguments. This example uses simulated data for demonstration. ```kotlin // Step2_AgentWithTools.kt (tool definitions) import ai.koog.agents.core.tools.annotations.LLMDescription import ai.koog.agents.core.tools.annotations.Tool import ai.koog.agents.core.tools.reflect.ToolSet // A ToolSet is a class whose methods can be called by the LLM. // Think of it like defining "functions" that an AI assistant can use. // // @Tool -- marks a function as callable by the agent // @LLMDescription -- tells the LLM what the function (or parameter) does, // so it knows WHEN and HOW to call it @LLMDescription("Tools for looking up weather, performing calculations, and retrieving facts") class AssistantTools : ToolSet { @Tool @LLMDescription("Get the current weather for a given city. Returns temperature and conditions.") fun getWeather(@LLMDescription("City name, e.g. 'Tokyo'") city: String): String { // In a real app, this would call a weather API. // We use hardcoded data so the tutorial works without extra API keys. val data = mapOf( "tokyo" to "22C, partly cloudy", "london" to "14C, rainy", "new york" to "28C, sunny", "sydney" to "18C, clear skies", ) return data[city.lowercase()] ?: "25C, clear (default forecast)" } @Tool @LLMDescription("Evaluate a basic arithmetic expression and return the numeric result.") fun calculate(@LLMDescription("Arithmetic expression, e.g. '144 / 12'") expression: String): String { val result = evaluateExpression(expression) return "$expression = $result" } @Tool @LLMDescription("Look up a factual piece of information about a topic.") fun lookupFact(@LLMDescription("Topic to look up, e.g. 'Kotlin'") topic: String): String { val facts = mapOf( "kotlin" to "Kotlin was created by JetBrains and first released in 2011. ...", "koog" to "Koog is an open-source AI agent framework by JetBrains. ...", ) return facts[topic.lowercase()] ?: "No specific fact found for '$topic'." } private fun evaluateExpression(expr: String): Double { /* ... */ } } ``` -------------------------------- ### Install a2a-sdk and Dependencies Source: https://github.com/nirdiamant/agents-towards-production/blob/main/tutorials/a2a/a2a_tutorial.ipynb Install the a2a-sdk, httpx, and uvicorn using pip. Restart your Jupyter kernel or runtime after installation if necessary. ```bash pip install a2a-sdk httpx uvicorn ``` -------------------------------- ### Install Dependencies Source: https://github.com/nirdiamant/agents-towards-production/blob/main/tutorials/agent-evaluation-intellagent/intellagent-evaluation-tutorial.ipynb Install the required Python packages for the IntellAgent framework using pip. ```bash # Install the required dependencies !pip install -r requirements.txt && pip install nest_asyncio ``` -------------------------------- ### Run Interactive Guided Runner Source: https://github.com/nirdiamant/agents-towards-production/blob/main/tutorials/kotlin-agent-with-koog/README.md Execute the interactive script to run the tutorial step-by-step. This is recommended for first-time users. ```bash ./run.sh ``` -------------------------------- ### Install MCP and Anthropic Libraries Source: https://github.com/nirdiamant/agents-towards-production/blob/main/tutorials/agent-with-mcp/mcp-tutorial.ipynb Install the required Python libraries, MCP for client-server communication and Anthropic for interacting with Claude's API. This is a prerequisite for building the custom agent. ```python ! pip install mcp anthropic ``` -------------------------------- ### Build Project with Gradle Source: https://github.com/nirdiamant/agents-towards-production/blob/main/tutorials/kotlin-agent-with-koog/tutorial.md This command compiles the project and downloads all necessary dependencies. It is typically run once at the beginning of the project setup. ```bash ./gradlew build ``` -------------------------------- ### Install Required Packages Source: https://github.com/nirdiamant/agents-towards-production/blob/main/tutorials/agent-RAG-with-Contextual/contextual_tutorial.ipynb Installs the necessary Python packages for Contextual AI integration, data visualization, and progress tracking. Ensure you have a stable internet connection. ```python # Install required packages for Contextual AI integration and data visualization %pip install contextual-client matplotlib tqdm requests pandas dotenv ``` -------------------------------- ### Example JSON Response for Blog Post Generation Source: https://github.com/nirdiamant/agents-towards-production/blob/main/tutorials/runpod-gpu-deploy/crew-ai-ollama-runpod-tutorial/README.md This is an example of the JSON output returned after a successful blog post generation task. ```json { "delayTime": 14836, "executionTime": 10799, "id": "4c04615b-540f-4d82-917d-4eb4256acd96-u1", "output": { "blog_post": "Title: The Future of Technology: A Promising Horizon\n\nIntroduction:\nTechnology has been a driving force behind human progress, constantly evolving to meet the challenges of our time. In recent years, the pace of technological advancements has accelerated, and we stand on the precipice of an exciting new era. This blog post explores the current state of technology, highlights its most promising trends, and looks forward to what's in store for the future.\n\nMain Points:\n1. The Unrelenting Importance of Technology: As per recent research, 82% of industry leaders consider technology a pivotal area of focus, demonstrating its significance in shaping our world. From healthcare and education to communication and entertainment, technology continues to transform our daily lives.\n2. Rising Research Investments: Last year alone, spending on technology-related research grew by an impressive 34%. This surge in investment highlights the growing belief that technological innovation will be a primary catalyst for economic growth and societal progress.\n3. Soaring Consumer Interest: Consumer interest in technology has soared since 2022, with a staggering 56% increase recorded. This rapid growth is a testament to the increasing role of technology in our lives and its ability to address the evolving needs and desires of individuals worldwide.\n4. A Promising Horizon: Experts predict that the next five years will bring significant advancements in technology. From artificial intelligence and quantum computing to breakthroughs in biotechnology, the future promises a world of endless possibilities and new frontiers to explore.\n\nConclusion:\nThe future of technology is undoubtedly bright, with innovation driving us towards a more connected, efficient, and prosperous society. As we forge ahead into this exciting new era, it's crucial that we continue to invest in research, foster collaboration, and embrace the transformative potential of technology. Our collective commitment to harnessing its power will determine the extent to which we can leverage technology to overcome global challenges and shape a better tomorrow for all.\n\nCall to Action:\nJoin the conversation on social media using #FutureOfTech and share your thoughts about how technology is changing our world. Let's engage in a dialogue that fosters understanding, inspiration, and collective action towards an even brighter future.", "status": "success" }, "status": "COMPLETED", "workerId": "fy17taoa4pyz2c" } ``` -------------------------------- ### Install and Import Libraries for Fine-tuning Source: https://github.com/nirdiamant/agents-towards-production/blob/main/tutorials/fine-tuning-agents/fine_tuning_agents_guide.ipynb Installs necessary Python packages and imports core libraries for interacting with OpenAI and managing data. Ensure you have your OpenAI API key set as an environment variable. ```python %pip install --upgrade openai langchain langgraph==0.3.1 tiktoken pandas scikit-learn import os, json, time from openai import OpenAI from dotenv import load_dotenv # Load environment variables and set OpenAI API key load_dotenv() os.environ["OPENAI_API_KEY"] = os.getenv('OPENAI_API_KEY') # Initialize OpenAI client client = OpenAI() ``` -------------------------------- ### Clone IntellAgent Repository Source: https://github.com/nirdiamant/agents-towards-production/blob/main/tutorials/agent-evaluation-intellagent/intellagent-evaluation-tutorial.ipynb Clone the IntellAgent repository and navigate into its directory to begin setup. ```bash # Clone the repository !git clone https://github.com/plurai-ai/intellagent.git # Change to the repo directory %cd intellagent ``` -------------------------------- ### Python Interactive Session Example Source: https://github.com/nirdiamant/agents-towards-production/blob/main/tutorials/docker-intro/README.md Demonstrates a typical interactive Python session within a Docker container after launching it with interactive flags. This example shows printing 'Hello World!'. ```python Python 3.10.12 (main, Jun 14 2023, 18:40:54) [GCC 12.2.0] on linux Type "help", "copyright", "credits" or "license" for more information. >>> print("Hello World!") Hello World! >>> ``` -------------------------------- ### Gradle Command to Run Agent Source: https://github.com/nirdiamant/agents-towards-production/blob/main/tutorials/kotlin-agent-with-koog/tutorial.md Execute this command in your terminal to run the Kotlin agent example. Ensure you have Gradle set up for your project. ```bash ./gradlew step1 ``` -------------------------------- ### Dockerfile with Separate Installs for Caching Demo Source: https://github.com/nirdiamant/agents-towards-production/blob/main/tutorials/docker-intro/README.md This Dockerfile installs curl and then vim in separate RUN commands to demonstrate Docker's layer caching. Use this when you want to explicitly show how Docker caches intermediate layers. ```Dockerfile FROM python:3.10 LABEL example=1 ENV PYTHON_VER=3.10 RUN apt-get update && apt-get install -y --no-install-recommends curl RUN apt-get update && apt-get install -y --no-install-recommends vim ``` -------------------------------- ### Run News Agent as Standalone Server Source: https://github.com/nirdiamant/agents-towards-production/blob/main/tutorials/a2a/a2a_tutorial.ipynb Provides an example of how to run the configured News Agent server using uvicorn. This code should be placed in a separate Python file and not run directly in the notebook to avoid blocking the kernel. ```python # --- How to Run News agent as standalone --- # The following uvicorn.run command is how you would typically start this server. # IMPORTANT: Do NOT run this directly in the notebook cell as it will block the kernel. # Instead, you should create a separate Python file (e.g., run_news_agent.py), # copy the necessary class definitions (NewsInfoAgent, NewsInfoAgentExecutor) and # the server setup code (AgentSkill, AgentCard, ..., news_agent_server_app creation) into it, # and then add the uvicorn.run command at the end of that file. # Example for run_news_agent.py: # ```python # # (Paste NewsInfoAgent, NewsInfoAgentExecutor class definitions here) # # (Paste AgentSkill, AgentCard, news_agent_executor, news_task_store, news_request_handler, news_agent_server_app setup here) # import uvicorn # Make sure to import uvicorn in the script # # if __name__ == '__main__': # logger.info(f"Starting News Agent server on {NEWS_AGENT_BASE_URL}") # uvicorn.run(news_agent_server_app, host='0.0.0.0', port=9001) # Port matches NEWS_AGENT_BASE_URL # ``` ``` -------------------------------- ### Example Tutorial Directory Structure Source: https://github.com/nirdiamant/agents-towards-production/blob/main/CONTRIBUTING.md Illustrates the required files and their organization within a tutorial's directory. Ensure all listed components are present for a complete tutorial submission. ```bash tutorials/your-tutorial-name/ ├── README.md # High-level overview and motivation ├── app.py # Main application code ├── tutorial.md or .ipynb # Documentation ├── requirements.txt # Dependencies └── assets/ # Media files ├── step1_screenshot.png # Screenshots for each step └── final_result.png # End result ``` -------------------------------- ### Start Streamlit Dashboard in Thread Source: https://github.com/nirdiamant/agents-towards-production/blob/main/tutorials/agent-evaluation-intellagent/intellagent-evaluation-tutorial.ipynb Launches the IntellAgent Results Dashboard in a separate thread for interactive visualization. Ensure Streamlit is installed and configured. The dashboard will be accessible at http://localhost:8501. ```python import threading import time from IPython.display import display, IFrame # Assuming run_streamlit is defined elsewhere and starts the Streamlit app def run_streamlit(): # Placeholder for the actual Streamlit run command print("Streamlit app is running...") print("🚀 Starting IntellAgent Results Dashboard...") print("📊 This will launch an interactive visualization of your agent's performance") print("⏱️ Please wait a moment for the dashboard to load ") streamlit_thread = threading.Thread(target=run_streamlit) streamlit_thread.daemon = True # Set as daemon so it exits when the notebook exits streamlit_thread.start() # Wait a few seconds for Streamlit to start time.sleep(5) # Display in an iframe (may not work in all environments) try: display(IFrame(src="http://localhost:8501", width=1000, height=600)) print("\n📈 Dashboard loaded successfully!") print("🔍 Navigate to the '🤖 Session Visualizer' page to explore conversation traces") except: print("\n🌐 Dashboard is running at: http://localhost:8501") print("📝 Please open this URL in a new browser tab to view your results") print("🔍 Once there, navigate to the '🤖 Session Visualizer' page") ``` -------------------------------- ### Set Up MCP Crypto Server Project Source: https://github.com/nirdiamant/agents-towards-production/blob/main/tutorials/agent-with-mcp/mcp-tutorial.ipynb Create a new project directory, initialize it with uv, set up a virtual environment, and install necessary dependencies for the MCP crypto server. ```bash # Create and navigate to a project directory mkdir mcp-crypto-server cd mcp-crypto-server uv init # Create and activate virtual environment uv venv source .venv/bin/activate # On Windows: .venv\Scripts\activate # Install dependencies uv add "mcp[cli]" httpx ``` -------------------------------- ### Run Tutorials Source: https://github.com/nirdiamant/agents-towards-production/blob/main/README.md Execute tutorials locally using either Jupyter notebooks for interactive experimentation or Python scripts for integration testing. ```bash # Run interactive notebooks for experimentation jupyter notebook tutorial.ipynb ``` ```bash # Execute production scripts for integration testing python app.py ``` -------------------------------- ### Dockerfile for Dynamic AI Agent Source: https://github.com/nirdiamant/agents-towards-production/blob/main/tutorials/docker-intro/README.md This Dockerfile sets up a Python environment, installs the OpenAI library, copies the agent script, and sets a default QUESTION environment variable. The CMD instruction specifies how to run the Python script when the container starts. ```dockerfile FROM python:3.10-slim RUN pip install --no-cache-dir openai COPY ./examples/ex5/dynamic_agent.py /app/dynamic_agent.py ENV QUESTION="What is the capital of France?" CMD ["python", "/app/dynamic_agent.py"] ``` -------------------------------- ### Initialize FastAPI Application and Agent Source: https://github.com/nirdiamant/agents-towards-production/blob/main/tutorials/fastapi-agent/fastapi-agent-tutorial.ipynb Set up the FastAPI application instance, including title, description, and version. Also, create an instance of the SimpleAgent. ```python from fastapi import FastAPI, Depends, HTTPException, Header from fastapi.responses import StreamingResponse from pydantic import BaseModel import json import os import asyncio # Initialize FastAPI app app = FastAPI( title="Agent API", description="A simple API that serves an AI agent", version="0.1.0" ) # Create an instance of our agent agent = SimpleAgent() ``` -------------------------------- ### Install Python Dependencies in Dockerfile Source: https://github.com/nirdiamant/agents-towards-production/blob/main/tutorials/runpod-gpu-deploy/README.md Installs Python dependencies from requirements.txt, upgrades pip, installs uv, and then installs langchain-community. It also prints CrewAI and CrewAI Tools versions for verification. ```dockerfile COPY requirements.txt /requirements.txt RUN pip install --upgrade pip && \ pip install uv && \ uv pip install --upgrade -r /requirements.txt --no-cache-dir && \ uv pip install "langchain-community>=0.0.34" --no-cache-dir && \ python -c "import crewai; print(f'\nCrewAI version: {crewai.__version__}')" && \ python -c "import crewai_tools; print('CrewAI Tools import successful')" ``` -------------------------------- ### Set up AsyncOpenAI Client Source: https://github.com/nirdiamant/agents-towards-production/blob/main/tutorials/agent-security-apex/agent-security-evaluation-tutorial.ipynb Initializes the AsyncOpenAI client using an API key from environment variables. This is a prerequisite for interacting with the OpenAI API asynchronously. ```python my_api_key = os.getenv("OPENAI_API_KEY") my_client = AsyncOpenAI(api_key=my_api_key) ``` -------------------------------- ### Install Required Python Libraries Source: https://github.com/nirdiamant/agents-towards-production/blob/main/tutorials/agent-memory-with-redis/agent_memory_tutorial.ipynb Installs the necessary Python packages for building the memory-enabled agent. A kernel restart might be required after installation. ```python %pip install langchain-openai langgraph-checkpoint langgraph langgraph-checkpoint-redis langchain-redis ``` -------------------------------- ### Install Python Dependencies Source: https://github.com/nirdiamant/agents-towards-production/blob/main/tutorials/agent-with-tavily-web-access/web-agent-tutorial.ipynb Installs the required Python packages for Tavily, LangChain, and OpenAI integration. The '--quiet' flag suppresses verbose output during installation. ```python %pip install -U tavily-python langchain-openai langchain langchain-tavily langgraph --quiet ``` -------------------------------- ### Set Up Anthropic API Key and Initialize Client Source: https://github.com/nirdiamant/agents-towards-production/blob/main/tutorials/agent-with-mcp/mcp-tutorial.ipynb Configure the Anthropic API key by setting the ANTHROPIC_API_KEY environment variable. Then, initialize the Anthropic client for use in the agent. ```python # Import necessary libraries import os import json from typing import List, Dict, Any # MCP libraries for connecting to server from mcp import ClientSession, StdioServerParameters from mcp.client.stdio import stdio_client # Anthropic API for Claude from anthropic import Anthropic # Set up Anthropic API key (using the one you provided) os.environ["ANTHROPIC_API_KEY"] = "your_anthropic_api_key_here" # Initialize the Anthropic client client = Anthropic() ``` -------------------------------- ### Install Required Libraries with Pip Source: https://github.com/nirdiamant/agents-towards-production/blob/main/tutorials/agent-with-streamlit-ui/building-chatbot-notebook.ipynb Use pip to install the necessary Python libraries for interacting with OpenAI and building the Streamlit web application. This command installs the core libraries. ```bash !pip install openai streamlit ``` -------------------------------- ### Verify Cognee Installation Source: https://github.com/nirdiamant/agents-towards-production/blob/main/tutorials/ai-memory-with-cognee/cognee-ai-memory.ipynb Check if Cognee is installed correctly and determine if you are using a local development version or an installed package. This script prints the Cognee file location and its parent directory. ```python import cognee import os from pathlib import Path print('Quick Cognee Import Check') print('=' * 30) print(f'Cognee location: {cognee.__file__}') print(f'Package directory: {os.path.dirname(cognee.__file__)}') # Check if it's local or installed current_dir = Path.cwd() cognee_path = Path(cognee.__file__) if current_dir in cognee_path.parents: print('Status: LOCAL DEVELOPMENT VERSION') else: print('Status: INSTALLED PACKAGE') ``` -------------------------------- ### Build Basic Agent with Gradle Source: https://github.com/nirdiamant/agents-towards-production/blob/main/tutorials/kotlin-agent-with-koog/README.md Use Gradle to build the basic AI agent. This command executes step 1 of the tutorial. ```bash ./gradlew step1 ``` -------------------------------- ### Run Demo Agent with Sample Texts Source: https://github.com/nirdiamant/agents-towards-production/blob/main/tutorials/on-prem-llm-ollama/scripts/langchain_agent.ipynb Initializes the agent and processes a list of predefined sample texts, printing the analysis results for each. Ensure the SimpleAnalysisAgent is correctly initialized before use. ```python def demo_agent(): """Demonstrate the agent with sample texts.""" print("🤖 LangChain Agent with Ollama Demo") print("=" * 40) try: agent = SimpleAnalysisAgent() print("✅ Agent initialized successfully\n") except ValueError as e: print(e) return # Sample texts to analyze samples = [ { "name": "Tech News", "text": "\n Apple announced today that its new iPhone 15 will feature USB-C charging,\n marking a significant shift from the Lightning connector. The change comes\n after pressure from the European Union's new charging regulations. The new\n phones will also include improved cameras and faster processors. Industry\n analysts expect this to boost sales significantly in the next quarter.\n " }, { "name": "Code Comment", "text": "\n def process_data(input_list): # This function takes a list of numbers and returns the average # It handles empty lists by returning 0 if not input_list: return 0 return sum(input_list) / len(input_list) " } ] # Analyze each sample for sample in samples: print(f"📋 Sample: {sample['name']}") print("-" * 30) result = agent.analyze_text(sample["text"].strip()) print(f"Category: {result['category']}") print(f"Summary: {result['summary']}") print("Key Points:") for point in result['key_points']: print(f" • {point}") print() ``` ```python demo_agent() print("\n✅ Done!") ``` -------------------------------- ### Create and Run a Basic Agent in Kotlin Source: https://github.com/nirdiamant/agents-towards-production/blob/main/tutorials/kotlin-agent-with-koog/tutorial.md Use this snippet to initialize an OpenAI executor, build an agent with a system prompt, and run a query. Ensure the OPENAI_API_KEY environment variable is set. The '.use' block ensures the executor's connection is closed automatically. ```kotlin // Step1_HelloAgent.kt import ai.koog.agents.core.agent.AIAgent import ai.koog.prompt.executor.clients.openai.OpenAIModels import ai.koog.prompt.executor.llms.all.simpleOpenAIExecutor // "suspend fun main()" is Kotlin's way of writing an async main function. // If you come from Python, think of it like: async def main() // Koog agents run on coroutines, so the entry point must be suspendable. suspend fun main() { // Read the API key from an environment variable. // The "? :" operator (called "Elvis") provides a fallback if the value is null. // In Python terms: api_key = os.environ.get("OPENAI_API_KEY") or raise ... val apiKey = System.getenv("OPENAI_API_KEY") ?: error("Set the OPENAI_API_KEY environment variable before running this example.") // Create an executor -- the HTTP client that talks to OpenAI's API. // ".use { ... }" automatically closes the connection when the block finishes, // similar to Python's "with open(...) as f:" pattern. simpleOpenAIExecutor(apiKey).use { executor -> // Build the agent. At minimum, it needs: // - an executor (how to reach the LLM) // - a model (which LLM to use) // - a system prompt (the agent's personality / instructions) val agent = AIAgent( promptExecutor = executor, llmModel = OpenAIModels.Chat.GPT4oMini, systemPrompt = "You are a concise assistant. Answer in one or two sentences.", ) // Send a prompt and get a text response back. val response = agent.run("What makes Kotlin a good language for backend development?") println("Agent response: $response") } } ``` -------------------------------- ### Install Dependencies Source: https://github.com/nirdiamant/agents-towards-production/blob/main/tutorials/agent-with-tavily-web-access/supplemental/vectorize_tutorial.ipynb Installs the necessary Python packages for Langchain, PDF processing, and OpenAI integration. ```python %pip install langchain pypdf langchain-openai --quiet ``` -------------------------------- ### Setup Bright Data MCP Client and Tools Source: https://github.com/nirdiamant/agents-towards-production/blob/main/tutorials/agent-with-brightdata/web_scraping_agent.ipynb Configures the MCP server connection and converts available tools into a LangChain-compatible format. Requires Bright Data API token to be set as an environment variable. ```python async def setup_bright_data_tools(): """ Configure Bright Data MCP client and create LangChain-compatible tools """ # Configure the MCP server connection bright_data_config = { "mcpServers": { "Bright Data": { "command": "npx", "args": ["@brightdata/mcp"], "env": { "API_TOKEN": os.getenv("BRIGHT_DATA_API_TOKEN"), } } } } # Create MCP client and adapter client = MCPClient.from_dict(bright_data_config) adapter = LangChainAdapter() # Convert MCP tools to LangChain-compatible format tools = await adapter.create_tools(client) print(f"✅ Connected to Bright Data MCP server") print(f"📊 Available tools: {len(tools)}") return tools # Test the connection tools = await setup_bright_data_tools() ``` -------------------------------- ### Install Dependencies Source: https://github.com/nirdiamant/agents-towards-production/blob/main/tutorials/agent-with-tavily-web-access/hybrid-agent-tutorial.ipynb Installs the necessary Python packages for Tavily, Chroma, OpenAI embeddings, Langgraph, and Langchain. ```python %pip install -U tavily-python langchain-chroma langchain-openai langgraph langchain-tavily --quiet ``` -------------------------------- ### Setup Testing Environment with OpenAI and Utilities Source: https://github.com/nirdiamant/agents-towards-production/blob/main/tutorials/agent-security-apex/agent-security-evaluation-tutorial.ipynb Initializes the testing environment by loading environment variables and importing necessary modules for OpenAI API interaction, model testing, and prompt manipulation. ```python %load_ext autoreload %autoreload 2 import os from dotenv import load_dotenv from openai import AsyncOpenAI from model_testing_tools import test_model, send_prompt_to_model, check_password_in_response from prompt_manipulation_tools import prompt_encoder load_dotenv() ``` -------------------------------- ### Install Cognee Package Source: https://github.com/nirdiamant/agents-towards-production/blob/main/tutorials/ai-memory-with-cognee/cognee-ai-memory.ipynb Installs the Cognee library version 0.3.3. This is required before importing and using Cognee functionalities. ```python %pip install cognee==0.3.3 ``` -------------------------------- ### Agent Setup with Structured Output Strategy Source: https://github.com/nirdiamant/agents-towards-production/blob/main/tutorials/kotlin-agent-with-koog/tutorial.md Use `structuredOutputWithToolsStrategy()` to enable an agent to return a typed object. This strategy handles the entire flow, including tool calls and final serialization. Ensure the `OPENAI_API_KEY` environment variable is set. ```kotlin import ai.koog.agents.core.agent.AIAgent import ai.koog.agents.core.agent.config.AIAgentConfig import ai.koog.agents.ext.agent.structuredOutputWithToolsStrategy import ai.koog.prompt.dsl.prompt import ai.koog.prompt.executor.clients.openai.OpenAIModels import ai.koog.prompt.executor.llms.all.simpleOpenAIExecutor suspend fun main() { val apiKey = System.getenv("OPENAI_API_KEY") ?: error("Set the OPENAI_API_KEY environment variable before running this example.") val agentConfig = AIAgentConfig( prompt = prompt("city-analyst") { system("You are a knowledgeable city analyst. When asked about a city, provide accurate structured data.") }, model = OpenAIModels.Chat.GPT4o, maxAgentIterations = 5, ) simpleOpenAIExecutor(apiKey).use { executor -> // structuredOutputWithToolsStrategy() is a built-in Koog strategy // that lets the agent call tools in a loop and then finish with a structured // output of the specified type once the process is complete. val agent = AIAgent( promptExecutor = executor, strategy = structuredOutputWithToolsStrategy(), agentConfig = agentConfig, ) // The return type is CityAnalysis -- a real Kotlin object, not a string. // No JSON parsing or regex extraction needed in your code. val analysis: CityAnalysis = agent.run("Tell me about Tokyo") // Access typed fields directly println("City: ${analysis.city}") println("Country: ${analysis.country}") println("Population: ${analysis.populationMillions}M") println("Language: ${analysis.primaryLanguage}") println("Landmarks: ${analysis.landmarks.joinToString(", ")}) println("Summary: ${analysis.summary}") } } ``` -------------------------------- ### Install uv Package Manager Source: https://github.com/nirdiamant/agents-towards-production/blob/main/tutorials/agent-with-mcp/mcp-tutorial.ipynb Install the uv package manager by running this command in your terminal. Ensure you are not in a Jupyter notebook cell. ```bash # Run this in your terminal, not in Jupyter curl -LsSf https://astral.sh/uv/install.sh | sh ``` -------------------------------- ### Install LangGraph and Dependencies Source: https://github.com/nirdiamant/agents-towards-production/blob/main/tutorials/LangGraph-agent/langgraph_tutorial.ipynb Installs the necessary Python packages for LangGraph, LangChain, and OpenAI integration. Ensure you have a Python environment set up. ```python # Install required packages !pip install langgraph langchain langchain-openai python-dotenv ``` -------------------------------- ### Initialize Bright Data SERP Tool Source: https://github.com/nirdiamant/agents-towards-production/blob/main/tutorials/agent-with-brightdata/langgraph_integration.ipynb Configure the Bright Data SERP tool with specific search parameters like engine, country, language, and result count. Set parse_results to True for structured output. ```python serp_tool = BrightDataSERP( search_engine="google", # Use Google as the search engine country="us", # Search from US perspective language="en", # English language results results_count=10, # Get top 10 results parse_results=True, # Automatically parse and structure results ) print("Bright Data SERP tool configured successfully!") print(f" Search Engine: {serp_tool.search_engine}") print(f" Country: {serp_tool.country}") print(f" Language: {serp_tool.language}") print(f" Results Count: {serp_tool.results_count}") ``` -------------------------------- ### Run the MCP Server Source: https://github.com/nirdiamant/agents-towards-production/blob/main/tutorials/agent-with-mcp/mcp-tutorial.ipynb Copy the server file into the current directory and start the MCP server using uv run. Ensure the server file is in the correct location. ```bash # Copy the server file from the scripts folder cp ../scripts/mcp_server.py . # Start the MCP server uv run mcp_server.py ``` -------------------------------- ### Install Tavily Python Package Source: https://github.com/nirdiamant/agents-towards-production/blob/main/tutorials/agent-with-tavily-web-access/search-extract-crawl.ipynb Install or upgrade the Tavily Python client library. The --quiet flag suppresses verbose output. ```python %pip install --upgrade tavily-python --quiet ``` -------------------------------- ### Prepare Document Collection for Upload Source: https://github.com/nirdiamant/agents-towards-production/blob/main/tutorials/agent-RAG-with-Contextual/contextual_tutorial.ipynb Download sample financial documents from a GitHub repository and save them to a local 'data' directory. This prepares the files for ingestion into the datastore. ```python import os import requests # Create data directory if it doesn't exist if not os.path.exists('data'): os.makedirs('data') # File list with corresponding GitHub URLs files_to_upload = [ # NVIDIA quarterly revnue 24/25 ("A_Rev_by_Mkt_Qtrly_Trend_Q425.pdf", "https://raw.githubusercontent.com/ContextualAI/examples/refs/heads/main/08-ai-workshop/data/A_Rev_by_Mkt_Qtrly_Trend_Q425.pdf"), # NVIDIA quarterly revenue 22/23 ("B_Q423-Qtrly-Revenue-by-Market-slide.pdf", "https://raw.githubusercontent.com/ContextualAI/examples/refs/heads/main/08-ai-workshop/data/B_Q423-Qtrly-Revenue-by-Market-slide.pdf"), # Spurious correlations report - fun example of graphs and statistical analysis ("C_Neptune.pdf", "https://raw.githubusercontent.com/ContextualAI/examples/refs/heads/main/08-ai-workshop/data/C_Neptune.pdf"), # Another spurious correlations report - fun example of graphs and statistical analysis ("D_Unilever.pdf", "https://raw.githubusercontent.com/ContextualAI/examples/refs/heads/main/08-ai-workshop/data/D_Unilever.pdf") ] ``` -------------------------------- ### Install Dependencies for LangGraph and LangChain-Arcade Source: https://github.com/nirdiamant/agents-towards-production/blob/main/tutorials/arcade-secure-tool-calling/multiuser-agent-arcade.ipynb Installs the necessary libraries for agent orchestration, tool integration with Arcade, and core LangChain functionality with OpenAI support. ```python !pip install langgraph langchain-arcade "langchain[openai]" ``` -------------------------------- ### Build Agent with Tools using Gradle Source: https://github.com/nirdiamant/agents-towards-production/blob/main/tutorials/kotlin-agent-with-koog/README.md Use Gradle to build the AI agent with integrated tools. This command executes step 2 of the tutorial. ```bash ./gradlew step2 ``` -------------------------------- ### Interactive Chat Session Start Source: https://github.com/nirdiamant/agents-towards-production/blob/main/tutorials/agent-with-mcp/mcp-tutorial.ipynb Starts an interactive chat session, prompting the user for input. Indicates that the session can be ended by typing 'exit' or 'quit'. ```python print("\033[96m\033[1m==================================================\n💬 INTERACTIVE CHAT SESSION\n==================================================\033[0m") print("\033[94mProcessing...\033[0m") print("\033[95m========================================\n🧠 REASONING PHASE: Processing query with Claude\n🔤 Query: \"What's the market data for Dogecoin and Solana?\"\n========================================\033[0m") print("\033[94m📡 Sending request to Claude API...\033[0m") print("\033[92m✅ Received response from Claude\033[0m") print("\033[93m🔍 Tool usage detected in response\033[0m") print("\033[94m📦 Extracted JSON: {\n \"tool\": \"get_crypto_market_info\",\n \"arguments\": {\n \"crypto_ids\": \"dogecoin,solana\"\n }\n}\033[0m") print("\033[93m🔧 Claude wants to use tool: get_crypto_market_info\033[0m") print("\033[93m----------------------------------------\n⚙️ EXECUTION PHASE: Running tool 'get_crypto_market_info'\n📋 Arguments: {\n \"crypto_ids\": \"dogecoin,solana\"\n}\n----------------------------------------\033[0m") print("\033[94m📡 Sending request to MCP server...\033[0m") print("\033[92m✅ Tool execution complete\033[0m") print("\033[94m📊 Result: meta=None content=[TextContent(type='text', text='Solana (SOL):\nCurrent price: 120.93 USD\nMarket cap: 62246986425 USD\n24h trading volume: 566579...\033[0m") print("----------------------------------------") print("\033[95m🔄 Getting Claude's interpretation of the tool result...\033[0m") print("\033[92m✅ Final response ready\033[0m") print("========================================") print("\n\033[1mAssistant:\033[0m Thank you for providing the market data. I'll summarize the information for Dogecoin and Solana:\n\nSolana (SOL):\n1. Current price: $120.93\n2. Market cap: $62,246,986,425\n3. 24h trading volume: $5,665,790,205\n4. 24h price change: +5.01%\n\nDogecoin (DOGE):\n1. Current price: $0.169366\n2. Market cap: $25,197,463,810\n3. 24h trading volume: $1,635,314,095\n4. 24h price change: +4.39%\n\nBoth cryptocurrencies have shown positive price movements in the last 24 hours, with Solana experiencing a slightly higher increase compared to Dogecoin. Solana has a significantly higher market capitalization and trading volume than Dogecoin.\n\nIs there any specific aspect of this market data you'd like me to elaborate on or any other information you need about these cryptocurrencies?\n\n\033[92mEnding chat session. Goodbye!\033[0m") ``` -------------------------------- ### Example Usage of Agent Integration Source: https://context7.com/nirdiamant/agents-towards-production/llms.txt This Python code demonstrates how to use the discover_tools and query_agent functions to interact with an AI agent. It first discovers available tools from the MCP server and then sends a prompt to the agent, printing the result. ```python async def discover_tools(): """Connect to MCP server and discover available tools.""" server_params = StdioServerParameters(command="python", args=[mcp_server_path]) async with stdio_client(server_params) as (read, write): async with ClientSession(read, write) as session: await session.initialize() tools = await session.list_tools() tool_info = [] for tool_type, tool_list in tools: if tool_type == "tools": for tool in tool_list: tool_info.append({ "name": tool.name, "description": tool.description, "schema": tool.inputSchema }) return tool_info async def execute_tool(tool_name: str, arguments: dict): """Execute a specific MCP tool with arguments.""" server_params = StdioServerParameters(command="python", args=[mcp_server_path]) async with stdio_client(server_params) as (read, write): async with ClientSession(read, write) as session: await session.initialize() result = await session.call_tool(tool_name, arguments) return result async def query_agent(prompt: str, tools: list): """Send query to Claude and process tool calls.""" tool_descriptions = "\n".join([ f"Tool: {t['name']}\nDescription: {t['description']}" for t in tools ]) system_prompt = f"""You have access to these tools: {tool_descriptions} When you need a tool, respond with JSON: {{'tool': 'name', 'arguments': {{...}}}}""" response = client.messages.create( model="claude-3-5-sonnet-20240620", max_tokens=4000, system=system_prompt, messages=[{"role": "user", "content": prompt}] ) claude_response = response.content[0].text # Check for tool usage import re json_match = re.search(r'(\{[\s\S]*\})', claude_response) if json_match: tool_request = json.loads(json_match.group(1)) if "tool" in tool_request: result = await execute_tool(tool_request["tool"], tool_request["arguments"]) return f"Tool result: {result}" return claude_response # Usage tools = await discover_tools() response = await query_agent("What is the current price of Bitcoin?", tools) print(response) ``` -------------------------------- ### Install python-dotenv for Environment Variables Source: https://github.com/nirdiamant/agents-towards-production/blob/main/tutorials/agent-with-streamlit-ui/building-chatbot-notebook.ipynb Install the python-dotenv package to manage environment variables, which is a recommended way to handle sensitive information like API keys. ```bash !pip install python-dotenv ``` -------------------------------- ### Verify Environment Setup Source: https://github.com/nirdiamant/agents-towards-production/blob/main/tutorials/agent-with-brightdata/web_scraping_agent.ipynb Checks if the environment variables, specifically the OpenRouter API Key, have been loaded correctly. This step ensures proper agent configuration and prevents runtime errors. ```python # Verify environment setup print("✅ Environment setup complete!") print(f"OpenRouter API Key loaded: {'Yes' if os.getenv('OPENROUTER_API_KEY') else 'No'}") ```