### Shell Command Execution with giga_agent.tools.repl.shell Source: https://context7.com/ai-forever/giga_agent/llms.txt This snippet shows how to execute shell commands within GigaAgent's REPL environment using the `shell` tool. It provides an example of installing Python packages like scikit-learn using pip. ```python from giga_agent.tools.repl import shell # Install packages or run system commands result = await shell.ainvoke({ "command": "pip install scikit-learn", "state": {"kernel_id": "kernel-id"}, "config": {"configurable": {"thread_id": "thread-123"}} }) ``` -------------------------------- ### Create a Custom LLM Tool with Langchain Source: https://context7.com/ai-forever/giga_agent/llms.txt This Python example shows how to define a custom tool that can be called by an LLM using Langchain. It utilizes the `@tool` decorator and defines input arguments using `TypedDict`. The example demonstrates making an asynchronous HTTP POST request to an external API, including error handling for the request. Ensure to register the tool in `config.py` and follow the build process. ```python # backend/graph/giga_agent/tools/my_tool.py # Example: Creating a new LLM-callable tool from typing import TypedDict, Optional from langchain_core.tools import tool import httpx class MyToolArgs(TypedDict, total=False): query: str limit: Optional[int] @tool("my_custom_search", args_schema=MyToolArgs) async def my_custom_search(query: str, limit: int = 10) -> str: """Search custom database for relevant documents. Args: query: Search query string limit: Maximum results to return (default: 10) """ async with httpx.AsyncClient() as client: response = await client.post( "https://api.myservice.com/search", json={"q": query, "limit": limit}, headers={"Authorization": f"Bearer {settings.external.my_api_key}"} ) response.raise_for_status() return response.json() # Register in config.py: # 1. Add to TOOLS_REQUIRED_ENVS if needs API keys # 2. Add to SERVICE_TOOLS or AGENTS list # 3. Run: make build_graph && make build && make up ``` -------------------------------- ### Python Code Execution with giga_agent.tools.repl.args_tool.python Source: https://context7.com/ai-forever/giga_agent/llms.txt This snippet demonstrates how to execute Python code within GigaAgent's stateful REPL environment using the `python` tool. It includes an example of data analysis with pandas, reading an Excel file, generating a histogram, and retrieving the results, including potential exceptions and attachments. ```python from giga_agent.tools.repl.args_tool import python code = """ import pandas as pd # Read Excel file with thousands of rows df = pd.read_excel('/files/data.xlsx') # Analyze data summary = df.describe() correlations = df.corr() # Create visualization import matplotlib.pyplot as plt df['column_name'].hist() plt.savefig('/runs/histogram.png') summary """ result = await python.ainvoke({ "code": code, "state": {"kernel_id": "unique-kernel-id"}, "config": {"configurable": {"thread_id": "thread-123"}} }) # Result includes: # - result: execution output # - is_exception: bool indicating errors # - exception: error message if any # - attachments: generated images/files with paths ``` -------------------------------- ### GigaAgent Environment Configuration (.docker.env) Source: https://context7.com/ai-forever/giga_agent/llms.txt This snippet shows an example `.docker.env` file, detailing essential configuration variables for GigaAgent. It includes settings for LLM providers, embedding models, image generation, API keys for external services, MCP tool configuration, RAG knowledge base, and REPL code execution mode. ```env GIGA_AGENT_LLM="gigachat:GigaChat-2-Max" GIGA_AGENT_LLM_FAST="gigachat:GigaChat-2-Pro" GIGA_AGENT_EMBEDDINGS="gigachat:EmbeddingsGigaR" IMAGE_GEN_NAME="gigachat:kandinsky-4.1" TAVILY_API_KEY="tvly-xxxxx" GITHUB_TOKEN="ghp_xxxxx" VK_TOKEN="vk1.a.xxxxx" TWOGIS_TOKEN="xxxxx" OPENWEATHERMAP_API_KEY="xxxxx" SALUTE_SPEECH="xxxxx" GIGA_AGENT_MCP_CONFIG='{"giga_tools": {"transport": "stdio", "command": "npx", "args": ["-y", "mcp-remote@latest", "https://gigachat.fastmcp.app/mcp"]}}' LANGCONNECT_API_URL=http://host.docker.internal:8833 LANGCONNECT_API_SECRET_TOKEN=your_secret_token REPL_FROM_MESSAGE=0 ``` -------------------------------- ### Install Giga Agent Dependencies (Python) Source: https://github.com/ai-forever/giga_agent/blob/main/backend/graph/giga_agent/repl_tools/models/sentiment_model.ipynb This command installs the core Python libraries required for the Giga Agent project. It includes langchain_gigachat for LLM integration, pandas and numpy for data manipulation, scikit-learn for machine learning functionalities, and python-dotenv for environment variable management. The output confirms successful installation or prior existence of these packages. ```python !pip install langchain_gigachat pandas numpy scikit-learn python-dotenv ``` -------------------------------- ### Register Required Environment Variables for Giga Agent Tools Source: https://context7.com/ai-forever/giga_agent/llms.txt This Python configuration snippet from `backend/graph/giga_agent/config.py` shows how to register new tools and specify their environment variable requirements. The `TOOLS_REQUIRED_ENVS` dictionary maps tool names (e.g., 'gen_image', 'search') to a list of necessary environment variable keys (e.g., 'IMAGE_GEN_NAME', 'TAVILY_API_KEY'). This ensures proper tool setup and security. ```python # backend/graph/giga_agent/config.py # Register new tools and configure environment requirements TOOLS_REQUIRED_ENVS = { "gen_image": ["IMAGE_GEN_NAME"], "search": ["TAVILY_API_KEY"], "vk_get_posts": ["VK_TOKEN"], "weather": ["OPENWEATHERMAP_API_KEY"], # Add custom tool requirements "my_custom_tool": ["MY_API_KEY", "MY_SECRET"] } ``` -------------------------------- ### GitHub Integration: List and Get Pull Requests and Workflow Runs Source: https://context7.com/ai-forever/giga_agent/llms.txt Python code to interact with GitHub repositories, listing pull requests, retrieving specific pull request details, and fetching CI/CD workflow runs. It requires the `giga_agent.tools.github` module and uses asynchronous operations. The output includes PR data, commit info, review status, and CI status, with URL fields automatically filtered. ```python # List pull requests from repository from giga_agent.tools.github import list_pull_requests, get_pull_request, get_workflow_runs # Get open PRs prs = await list_pull_requests.ainvoke({ "owner": "ai-forever", "repo": "giga_agent", "state": "open", "per_page": 30, "page": 1, "sort": "updated", "direction": "desc" }) # Get specific PR details pr_details = await get_pull_request.ainvoke({ "owner": "ai-forever", "repo": "giga_agent", "pull_number": 42 }) # Get CI/CD workflow runs workflow_runs = await get_workflow_runs.ainvoke({ "owner": "ai-forever", "repo": "giga_agent", "status": "completed", "branch": "main", "per_page": 50, "page": 1 }) # Results include PR data, commit info, review status, and CI status # URL fields are automatically filtered for cleaner output ``` -------------------------------- ### Explore Cities with Giga Agent and 2GIS Integration Source: https://context7.com/ai-forever/giga_agent/llms.txt This Python code snippet shows how to use the Giga Agent's city exploration module, integrated with the 2GIS API, to find points of interest like restaurants, hotels, and attractions. It requires a TWOGIS_TOKEN environment variable for authentication and returns a formatted guide with addresses, ratings, and map links. ```python # Find interesting places, hotels, restaurants with maps from giga_agent.agents.gis_agent.graph import city_explore city_guide = await city_explore.ainvoke({ "task": "Find top restaurants and tourist attractions in Saint Petersburg, Russia. Include map.", "state": { "messages": conversation_history } }) # Agent workflow nodes: # - attractions: Searches tourist spots via 2GIS API # - food: Finds restaurants and cafes # - hotels: Locates accommodations # # Returns formatted guide with addresses, ratings, and map links # Requires TWOGIS_TOKEN environment variable ``` -------------------------------- ### Read CSV Data with Pandas Source: https://github.com/ai-forever/giga_agent/blob/main/backend/graph/giga_agent/repl_tools/models/sentiment_model.ipynb Reads data from a CSV file named 'rusentiment_random_posts.csv' into a pandas DataFrame. Pandas is a powerful library for data manipulation and analysis in Python. This operation requires the `pandas` library to be installed. ```python import pandas as pd df = pd.read_csv("rusentiment_random_posts.csv") ``` -------------------------------- ### Create Memes with AI using Giga Agent Source: https://context7.com/ai-forever/giga_agent/llms.txt This Python snippet shows how to create memes using the Giga Agent's meme generation module. It takes a descriptive task and can utilize conversation history and a kernel ID for context. This agent requires GigaChat Kandinsky for character generation and serves as a good starting point for custom agent development. ```python # Create memes with AI-generated images and text from giga_agent.agents.meme_agent.graph import create_meme meme = await create_meme.ainvoke({ "meme_task": "Create a funny meme about debugging code at 3 AM with Sbercat character", "state": { "messages": conversation_history, "kernel_id": "kernel-id" } }) # Simple agent demonstrating custom subagent creation # Requires GigaChat Kandinsky for Sbercat character # Good starting point for building custom agents ``` -------------------------------- ### Get Text Embeddings using Giga Agent REPL Tools Source: https://context7.com/ai-forever/giga_agent/llms.txt This Python code shows how to obtain embeddings for a list of texts using the `get_embeddings` function from Giga Agent's REPL tools. It returns a NumPy array where each row represents the embedding vector for a corresponding input text. This is useful for various NLP tasks like similarity comparison. ```python # Get embeddings from giga_agent.repl_tools.sentiment import get_embeddings embeddings = get_embeddings([ "AI and machine learning", "Artificial intelligence applications" ]) # Returns: numpy array of embedding vectors ``` -------------------------------- ### Docker Deployment and Service Management Commands Source: https://context7.com/ai-forever/giga_agent/llms.txt This snippet outlines the make commands for initializing, building, running, and stopping Docker containers for the GigaAgent project. It details commands for development mode with hot-reloading and lists the default service URLs available after startup. ```bash make init_files make build make up # Services available after startup: # - Frontend: http://localhost:8502 # - LangGraph API: http://langgraph-api:8000 (internal) # - REPL Service: http://repl:9090 (internal) # - Tool Server: http://tool_server:9091 (internal) make build_dev make up_dev make down ``` -------------------------------- ### Generate Landing Pages with Giga Agent Source: https://context7.com/ai-forever/giga_agent/llms.txt This Python code demonstrates the use of the Giga Agent's landing page creation module to generate complete, responsive HTML landing pages with images. The agent can create various sections including hero, features, pricing, and contact forms. It follows a workflow of planning, image generation, and coding. ```python # Generate complete landing pages with images from giga_agent.agents.landing_agent.graph import create_landing landing = await create_landing.ainvoke({ "landing_task": "Create landing page for AI-powered project management tool. Include hero section, features, pricing, and contact form.", "state": { "messages": conversation_history } }) # Agent workflow: # 1. plan: Designs page structure and sections # 2. image: Generates hero and feature images # 3. coder: Builds complete HTML/CSS/JS page # # Returns fully functional, responsive HTML page ``` -------------------------------- ### Generate Podcast with SaluteSpeech TTS using Giga Agent Source: https://context7.com/ai-forever/giga_agent/llms.txt This snippet demonstrates how to generate a podcast from provided content or a conversation using the Giga Agent's podcast generation module. It leverages SaluteSpeech TTS for audio synthesis and allows configuration of podcast length, tone, and topic. The agent supports input from URLs or conversation history. ```python from giga_agent.agents.podcast.graph import podcast_generate podcast = await podcast_generate.ainvoke({ "podcast_task": "Create podcast about AI safety and alignment", "podcast_config": { "url": "https://example.com/ai-safety-article", # Optional: source URL "use_messages": True, # Use conversation history "length": "medium", # Options: short, medium "tone": "casual", # Options defined in TONE_MODIFIERS "question": "How do we ensure AI systems remain aligned with human values?" }, "state": { "messages": conversation_history } }) # Agent workflow: # 1. download_url: Scrapes content from URL # 2. summarize_messages: Extracts key points from chat # 3. script: Generates dialogue using LLM # 4. audio: Synthesizes speech with SaluteSpeech # # Returns: # { # "message": "Generated podcast at /runs/podcast.mp3", # "giga_attachments": [{ # "type": "audio/mp3", # "file_id": "uuid", # "path": "/runs/podcast.mp3", # "data": "base64-encoded-audio" # }] # } ``` -------------------------------- ### Web Search with giga_agent.tools.another.search Source: https://context7.com/ai-forever/giga_agent/llms.txt This snippet demonstrates performing internet searches using the `search` tool, which leverages Tavily. It shows how to input multiple search queries and outlines the expected output format, including content, URL, and title for each search result. ```python from giga_agent.tools.another import search search_results = await search.ainvoke({ "queries": [ "latest AI developments 2025", "LangGraph framework tutorials", "multi-agent systems best practices" ] }) # Returns: List of search results with content and source URLs # Output format: # [ # { # "content": "Summary of relevant information...", # "url": "https://source.com/article", # "title": "Article Title" # }, # ... # ] ``` -------------------------------- ### Generate Lean Canvas Business Model with Giga Agent Source: https://context7.com/ai-forever/giga_agent/llms.txt This Python snippet illustrates how to generate a Lean Canvas business model using the Giga Agent. The agent creates structured documentation covering key business aspects such as problem, solution, metrics, value proposition, customer segments, and revenue streams. It can optionally incorporate web search for market research. ```python # Generate Lean Canvas business model documentation from giga_agent.agents.lean_canvas import lean_canvas canvas = await lean_canvas.ainvoke({ "task": "Create Lean Canvas for SaaS startup providing AI code review for enterprises", "state": { "messages": conversation_history } }) # Creates structured business model covering: # - Problem, Solution, Key Metrics # - Unique Value Proposition # - Channels, Customer Segments # - Cost Structure, Revenue Streams # # Optionally uses web search for market research ``` -------------------------------- ### VKontakte Integration: Fetch Posts and Comments Source: https://context7.com/ai-forever/giga_agent/llms.txt Python code for integrating with VKontakte to fetch posts from a community wall and comments for a specific post. It utilizes functions from `giga_agent.tools.vk`. The `vk_get_posts` function takes a domain and count, while `vk_get_comments` requires owner ID and post ID. This can be combined with other tools for sentiment analysis and reporting. ```python # VK tools - Fetch posts and comments from VK communities from giga_agent.tools.vk import vk_get_posts, vk_get_comments, vk_get_last_comments # Get posts from VK wall posts = await vk_get_posts.ainvoke({ "domain": "ai_forever", # Community short name "offset": 0, "count": 100 # Maximum 100 per request }) # Get comments for specific post comments = await vk_get_comments.ainvoke({ "owner_id": "-123456789", # Community ID with '-' prefix "post_id": 12345, "offset": 0, "count": 100 }) # Use case: Sentiment analysis of community engagement # Combine with REPL tools for clustering and analysis: # 1. Fetch comments # 2. Use predict_sentiments() to analyze mood # 3. Cluster similar complaints or feedback # 4. Generate summary report ``` -------------------------------- ### Web Scraping with giga_agent.tools.scraper.get_urls Source: https://context7.com/ai-forever/giga_agent/llms.txt This snippet illustrates how to scrape and analyze webpage content using the `get_urls` tool from `giga_agent.tools.scraper`. It shows the parameters for providing URLs and state messages for context, and describes the expected output of processed content fragments. ```python from giga_agent.tools.scraper import get_urls scraped_data = await get_urls.ainvoke({ "urls": ["https://example.com/article"], "state": {"messages": [{"role": "user", "content": "Extract key points about AI agents"}]}, "config": {"configurable": {"thread_id": "thread-123"}} }) # Returns processed content with: # - Relevant text fragments ``` -------------------------------- ### Summarize Text using Giga Agent REPL Tools Source: https://context7.com/ai-forever/giga_agent/llms.txt This Python snippet demonstrates text summarization using the `summarize` function from Giga Agent's REPL tools. It takes a long text and an optional `max_tokens` parameter to control the summary length, returning a concise summary generated by an LLM. This tool ensures secure LLM access. ```python # Text summarization from giga_agent.repl_tools.llm import summarize summary = summarize( "Very long article text here...", max_tokens=150 ) # Returns: concise summary generated by LLM ``` -------------------------------- ### Custom CSS for Presentations Source: https://github.com/ai-forever/giga_agent/blob/main/backend/graph/giga_agent/agents/presentation_agent/nodes/presentation.html This CSS code provides custom styling for presentations, including font choices, text colors, list styles, image sizing, and responsive adjustments for different screen sizes. It also includes styles for a print button. ```css /* Custom styles */ @import url('https://fonts.googleapis.com/css2?family=Roboto&display=swap'); body { font-family: 'Roboto', sans-serif; } h1, h2, h3, h4, h5, h6, p, span, div { color: white !important; } li { list-style: none; } section img { width: 100%; height: auto; } .reveal section img { display: block; margin-left: auto; margin-right: auto; } .reveal section { text-align: center; } @media screen and (max-width: 768px) { .reveal h1 { font-size: 2em; } .reveal h2 { font-size: 1.5em; } .reveal p { font-size: 1.2em; } } ul, ol { color: white; } .graph { margin: auto; } .graph .main-svg { border-radius: 20px; } .graph { max-width: 700px !important; } .left > .graph, .right > .graph { max-width: 500px !important; } .left > .content, .right > .content { max-width: 100% !important; } .horizontal-slide { display: flex; align-items: center; } .horizontal-slide > .left { flex: 1; text-align: left; padding-right: 40px; overflow-y: auto; } .horizontal-slide > .right { flex: 1; max-height: 60vh; display: flex; flex-direction: column; justify-content: center; align-items: center; max-width: 500px; } .img { border-radius: 20px; max-width: 400px !important; } img.graph { max-width: 500px !important; border-radius: 20px; } /* Print button */ .print-button { position: fixed; top: 12px; right: 12px; z-index: 9999; background: rgba(0, 0, 0, 0.6); color: #ffffff; border: 1px solid rgba(255, 255, 255, 0.3); border-radius: 8px; padding: 8px 12px; font-size: 14px; cursor: pointer; backdrop-filter: blur(4px); } .print-button:hover { background: rgba(255, 255, 255, 0.15); } @media print { .print-button { display: none !important; } } ``` -------------------------------- ### VKontakte Social Network Integration Source: https://context7.com/ai-forever/giga_agent/llms.txt Tools for fetching posts and comments from VK communities. ```APIDOC ## VKontakte Social Network Integration ### Description Tools for fetching posts and comments from VK communities. ### Method Asynchronous function calls (e.g., `ainvoke`) ### Endpoints - `vk_get_posts`: Fetches posts from a VK community's wall. - `vk_get_comments`: Fetches comments for a specific VK post. - `vk_get_last_comments`: Fetches the latest comments (usage not detailed in provided text, assumed similar to `vk_get_comments`). ### Parameters #### `vk_get_posts` - **domain** (string) - Required - The community's short name (e.g., 'ai_forever'). - **offset** (integer) - Optional - The number of posts to skip. - **count** (integer) - Optional - The number of posts to retrieve (maximum 100). #### `vk_get_comments` - **owner_id** (string) - Required - The community ID, prefixed with '-'. - **post_id** (integer) - Required - The ID of the post. - **offset** (integer) - Optional - The number of comments to skip. - **count** (integer) - Optional - The number of comments to retrieve (maximum 100). ### Request Example (vk_get_posts) ```python await vk_get_posts.ainvoke({ "domain": "ai_forever", "offset": 0, "count": 100 }) ``` ### Response Example (vk_get_posts) Returns a list of posts from the specified VK community. ``` -------------------------------- ### JavaScript Print/PDF Helper Functionality Source: https://github.com/ai-forever/giga_agent/blob/main/backend/graph/giga_agent/agents/presentation_agent/nodes/presentation.html This JavaScript code handles the integration with presentation frameworks for print and PDF generation. It injects necessary stylesheets for PDF printing and manages the functionality of a print button to open a new tab with print parameters. ```javascript // Print/PDF helpers const urlParams = new URLSearchParams(window.location.search); const isPrintPdf = urlParams.has('print-pdf') || /print-pdf/gi.test(window.location.search); // Inject Reveal's PDF print stylesheet when in print mode if (isPrintPdf) { const link = document.createElement('link'); link.rel = 'stylesheet'; link.href = 'https://cdn.jsdelivr.net/npm/reveal.js@4/dist/print/pdf.css'; document.head.appendChild(link); } // Handle print button click: open a new tab with print params const printBtn = document.querySelector('.print-button'); if (printBtn) { printBtn.addEventListener('click', () => { const url = new URL(window.location.href); url.searchParams.set('print-pdf', '1'); url.searchParams.set('autoprint', '1'); window.open(url.toString(), '_blank'); }); } setTimeout(() => { // Initialize RevealJS Reveal.initialize({ hash: true, controls: !isPrintPdf, progress: !isPrintPdf, history: true, keyboard: true, overview: true, touch: true, fragments: true, embedded: false, help: true, pause: true, countdown: false, transition: 'slide', backgroundTransition: 'fade', dependencies: [], plugins: [RevealMath.KaTeX] }); // Auto-open print dialog when in print mode if (isPrintPdf) { // Allow disabling via ?autoprint=0 or ?noautoprint const shouldAuto = !( urlParams.get('autoprint') === '0' || urlParams.has('noautoprint') ); // Close tab when user finishes or cancels printing let printStarted = false; const safeClose = () => { try { window.close(); } catch (e) { /* noop */ } }; window.addEventListener('beforeunload', (event) => { if (printStarted && shouldAuto) { // Schedule close to allow print dialog to show setTimeout(safeClose, 100); } }); if (shouldAuto) { Reveal.addEventListener('ready', (event) => { // Use a timeout to ensure the print dialog appears after the initial render setTimeout(() => { printStarted = true; window.print(); }, 1000); }); } } }, 100); ``` -------------------------------- ### GitHub Integration Source: https://context7.com/ai-forever/giga_agent/llms.txt Tools for interacting with the GitHub API to manage pull requests and workflow runs. ```APIDOC ## GitHub Integration ### Description Tools for interacting with the GitHub API to manage pull requests and workflow runs. ### Method Asynchronous function calls (e.g., `ainvoke`) ### Endpoints - `list_pull_requests`: Lists pull requests from a repository. - `get_pull_request`: Retrieves details for a specific pull request. - `get_workflow_runs`: Fetches CI/CD workflow runs for a repository. ### Parameters #### `list_pull_requests` - **owner** (string) - Required - The owner of the repository. - **repo** (string) - Required - The name of the repository. - **state** (string) - Optional - The state of the pull requests (e.g., 'open', 'closed'). - **per_page** (integer) - Optional - Number of items per page. - **page** (integer) - Optional - The page number. - **sort** (string) - Optional - The field to sort by (e.g., 'updated'). - **direction** (string) - Optional - The sort direction ('asc' or 'desc'). #### `get_pull_request` - **owner** (string) - Required - The owner of the repository. - **repo** (string) - Required - The name of the repository. - **pull_number** (integer) - Required - The number of the pull request. #### `get_workflow_runs` - **owner** (string) - Required - The owner of the repository. - **repo** (string) - Required - The name of the repository. - **status** (string) - Optional - The status of the workflow runs (e.g., 'completed'). - **branch** (string) - Optional - The branch name. - **per_page** (integer) - Optional - Number of items per page. - **page** (integer) - Optional - The page number. ### Request Example (list_pull_requests) ```python await list_pull_requests.ainvoke({ "owner": "ai-forever", "repo": "giga_agent", "state": "open", "per_page": 30, "page": 1, "sort": "updated", "direction": "desc" }) ``` ### Response Example (list_pull_requests) Results include PR data, commit info, review status, and CI status. URL fields are automatically filtered for cleaner output. ``` -------------------------------- ### Presentation Generation Agent Source: https://context7.com/ai-forever/giga_agent/llms.txt Python code for creating Reveal.js presentations using the `generate_presentation` function from `giga_agent.agents.presentation_agent.graph`. This agent takes a presentation task description, which can include text and attachments like charts, and an optional state. It orchestrates planning, image creation, and slide generation, outputting an HTML presentation file. ```python # Create Reveal.js presentations with AI-generated slides and images from giga_agent.agents.presentation_agent.graph import generate_presentation presentation = await generate_presentation.ainvoke({ "presentation_task": "Create a 10-slide presentation about multi-agent AI systems. Include: architecture overview, key components, use cases, and future trends. Attach this chart: attachment:/runs/graphs/agent_performance.png", "state": { "messages": conversation_history, "kernel_id": "kernel-id" } }) # Agent workflow: # 1. plan_node: Generates presentation structure # 2. image_node: Creates images for slides # 3. slides_node: Builds HTML presentation with Reveal.js # # Returns: # { # "message": "Generated HTML page at /runs/presentation.html", # "giga_attachments": [{ # "type": "text/html", # "file_id": "uuid", # "path": "/runs/presentation.html", # "data": "..." # }] # } ``` -------------------------------- ### Handle Browser Print Events with JavaScript Source: https://github.com/ai-forever/giga_agent/blob/main/backend/graph/giga_agent/agents/presentation_agent/nodes/presentation.html This snippet sets up event listeners for various browser print-related events. It captures the 'beforeprint' event to set a flag, and the 'afterprint' event to trigger a 'safeClose' function. It also uses a media query to detect when the print view is exited and calls 'safeClose' if printing was initiated. ```javascript er('beforeprint', () => { printStarted = true; }); window.addEventListener('afterprint', () => { safeClose(); }); const mediaQuery = window.matchMedia && window.matchMedia('print'); if (mediaQuery) { if ('addEventListener' in mediaQuery) { mediaQuery.addEventListener('change', (e) => { if (!e.matches && printStarted) safeClose(); }); } else if ('addListener' in mediaQuery) { mediaQuery.addListener((e) => { if (!e.matches && printStarted) safeClose(); }); } } document.addEventListener('visibilitychange', () => { if (document.visibilityState === 'visible' && printStarted) { safeClose(); } }); Reveal.on('ready', () => { setTimeout(() => { if (shouldAuto) window.print(); }, 500); }); ``` -------------------------------- ### Load Environment Variables with dotenv Source: https://github.com/ai-forever/giga_agent/blob/main/backend/graph/giga_agent/repl_tools/models/sentiment_model.ipynb Loads environment variables from a .env file into the current environment. This is often the first step in configuring applications that rely on external configurations such as API keys or database credentials. It requires the `dotenv` library. ```python from dotenv import load_dotenv load_dotenv() ``` -------------------------------- ### Weather Information Retrieval Source: https://context7.com/ai-forever/giga_agent/llms.txt A tool to retrieve current weather conditions and a 5-day forecast for a specified city. ```APIDOC ## Weather Information Retrieval ### Description A tool to retrieve current weather conditions and a 5-day forecast for a specified city. ### Method Asynchronous function calls (e.g., `ainvoke`) ### Endpoint `weather` ### Parameters - **city** (string) - Required - The name of the city for which to retrieve weather data. - **units** (string) - Optional - The units for temperature. Options: 'c' (Celsius), 'f' (Fahrenheit), 'k' (Kelvin). Defaults to Celsius if not specified. - **lang** (string) - Optional - The language for weather descriptions. Defaults to 'en'. ### Request Example ```python await weather.ainvoke({ "city": "Moscow", "units": "c", "lang": "en" }) ``` ### Response #### Success Response (200) Returns formatted text containing: - **Current Weather**: - Conditions, Temperature (now/high/low) - Pressure, Humidity, Feels Like - Wind Speed/Direction - Sunrise/Sunset times - **5-Day Forecast**: - Date/Time intervals - Conditions and temperatures - High/Low predictions ``` -------------------------------- ### Filter Tools by Environment Variables Source: https://context7.com/ai-forever/giga_agent/llms.txt This Python code snippet demonstrates filtering a list of tools based on the presence of required environment variables. It's crucial for ensuring tools requiring specific API keys or configurations are only enabled when those dependencies are met. The `filter_tools_by_env` function (implementation not shown) likely checks for necessary environment variables before returning a subset of the provided tools. ```python SERVICE_TOOLS = filter_tools_by_env([ weather, vk_get_posts, vk_get_comments, get_workflow_runs, list_pull_requests, get_pull_request, get_documents, # RAG knowledge base ]) AGENTS = filter_tools_by_env([ gen_image, search, get_urls, lean_canvas, generate_presentation, create_landing, podcast_generate, create_meme, city_explore, ]) TOOLS = [python, shell] + AGENTS + SERVICE_TOOLS REPL_TOOLS = [predict_sentiments, summarize, get_embeddings] ``` -------------------------------- ### Image Analysis with Vision LLM Source: https://context7.com/ai-forever/giga_agent/llms.txt Python code for analyzing images using a vision-capable LLM via the `ask_about_image` function in `giga_agent.tools.another`. This function takes an image path (from `/runs/` or `/files/` directories) and a question. It returns a detailed LLM analysis of the image content, suitable for iterative follow-up questions. ```python # Analyze images using vision-capable LLM from giga_agent.tools.another import ask_about_image analysis = await ask_about_image.ainvoke({ "image_path": "/runs/images/chart.png", "question": "Analyze this chart. What are the key trends? What insights can you extract about the data patterns and anomalies?" }) # Supports images from: # - /runs/ directory (generated by code execution) # - /files/ directory (user-uploaded files) # # Returns detailed LLM analysis response # Use iteratively for follow-up questions if needed ``` -------------------------------- ### Prepare Data for Machine Learning with NumPy and Scikit-learn Source: https://github.com/ai-forever/giga_agent/blob/main/backend/graph/giga_agent/repl_tools/models/sentiment_model.ipynb Stacks the embedding vectors from the 'emb' column of a DataFrame into a single NumPy array `X`. This array is typically used as the feature set for machine learning models. It requires the `numpy` library and a DataFrame `filtered_df` with an 'emb' column containing embeddable data. ```python import numpy as np from sklearn.linear_model import LogisticRegression from sklearn.metrics import classification_report from sklearn.model_selection import train_test_split X = np.vstack(filtered_df["emb"].values) ``` -------------------------------- ### Presentation Generation Agent Source: https://context7.com/ai-forever/giga_agent/llms.txt An agent that creates Reveal.js presentations with AI-generated slides and images based on a given task. ```APIDOC ## Presentation Generation Agent ### Description An agent that creates Reveal.js presentations with AI-generated slides and images based on a given task. The agent follows a workflow involving planning, image creation, and slide building. ### Method Asynchronous function calls (e.g., `ainvoke`) ### Endpoint `generate_presentation` ### Parameters - **presentation_task** (string) - Required - A detailed description of the presentation content, including the number of slides, topics, and optionally, attachments (e.g., 'attachment:/runs/graphs/agent_performance.png'). - **state** (object) - Optional - The current state of the conversation or session, may include: - **messages** (array) - Conversation history. - **kernel_id** (string) - Identifier for a kernel. ### Request Example ```python await generate_presentation.ainvoke({ "presentation_task": "Create a 10-slide presentation about multi-agent AI systems. Include: architecture overview, key components, use cases, and future trends. Attach this chart: attachment:/runs/graphs/agent_performance.png", "state": { "messages": conversation_history, "kernel_id": "kernel-id" } }) ``` ### Response #### Success Response (200) - **message** (string) - A message indicating where the generated HTML presentation is saved (e.g., '/runs/presentation.html'). - **giga_attachments** (array) - An array containing the generated HTML presentation: - **type** (string) - The MIME type of the attachment ('text/html'). - **file_id** (string) - A unique identifier for the file. - **path** (string) - The file path to the generated presentation. - **data** (string) - The HTML content of the presentation. ### Agent Workflow 1. **plan_node**: Generates the presentation structure and outline. 2. **image_node**: Creates necessary images for the slides. 3. **slides_node**: Builds the final HTML presentation using Reveal.js. ``` -------------------------------- ### JavaScript Image and Graph Handling Source: https://github.com/ai-forever/giga_agent/blob/main/backend/graph/giga_agent/agents/presentation_agent/nodes/presentation.html This JavaScript code includes functions to determine if a path points to an image file and to create image elements dynamically. It also handles the replacement of placeholder elements with actual images or Plotly graphs based on source attributes. ```javascript function isImageInPath(path) { const lower = path.toLowerCase(); const dotIdx = lower.lastIndexOf("."); const ext = dotIdx >= 0 ? lower.slice(dotIdx + 1) : ""; const imageExt = ["png", "jpg", "jpeg", "gif", "webp", "bmp", "svg"]; return imageExt.includes(ext); } function createImage(el, path) { const uuid = crypto.randomUUID(); const d = document.createElement('img'); d.attributes = el.attributes; const attributes = $(el).prop("attributes"); $.each(attributes, function () { $(d).attr(this.name, this.value); }); d.src = `/files/${path}`; d.setAttribute('id', uuid); d.removeAttribute("data-src"); el.parentNode.replaceChild(d, el); } // Replace placeholders for graphs/images jQuery('.graph').each((index, el) => { const src = el.getAttribute('src') ? el.getAttribute('src') : el.getAttribute('data-src'); if (src.startsWith("attachment:") || src.startsWith("graph:")) { let graphId = src.replace(/^attachment:/, ""); graphId = graphId.replace(/^graph:/, ""); if (graphId.startsWith("/home/jupyter") && isImageInPath(graphId)) { createImage(el, graphId) } else { fetch(`/graph/store/items?namespace=attachments&key=${graphId}`).then((res) => { res.json().then((json) => { if (json.value.file_type === "image") { createImage(el, json.value.path) } else if (json.value.file_type === "plotly_graph") { fetch(`/files/${json.value.path}`).then((res) => { res.json().then((data) => { const uuid = crypto.randomUUID(); const d = document.createElement('div'); d.innerHTML = el.innerHTML; d.attributes = el.attributes; const attributes = $(el).prop("attributes"); $.each(attributes, function () { $(d).attr(this.name, this.value); }); el.parentNode.replaceChild(d, el); el = d; el.setAttribute('id', uuid); Plotly.newPlot(uuid, data.data, data.layout, data.config); }) }); } }); }); } } }); ``` -------------------------------- ### Image Analysis with Vision LLM Source: https://context7.com/ai-forever/giga_agent/llms.txt Analyzes images using a vision-capable LLM based on a provided question. ```APIDOC ## Image Analysis with Vision LLM ### Description Analyzes images using a vision-capable LLM based on a provided question. Supports images from the `/runs/` directory (generated by code execution) and `/files/` directory (user-uploaded files). ### Method Asynchronous function calls (e.g., `ainvoke`) ### Endpoint `ask_about_image` ### Parameters - **image_path** (string) - Required - The path to the image file to be analyzed. - **question** (string) - Required - The question to ask about the image. ### Request Example ```python await ask_about_image.ainvoke({ "image_path": "/runs/images/chart.png", "question": "Analyze this chart. What are the key trends? What insights can you extract about the data patterns and anomalies?" }) ``` ### Response #### Success Response (200) Returns a detailed LLM analysis response based on the provided image and question. The analysis can be used iteratively for follow-up questions. ``` -------------------------------- ### Image Generation Source: https://context7.com/ai-forever/giga_agent/llms.txt Generates images using multiple AI providers based on a given theme. ```APIDOC ## Image Generation ### Description Generates images using multiple AI providers based on a given theme. The LLM automatically improves the prompt for better results. ### Method Asynchronous function calls (e.g., `ainvoke`) ### Endpoint `gen_image` ### Parameters - **theme** (string) - Required - A description of the desired image content. - **config** (object) - Optional - Configuration for the generation, may include: - **configurable** (object) - Specific configuration details: - **thread_id** (string) - Identifier for a thread. ### Request Example ```python await gen_image.ainvoke({ "theme": "Modern AI assistant helping developer write code", "config": {"configurable": {"thread_id": "thread-123"}} }) ``` ### Response #### Success Response (200) - **image_description** (string) - The enhanced prompt used for generation. - **message** (string) - A message indicating where the image was saved (e.g., '/runs/images/uuid.png'). - **giga_attachments** (array) - An array of attachment objects: - **type** (string) - The MIME type of the attachment (e.g., 'image/png'). - **file_id** (string) - A unique identifier for the file. - **path** (string) - The file path to the generated image. - **data** (string) - The base64-encoded image data. ### Supported Providers - "gigachat:kandinsky-4.1" (GigaChat API) - "fusion_brain:kandinsky-3.0" (FusionBrain/100 free generations) - "openai:dall-e-3" (OpenAI) (Specified via `IMAGE_GEN_NAME` environment variable) ``` -------------------------------- ### Weather Information Retrieval Source: https://context7.com/ai-forever/giga_agent/llms.txt Python code to retrieve current weather conditions and a 5-day forecast for a specified city using the `giga_agent.tools.weather` module. The `weather` function accepts city, units (Celsius, Fahrenheit, or Kelvin), and language. The output is a formatted text string containing detailed current weather information and a multi-day forecast. ```python # Weather tool - Current weather and 5-day forecast from giga_agent.tools.weather import weather weather_data = await weather.ainvoke({ "city": "Moscow", "units": "c", # Options: c (Celsius), f (Fahrenheit), k (Kelvin) "lang": "en" # Language for descriptions }) # Returns formatted text with: # Current Weather: # - Conditions, Temperature (now/high/low) # - Pressure, Humidity, Feels Like # - Wind Speed/Direction # - Sunrise/Sunset times # # 5-Day Forecast: # - Date/Time intervals # - Conditions and temperatures # - High/Low predictions ``` -------------------------------- ### Perform Sentiment Analysis using Giga Agent REPL Tools Source: https://context7.com/ai-forever/giga_agent/llms.txt This Python snippet demonstrates how to perform sentiment analysis on a list of texts using the `predict_sentiments` function from Giga Agent's REPL tools. It returns a list of sentiment labels corresponding to the input texts. This tool is designed for secure access within a REPL environment. ```python # Sentiment analysis from giga_agent.repl_tools.sentiment import predict_sentiments sentiments = predict_sentiments([ "This product is amazing!", "Terrible experience, very disappointed", "It's okay, nothing special" ]) # Returns: ['positive', 'negative', 'neutral'] ``` -------------------------------- ### Load Embeddings with Giga Agent Utility Source: https://github.com/ai-forever/giga_agent/blob/main/backend/graph/giga_agent/repl_tools/models/sentiment_model.ipynb Initializes and loads embeddings using the `load_embeddings` function from the `giga_agent.utils.llm` module. This function is likely used to prepare text data for natural language processing tasks by converting it into numerical vector representations. It depends on the `giga_agent` library. ```python from giga_agent.utils.llm import load_embeddings emb = load_embeddings() ``` -------------------------------- ### Image Generation with Multiple Providers Source: https://context7.com/ai-forever/giga_agent/llms.txt Python code to generate images using the `gen_image` function from `giga_agent.tools.another`. It supports multiple image generation providers configurable via the `IMAGE_GEN_NAME` environment variable, including GigaChat, FusionBrain, and OpenAI's DALL-E 3. The function takes a theme and optional configuration, and returns a description of the generated image and its location. ```python # Generate images with multiple providers from giga_agent.tools.another import gen_image generated_image = await gen_image.ainvoke({ "theme": "Modern AI assistant helping developer write code", "config": {"configurable": {"thread_id": "thread-123"}} }) # LLM automatically improves the prompt for better results # Supported providers (via IMAGE_GEN_NAME env var): # - "gigachat:kandinsky-4.1" (GigaChat API) # - "fusion_brain:kandinsky-3.0" (FusionBrain/100 free generations) # - "openai:dall-e-3" (OpenAI) # Returns: # { # "image_description": "Enhanced prompt used for generation", # "message": "Image generated at /runs/images/uuid.png", # "giga_attachments": [{ # "type": "image/png", # "file_id": "uuid", # "path": "/runs/images/uuid.png", # "data": "base64-encoded-image" # }] # } ``` -------------------------------- ### Embed Documents using Loaded Embeddings Source: https://github.com/ai-forever/giga_agent/blob/main/backend/graph/giga_agent/repl_tools/models/sentiment_model.ipynb Generates embeddings for the 'text' column of a filtered DataFrame using a pre-loaded embeddings object `emb`. The `embed_documents` method converts text data into numerical vector representations, suitable for machine learning tasks. This requires the `emb` object to be initialized and the `filtered_df` to have a 'text' column. ```python embs = emb.embed_documents(list(filtered_df["text"])). ``` -------------------------------- ### Add Embeddings to DataFrame Source: https://github.com/ai-forever/giga_agent/blob/main/backend/graph/giga_agent/repl_tools/models/sentiment_model.ipynb Assigns a list of generated embeddings (`embs`) as a new column named 'emb' to the `filtered_df` DataFrame. This operation enriches the DataFrame with vector representations of the text data, preparing it for further analysis or model training. It assumes `filtered_df` and `embs` have been correctly prepared in previous steps. ```python filtered_df["emb"] = embs ```