### Cloudflare Pages Deployment (Frontend) Source: https://context7.com/kritsanan1/facebook-gemini-agents/llms.txt Guides the deployment of the TypeScript/JavaScript frontend to Cloudflare Pages. It covers installing dependencies, building the frontend, and deploying to production or preview environments, leveraging Vite and Hono for edge computing. ```bash # Install dependencies npm install # Build the frontend npm run build # Deploy to Cloudflare Pages npm run deploy # Deploy to production environment npm run deploy:prod # Preview deployment locally npm run preview # Development with sandbox mode npm run dev:sandbox # The deployment includes: # - Vite build system for fast bundling # - Hono framework for edge API routes # - TypeScript support with type generation # - Cloudflare Workers integration ``` -------------------------------- ### TypeScript Agent Client Example Source: https://context7.com/kritsanan1/facebook-gemini-agents/llms.txt Example demonstrating how to use the TypeScript agent client to interact with the Facebook Gemini Agents. ```APIDOC ## TypeScript Agent Client Example ### Description Example usage of the TypeScript agent client for generating content and checking agent status. ### Code Example ```typescript import { FacebookAgentCrew } from './agents/facebook-agent-crew'; // Initialize the crew with necessary credentials const crew = new FacebookAgentCrew({ geminiApiKey: 'your_gemini_api_key', facebookAccessToken: 'your_facebook_token', pageId: 'your_page_id' }); // Initialize agents within the crew await crew.initializeCrew(); // Generate content based on a prompt and tone const content = await crew.generateContent('summer vacation tips', 'enthusiastic'); // Get the current status of the agents const status = crew.getAgentStatus(); console.log(status); /* Example Output: { status: 'active', agents: [ // ... details about active agents ... ] } */ ``` ### Initialization Parameters - **geminiApiKey** (string) - Required - Your Google Gemini API key. - **facebookAccessToken** (string) - Required - Your Facebook access token. - **pageId** (string) - Required - The ID of the Facebook page. ### Methods - **initializeCrew()**: Initializes the agents within the crew. - **generateContent(prompt: string, tone: string)**: Generates content based on the provided prompt and tone. - **getAgentStatus()**: Returns the current status of the agents. ``` -------------------------------- ### Clone and Install Python Dependencies Source: https://github.com/kritsanan1/facebook-gemini-agents/blob/main/SETUP_GUIDE.md Clones the project repository and installs required Python packages using pip. Ensure you have Python 3.11+ installed. ```bash git clone cd facebook-gemini-agents pip install -r requirements.txt ``` -------------------------------- ### Configure Environment Variables Source: https://github.com/kritsanan1/facebook-gemini-agents/blob/main/SETUP_GUIDE.md Copies the example environment file and instructs the user to edit it with their specific API credentials for Facebook and Google Gemini. ```bash cp .env.example .env # Edit .env with your API credentials ``` -------------------------------- ### Docker Deployment Source: https://context7.com/kritsanan1/facebook-gemini-agents/llms.txt Instructions for deploying the application using Docker Compose, including building, starting, viewing logs, and stopping services. ```APIDOC ## Docker Deployment ### Description Deploy the entire system using Docker Compose with all dependencies. ### Commands - **Build and start all services in detached mode:** ```bash docker-compose up -d ``` This command starts the `app` (FastAPI), `redis`, and `nginx` services. - **View logs for the `app` service in real-time:** ```bash docker-compose logs -f app ``` - **Stop all services defined in `docker-compose.yml`:** ```bash docker-compose down ``` - **Rebuild images and restart services (useful after code changes):** ```bash docker-compose up -d --build ``` ### Services Started - **app**: The main Python FastAPI application, typically exposed on port 8000. - **redis**: The Redis caching layer, typically exposed on port 6379. - **nginx**: A reverse proxy, typically exposed on ports 80 (HTTP) and 443 (HTTPS). ``` -------------------------------- ### Docker Compose for Deployment Source: https://github.com/kritsanan1/facebook-gemini-agents/blob/main/SETUP_GUIDE.md Commands to build and manage Docker containers for the application. Includes starting services, viewing logs, and stopping services using `docker-compose`. ```bash # Build and start services docker-compose up -d # Check logs docker-compose logs -f # Stop services docker-compose down ``` -------------------------------- ### Cloudflare Pages Deployment Source: https://context7.com/kritsanan1/facebook-gemini-agents/llms.txt Guide for deploying the TypeScript/JavaScript frontend to Cloudflare Pages, including build and deployment commands. ```APIDOC ## Cloudflare Pages Deployment ### Description Deploy the TypeScript/JavaScript frontend to Cloudflare Pages with edge computing capabilities. ### Commands - **Install project dependencies:** ```bash npm install ``` - **Build the frontend for production:** ```bash npm run build ``` - **Deploy to Cloudflare Pages:** ```bash npm run deploy ``` - **Deploy to the production environment:** ```bash npm run deploy:prod ``` - **Preview deployment locally:** ```bash npm run preview ``` - **Run development with sandbox mode:** ```bash npm run dev:sandbox ``` ### Features Included - Vite build system for fast bundling. - Hono framework for edge API routes. - TypeScript support with type generation. - Cloudflare Workers integration for edge computing. ``` -------------------------------- ### Webhook Setup for Real-Time Messages Source: https://context7.com/kritsanan1/facebook-gemini-agents/llms.txt Instructions for setting up Facebook webhooks to receive real-time messages and events, including verification endpoint. ```APIDOC ## Webhook Setup for Real-Time Messages ### Description Configure Facebook webhooks to receive real-time messages and events. ### Setup Steps 1. Create a FastAPI application. 2. Implement a webhook verification endpoint. 3. Set up the Facebook Developer App to point to your webhook URL. ### Verification Endpoint This endpoint handles the initial subscription verification request from Facebook. #### Endpoint `/api/webhook/facebook` #### Method `GET` #### Query Parameters - **hub_mode** (string) - Required - Should be 'subscribe'. - **hub_challenge** (string) - Required - A random string provided by Facebook. - **hub_verify_token** (string) - Required - Your custom verify token configured in the Facebook App settings. #### Request Example ``` GET /api/webhook/facebook?hub_mode=subscribe&hub_challenge=314159265&hub_verify_token=YOUR_VERIFY_TOKEN ``` #### Response (Success) Returns the `hub_challenge` value as an integer if verification is successful. #### Response (Error) Returns an error message if verification fails. #### Example Implementation (FastAPI) ```python from fastapi import FastAPI, Request app = FastAPI() # Replace 'YOUR_VERIFY_TOKEN' with your actual verify token VERIFY_TOKEN = "YOUR_VERIFY_TOKEN" @app.get("/api/webhook/facebook") async def verify_webhook( hub_mode: str, hub_challenge: str, hub_verify_token: str ): if hub_mode == "subscribe" and hub_verify_token == VERIFY_TOKEN: return int(hub_challenge) return {"error": "Verification failed"} # Add a POST endpoint to handle incoming messages and events @app.post("/api/webhook/facebook") async def handle_webhook(request: Request): # Process incoming messages and events here payload = await request.json() # Example: Log the payload print(payload) return {"status": "received"} ``` ``` -------------------------------- ### Docker Compose Deployment Source: https://context7.com/kritsanan1/facebook-gemini-agents/llms.txt Instructions for deploying the entire system using Docker Compose. This includes commands to build, start, view logs, stop, and rebuild services managed by Docker Compose, such as the application, Redis, and Nginx. ```bash # Build and start all services docker-compose up -d # Services started: # - app: Main Python FastAPI application (port 8000) # - redis: Caching layer (port 6379) # - nginx: Reverse proxy (ports 80/443) # View logs docker-compose logs -f app # Stop all services docker-compose down # Rebuild after code changes docker-compose up -d --build ``` -------------------------------- ### Run Facebook Gemini Agents Application Source: https://github.com/kritsanan1/facebook-gemini-agents/blob/main/SETUP_GUIDE.md Provides commands to start the application's API server and demonstrates a command-line interface usage for content generation. Assumes Python environment is set up. ```bash # Start the API server python src/api/main.py # Or use the CLI python main.py content-generate --topic "summer vacation ideas" ``` -------------------------------- ### Facebook Agent Client (TypeScript) Source: https://context7.com/kritsanan1/facebook-gemini-agents/llms.txt An example demonstrating how to use the TypeScript agent client to interact with Facebook. This involves initializing a `FacebookAgentCrew` with API keys and page ID, generating content, and checking agent status. ```javascript // Example: Using the TypeScript agent client import { FacebookAgentCrew } from './agents/facebook-agent-crew'; const crew = new FacebookAgentCrew({ geminiApiKey: 'your_gemini_api_key', facebookAccessToken: 'your_facebook_token', pageId: 'your_page_id' }); // Initialize agents await crew.initializeCrew(); // Generate content const content = await crew.generateContent('summer vacation tips', 'enthusiastic'); // Check agent status const status = crew.getAgentStatus(); console.log(status); // Output: { status: 'active', agents: [...] } ``` -------------------------------- ### Python: Handle Customer Service Message Source: https://github.com/kritsanan1/facebook-gemini-agents/blob/main/SETUP_GUIDE.md Example Python code showing how to utilize the `customer_service_agent` to handle incoming customer messages, returning a response and identifying the user's intent. Requires the `customer_service_agent` to be imported. ```python from src.agents.customer_service_agent import customer_service_agent # Handle customer message result = customer_service_agent.handle_message( message="I need help with my order", sender_info={'name': 'John'} ) print(result['response']) print(f"Intent: {result['intent']}") ``` -------------------------------- ### Python: Generate Facebook Content Source: https://github.com/kritsanan1/facebook-gemini-agents/blob/main/SETUP_GUIDE.md Example Python code demonstrating how to use the `content_agent` to generate a Facebook post, including its content and relevant hashtags. Requires the `content_agent` to be imported. ```python from src.agents.content_agent import content_agent # Generate a Facebook post post = content_agent.create_post( topic="summer vacation", tone="friendly", length="medium" ) print(post['content']) print(post['hashtags']) ``` -------------------------------- ### GET /api/agents/service/metrics Source: https://context7.com/kritsanan1/facebook-gemini-agents/llms.txt Retrieves customer service metrics and response statistics. ```APIDOC ## GET /api/agents/service/metrics ### Description Retrieves key performance indicators related to customer service operations, including message handling, response times, and intent distribution. ### Method GET ### Endpoint /api/agents/service/metrics ### Parameters None ### Response #### Success Response (200) - **metrics** (object) - An object containing various customer service metrics. - **total_messages_handled** (integer) - The total number of messages processed. - **average_response_time** (string) - The average time taken to respond to messages (e.g., "2.3s"). - **intents_detected** (object) - A breakdown of detected intents and their counts. - **GENERAL_QUESTION** (integer) - Count for general questions. - **ORDER_INQUIRY** (integer) - Count for order-related inquiries. - **TECHNICAL_SUPPORT** (integer) - Count for technical support requests. - **COMPLAINT** (integer) - Count for customer complaints. - **escalation_rate** (number) - The percentage of conversations that required escalation. - **customer_satisfaction** (number) - The average customer satisfaction score. - **timestamp** (string) - The timestamp when the metrics were generated. - **status** (string) - The current status of the service (e.g., "active", "maintenance"). #### Response Example ```json { "metrics": { "total_messages_handled": 1523, "average_response_time": "2.3s", "intents_detected": { "GENERAL_QUESTION": 512, "ORDER_INQUIRY": 234, "TECHNICAL_SUPPORT": 156, "COMPLAINT": 89 }, "escalation_rate": 0.12, "customer_satisfaction": 4.6 }, "timestamp": "2024-07-15T10:30:00.000Z", "status": "active" } ``` ``` -------------------------------- ### GET /api/agents Source: https://context7.com/kritsanan1/facebook-gemini-agents/llms.txt Retrieves information about all available AI agents and their capabilities. ```APIDOC ## GET /api/agents ### Description Retrieves a list of all available AI agents, their roles, status, and supported capabilities. ### Method GET ### Endpoint /api/agents ### Parameters None ### Response #### Success Response (200) - **agents** (object) - An object where keys are agent identifiers and values are agent details. - **agent_id** (object) - **name** (string) - The display name of the agent. - **role** (string) - The primary role or function of the agent. - **status** (string) - The current operational status of the agent (e.g., "active", "inactive"). - **capabilities** (array of strings) - A list of actions or tasks the agent can perform. - **total_agents** (integer) - The total number of agents available. - **status** (string) - The overall status of the agent system. #### Response Example ```json { "agents": { "content_agent": { "name": "Content Creator", "role": "Social Media Content Creator", "status": "active", "capabilities": ["create_post", "optimize_content", "generate_calendar"] }, "customer_service_agent": { "name": "Customer Support", "role": "Customer Service Representative", "status": "active", "capabilities": ["handle_message", "create_quick_replies", "qualify_leads"] }, "analytics_agent": { "name": "Analytics Expert", "role": "Performance Analyst", "status": "active", "capabilities": ["analyze_performance", "identify_trending", "recommend_schedule"] } }, "total_agents": 3, "status": "active" } ``` ``` -------------------------------- ### Get Customer Service Metrics via REST API Source: https://context7.com/kritsanan1/facebook-gemini-agents/llms.txt This API endpoint fetches key performance metrics for the customer service operations. It returns data such as total messages handled, average response time, intent distribution, escalation rate, and customer satisfaction scores. This is a GET request. ```bash curl -X GET http://localhost:8000/api/agents/service/metrics \ -H "Content-Type: application/json" ``` -------------------------------- ### REST API: Content Generation Endpoint Source: https://context7.com/kritsanan1/facebook-gemini-agents/llms.txt Provides an HTTP POST endpoint for generating Facebook content. This is a command-line interface example for interacting with the content generation service. ```bash # Example usage for content generation endpoint (details not provided in snippet) # curl -X POST -H "Content-Type: application/json" -d '{"prompt": "Generate a post about our summer sale."}' http://your-api-endpoint/generate-content ``` -------------------------------- ### Retrieve Agent Information via REST API Source: https://context7.com/kritsanan1/facebook-gemini-agents/llms.txt This GET API endpoint provides information about all available AI agents within the system. It details each agent's name, role, status, and capabilities. The response includes a summary of total agents and the system status. ```bash curl -X GET http://localhost:8000/api/agents \ -H "Content-Type: application/json" ``` -------------------------------- ### Environment Configuration (.env file) Source: https://context7.com/kritsanan1/facebook-gemini-agents/llms.txt This section details the environment variables required for setting up API authentication and application settings. It includes configurations for Facebook, Google Gemini, and general application parameters, as well as optional database and security settings. ```env # Facebook API Configuration FACEBOOK_APP_ID=your_app_id_here FACEBOOK_APP_SECRET=your_app_secret_here FACEBOOK_ACCESS_TOKEN=your_long_lived_access_token FACEBOOK_PAGE_ID=your_facebook_page_id FACEBOOK_WEBHOOK_VERIFY_TOKEN=random_secure_token_here # Google Gemini API GOOGLE_API_KEY=your_gemini_api_key_here # Application Settings DEBUG=false LOG_LEVEL=INFO PORT=8000 # Optional: Database and Caching DATABASE_URL=sqlite:///./facebook_agents.db REDIS_URL=redis://localhost:6379/0 # Security SECRET_KEY=your_secret_key_minimum_32_characters JWT_SECRET=your_jwt_secret_for_authentication ``` -------------------------------- ### Run Pytest for Agent Testing Source: https://github.com/kritsanan1/facebook-gemini-agents/blob/main/SETUP_GUIDE.md Commands for executing the test suite using pytest. Includes options to run all tests, specific files, and to generate a test coverage report. ```bash # Run all tests pytest # Run specific test file pytest tests/test_agents.py -v # Run with coverage pytest --cov=src tests/ ``` -------------------------------- ### Environment Configuration Source: https://context7.com/kritsanan1/facebook-gemini-agents/llms.txt Details on setting up environment variables for API authentication and application settings, including Facebook, Google Gemini, and other application configurations. ```APIDOC ## Environment Configuration ### Description Set up environment variables for API authentication and application settings. ### Setup Steps 1. Copy the example environment file: ```bash cp .env.example .env ``` 2. Edit the `.env` file with your specific credentials and settings. ### Environment Variables #### Facebook API Configuration - **FACEBOOK_APP_ID**: Your Facebook App ID. - **FACEBOOK_APP_SECRET**: Your Facebook App Secret. - **FACEBOOK_ACCESS_TOKEN**: Your long-lived Facebook access token. - **FACEBOOK_PAGE_ID**: The ID of your Facebook page. - **FACEBOOK_WEBHOOK_VERIFY_TOKEN**: A secure token for webhook verification. #### Google Gemini API - **GOOGLE_API_KEY**: Your Google Gemini API key. #### Application Settings - **DEBUG**: Set to `true` for debugging mode, `false` otherwise. - **LOG_LEVEL**: The logging level (e.g., 'INFO', 'DEBUG', 'ERROR'). - **PORT**: The port the application will run on. #### Optional: Database and Caching - **DATABASE_URL**: Connection URL for the database (e.g., `sqlite:///./facebook_agents.db`). - **REDIS_URL**: Connection URL for Redis (e.g., `redis://localhost:6379/0`). #### Security - **SECRET_KEY**: A secret key for application security (minimum 32 characters). - **JWT_SECRET**: A secret key for JWT authentication. ### Example `.env` File ```env FACEBOOK_APP_ID=your_app_id_here FACEBOOK_APP_SECRET=your_app_secret_here FACEBOOK_ACCESS_TOKEN=your_long_lived_access_token FACEBOOK_PAGE_ID=your_facebook_page_id FACEBOOK_WEBHOOK_VERIFY_TOKEN=random_secure_token_here GOOGLE_API_KEY=your_gemini_api_key_here DEBUG=false LOG_LEVEL=INFO PORT=8000 DATABASE_URL=sqlite:///./facebook_agents.db REDIS_URL=redis://localhost:6379/0 SECRET_KEY=your_secret_key_minimum_32_characters JWT_SECRET=your_jwt_secret_for_authentication ``` ``` -------------------------------- ### Set API Keys in .env File Source: https://github.com/kritsanan1/facebook-gemini-agents/blob/main/SETUP_GUIDE.md Demonstrates the required format for setting Facebook and Google Gemini API keys within the `.env` file. This is crucial for the application's authentication. ```env # Facebook API FACEBOOK_APP_ID=your_app_id FACEBOOK_APP_SECRET=your_app_secret FACEBOOK_ACCESS_TOKEN=your_access_token FACEBOOK_PAGE_ID=your_page_id # Google Gemini GOOGLE_API_KEY=your_gemini_api_key ``` -------------------------------- ### Analyze Facebook Page Performance via CLI Source: https://context7.com/kritsanan1/facebook-gemini-agents/llms.txt This script allows for comprehensive page performance analysis directly from the command line. It requires a page ID, date range, and an output file path. The output includes key performance metrics. ```bash # Analyze page performance via CLI python main.py analyze-performance \ --page-id 123456789 \ --date-range last_30d \ --output analytics_report.json # Output: # 📊 Analyzing page performance... # # ✅ Performance Analysis Complete: # Page ID: 123456789 # Date Range: last_30d # Total Reach: 45,230 # Total Engagement: 3,421 # Engagement Rate: 7.56% # # 💾 Full report saved to: analytics_report.json ``` -------------------------------- ### Facebook API Client: Get Page Insights Source: https://context7.com/kritsanan1/facebook-gemini-agents/llms.txt Retrieves detailed analytics and insights for Facebook pages. Supports fetching general page insights by specifying 'page_id' and 'metrics', as well as post-specific insights using 'post_id'. ```python from src.tools.facebook_tools import facebook_client # Get page insights insights = facebook_client.get_page_insights( page_id="123456789", metrics="page_impressions,page_engaged_users,page_fan_adds" ) for metric in insights.get('data', []): print(f"{metric['name']}: {metric['values']}") # Get post-specific insights post_insights = facebook_client.get_post_insights(post_id="123456789_987654321") print(f"Post Impressions: {post_insights['data'][0]['values']}") ``` -------------------------------- ### Validate Environment Configuration via CLI Source: https://context7.com/kritsanan1/facebook-gemini-agents/llms.txt This command-line utility verifies that all necessary environment variables and API credentials are correctly configured for the application. It provides feedback on the validity of the configuration. ```bash # Validate environment configuration python main.py validate-config # Output (success): # 🔍 Validating configuration... # ✅ Configuration is valid! # Output (error): # 🔍 Validating configuration... # ❌ Configuration error: Missing GOOGLE_API_KEY # Please check your .env file and ensure all required settings are configured. ``` -------------------------------- ### CLI Interface - Validate Configuration Source: https://context7.com/kritsanan1/facebook-gemini-agents/llms.txt Verify that all required environment variables and API credentials are correctly configured for the application. ```APIDOC ## CLI Interface - Validate Configuration ### Description Verify that all required environment variables and API credentials are properly configured. ### Method CLI Command ### Command ```bash python main.py validate-config ``` ### Parameters None ### Request Example ```bash python main.py validate-config ``` ### Response #### Success Response A confirmation message indicating that the configuration is valid. #### Error Response An error message detailing the missing configuration (e.g., 'Missing GOOGLE_API_KEY'). #### Response Example (Success) ``` Configuration is valid! ``` #### Response Example (Error) ``` Configuration error: Missing GOOGLE_API_KEY Please check your .env file and ensure all required settings are configured. ``` ``` -------------------------------- ### CLI Interface - Analyze Performance Source: https://context7.com/kritsanan1/facebook-gemini-agents/llms.txt Analyze page performance from the command line. This tool requires a page ID and a date range, and can output the results to a JSON file. ```APIDOC ## CLI Interface - Analyze Performance ### Description Run comprehensive page performance analysis from the command line. ### Method CLI Command ### Command ```bash python main.py analyze-performance --page-id --date-range [--output ] ``` ### Parameters #### Command Line Arguments - **--page-id** (string) - Required - The ID of the Facebook page to analyze. - **--date-range** (string) - Required - The date range for the analysis (e.g., 'last_30d', 'yesterday'). - **--output** (string) - Optional - The filename to save the analytics report (e.g., 'analytics_report.json'). ### Request Example ```bash python main.py analyze-performance --page-id 123456789 --date-range last_30d --output analytics_report.json ``` ### Response #### Success Response - **Page ID** (string) - The ID of the analyzed page. - **Date Range** (string) - The date range used for the analysis. - **Total Reach** (integer) - Total reach of the page. - **Total Engagement** (integer) - Total engagement on the page. - **Engagement Rate** (string) - The engagement rate of the page. #### Response Example ```json { "Page ID": "123456789", "Date Range": "last_30d", "Total Reach": 45230, "Total Engagement": 3421, "Engagement Rate": "7.56%" } ``` ``` -------------------------------- ### Customer Service Agent: Quick Reply Buttons (Python) Source: https://context7.com/kritsanan1/facebook-gemini-agents/llms.txt Generates contextual quick reply buttons for common customer actions and handles their selection. The `create_quick_replies` function generates button suggestions based on context, while `handle_quick_reply` processes the user's selection. These are part of the customer service agent. ```python from src.agents.customer_service_agent import customer_service_agent # Create quick replies for sales context quick_replies = customer_service_agent.create_quick_replies(context="sales") for reply in quick_replies: print(f"{reply['title']}: {reply['payload']}") # Output: # View Products: VIEW_PRODUCTS # Get Quote: GET_QUOTE # Schedule Call: SCHEDULE_CALL # Handle quick reply click response = customer_service_agent.handle_quick_reply( payload="TRACK_ORDER", sender_info={'name': 'John'} ) print(response) # "Hi John, Please provide your order number..." ``` -------------------------------- ### Customer Service Agent: Generate Lead Qualification Questions Source: https://context7.com/kritsanan1/facebook-gemini-agents/llms.txt Generates targeted questions to qualify leads based on business type. It takes a 'service_type' (e.g., 'b2b') as input and returns a list of questions. No external dependencies beyond the agent itself are explicitly mentioned. ```python from src.agents.customer_service_agent import customer_service_agent # Generate B2B lead qualification questions questions = customer_service_agent.generate_lead_qualification_questions( service_type="b2b" ) for i, question in enumerate(questions, 1): print(f"{i}. {question}") # Output: # 1. What type of business are you in? # 2. What's your current monthly revenue? # 3. What tools are you currently using? # 4. What's your biggest challenge right now? ``` -------------------------------- ### Generate Content via CLI Source: https://context7.com/kritsanan1/facebook-gemini-agents/llms.txt This command-line interface command allows users to generate content by specifying the topic, tone, length, and an output file path. The script processes these arguments and saves the generated content to the specified JSON file. ```bash python main.py content-generate \ --topic "eco-friendly home tips" \ --tone professional \ --length long \ --output generated_content.json ``` -------------------------------- ### Configure AI Agent Settings (Python) Source: https://github.com/kritsanan1/facebook-gemini-agents/blob/main/SETUP_GUIDE.md Defines the configuration parameters for different AI agents, including the model to use, temperature for creativity, and maximum tokens for response length. This configuration is crucial for customizing agent behavior. ```python AGENT_CONFIGS = { 'content_agent': { 'model': 'gemini-pro', 'temperature': 0.7, 'max_tokens': 1000, }, 'customer_service_agent': { 'model': 'gemini-pro', 'temperature': 0.3, 'max_tokens': 500, }, 'analytics_agent': { 'model': 'gemini-pro', 'temperature': 0.1, 'max_tokens': 2000, } } ``` -------------------------------- ### Contribution Workflow (Git) Source: https://github.com/kritsanan1/facebook-gemini-agents/blob/main/SETUP_GUIDE.md Standard Git commands for contributing to the project. This involves forking the repository, creating a new branch for features, committing changes, and pushing the branch for a pull request. ```bash git checkout -b feature/amazing-feature git commit -m 'Add amazing feature' git push origin feature/amazing-feature ``` -------------------------------- ### Access Web Interface Source: https://github.com/kritsanan1/facebook-gemini-agents/blob/main/SETUP_GUIDE.md Instructs users on how to access the web dashboard for agent management by navigating to a local URL in their web browser. ```text Open your browser to: `http://localhost:8000/web/` ``` -------------------------------- ### CLI Interface - Post to Facebook Source: https://context7.com/kritsanan1/facebook-gemini-agents/llms.txt Publish content to Facebook directly from the command line. This tool allows you to specify a message, page ID, and save the result to a file. ```APIDOC ## CLI Interface - Post to Facebook ### Description Publish content to Facebook directly from the command line. ### Method CLI Command ### Command ```bash python main.py post-facebook --message "" --page-id [--output ] ``` ### Parameters #### Command Line Arguments - **--message** (string) - Required - The content of the post. - **--page-id** (string) - Required - The ID of the Facebook page to post to. - **--output** (string) - Optional - The filename to save the post result (e.g., 'post_result.json'). ### Request Example ```bash python main.py post-facebook --message "Join us for our webinar on digital marketing trends!" --page-id 123456789 --output post_result.json ``` ### Response #### Success Response - **Post ID** (string) - The ID of the created post. - **Page ID** (string) - The ID of the page where the post was published. #### Response Example ```json { "Post ID": "123456789_987654321", "Page ID": "123456789" } ``` ``` -------------------------------- ### Post Content to Facebook via CLI Source: https://context7.com/kritsanan1/facebook-gemini-agents/llms.txt Enables publishing content to a Facebook page directly from the command line. It requires a message, page ID, and an output file for the posting result. The output confirms successful posting and provides a post ID. ```bash # Post to Facebook via CLI python main.py post-facebook \ --message "Join us for our webinar on digital marketing trends!" \ --page-id 123456789 \ --output post_result.json # Output: # 📱 Posting to Facebook... # # ✅ Posted successfully! # Post ID: 123456789_987654321 # Page ID: 123456789 # # 💾 Response saved to: post_result.json ``` -------------------------------- ### List Connected Facebook Pages via CLI Source: https://context7.com/kritsanan1/facebook-gemini-agents/llms.txt Retrieves a list of all connected Facebook pages along with their details from the command line. The output is saved to a specified JSON file and lists page names, IDs, and categories. ```bash # List all Facebook pages via CLI python main.py list-pages \ --output pages_list.json # Output: # 📋 Fetching Facebook pages... # # ✅ Found 3 pages: # 1. My Business Page (ID: 123456789) # Category: Business # # 2. Community Page (ID: 987654321) # Category: Community # # 3. Brand Page (ID: 555666777) # Category: Brand # # 💾 Pages data saved to: pages_list.json ``` -------------------------------- ### Basic HTML Structure for Dashboard (HTML) Source: https://github.com/kritsanan1/facebook-gemini-agents/blob/main/SETUP_GUIDE.md A basic HTML file structure for the web dashboard. This serves as the entry point for the user interface, likely to be styled with CSS and interacted with via JavaScript. ```html Facebook Gemini Agents Dashboard

Facebook Gemini Agents Dashboard

``` -------------------------------- ### Handle Customer Messages via CLI Source: https://context7.com/kritsanan1/facebook-gemini-agents/llms.txt This CLI command processes customer service messages by taking the message text, sender name, and an output file path as arguments. It performs intent classification and generates a response, saving the analysis and response to a JSON file. ```bash python main.py handle-message \ --message "I'm having trouble logging into my account" \ --sender-name "Jessica" \ --output response.json ``` -------------------------------- ### CLI Interface - List Facebook Pages Source: https://context7.com/kritsanan1/facebook-gemini-agents/llms.txt Retrieve a list of all connected Facebook pages with their details. The output can be saved to a JSON file. ```APIDOC ## CLI Interface - List Facebook Pages ### Description Retrieve all connected Facebook pages with their details. ### Method CLI Command ### Command ```bash python main.py list-pages [--output ] ``` ### Parameters #### Command Line Arguments - **--output** (string) - Optional - The filename to save the list of pages (e.g., 'pages_list.json'). ### Request Example ```bash python main.py list-pages --output pages_list.json ``` ### Response #### Success Response - **Pages** (array) - A list of Facebook pages. - **ID** (string) - The ID of the page. - **Name** (string) - The name of the page. - **Category** (string) - The category of the page. #### Response Example ```json { "pages": [ { "ID": "123456789", "Name": "My Business Page", "Category": "Business" }, { "ID": "987654321", "Name": "Community Page", "Category": "Community" }, { "ID": "555666777", "Name": "Brand Page", "Category": "Brand" } ] } ``` ``` -------------------------------- ### Facebook API Client: Create Post Source: https://context7.com/kritsanan1/facebook-gemini-agents/llms.txt Enables publishing content directly to Facebook pages. Supports creating simple text posts and posts with photos. Requires the 'facebook_client' and specifies 'message', 'page_id', and optionally 'image_path'. ```python from src.tools.facebook_tools import facebook_client # Create a simple text post result = facebook_client.create_post( message="Exciting news! Our new product launches next week 🚀", page_id="123456789" # Optional, uses default if not specified ) print(f"Post ID: {result['id']}") print(f"Success: {result.get('success', True)}") # Create post with photo photo_result = facebook_client.create_photo_post( message="Check out our new office space!", image_path="/path/to/image.jpg", page_id="123456789" ) print(f"Photo Post ID: {photo_result['id']}") ``` -------------------------------- ### Initialize Dashboard and Load Agent Status (JavaScript) Source: https://github.com/kritsanan1/facebook-gemini-agents/blob/main/src/web/index.html Sets up the dashboard upon DOMContentLoaded, including loading agent status and activity logs. It uses `axios` to fetch agent data from the `/api/agents` endpoint and updates the UI accordingly. Error handling is included for the API request. ```javascript const API_BASE_URL = window.location.origin + '/api'; document.addEventListener('DOMContentLoaded', function() { loadAgentStatus(); loadActivityLog(); setupEventListeners(); }); async function loadAgentStatus() { try { const response = await axios.get(`${API_BASE_URL}/agents`); const agents = response.data.agents; // Update UI based on agent status Object.keys(agents).forEach(agentKey => { const agent = agents[agentKey]; // Update UI logic here }); } catch (error) { console.error('Failed to load agent status:', error); } } ``` -------------------------------- ### POST /api/agents/content/generate Source: https://context7.com/kritsanan1/facebook-gemini-agents/llms.txt Generates content based on specified topic, tone, length, and target audience. ```APIDOC ## POST /api/agents/content/generate ### Description Generates content based on specified topic, tone, length, and target audience. ### Method POST ### Endpoint /api/agents/content/generate ### Parameters #### Request Body - **topic** (string) - Required - The subject of the content to be generated. - **tone** (string) - Required - The desired tone of the content (e.g., "enthusiastic", "professional"). - **length** (string) - Required - The desired length of the content (e.g., "short", "medium", "long"). - **target_audience** (string) - Optional - The intended audience for the content. ### Request Example ```json { "topic": "healthy breakfast recipes", "tone": "enthusiastic", "length": "medium", "target_audience": "health-conscious millennials" } ``` ### Response #### Success Response (200) - **content** (string) - The generated content. - **hashtags** (array of strings) - Relevant hashtags for the generated content. - **topic** (string) - The input topic. - **tone** (string) - The input tone. - **length** (string) - The input length. - **confidence_score** (number) - The confidence score of the generated content. #### Response Example ```json { "content": "Rise and shine! 🌅 Start your day right with these amazing...", "hashtags": ["#HealthyBreakfast", "#MorningRoutine", "#HealthyEating"], "topic": "healthy breakfast recipes", "tone": "enthusiastic", "length": "medium", "confidence_score": 0.85 } ``` ``` -------------------------------- ### POST /api/agents/service/respond Source: https://context7.com/kritsanan1/facebook-gemini-agents/llms.txt Handles customer messages by classifying intent and generating a response. ```APIDOC ## POST /api/agents/service/respond ### Description Handles customer messages by classifying intent and generating a response. This endpoint is useful for customer service automation. ### Method POST ### Endpoint /api/agents/service/respond ### Parameters #### Request Body - **message** (string) - Required - The customer's message. - **sender_info** (object) - Optional - Information about the sender. - **name** (string) - Required - The sender's name. - **id** (string) - Required - The sender's unique identifier. - **context** (object) - Optional - Contextual information for the conversation. - **conversation_history** (array) - Optional - Previous messages in the conversation. ### Request Example ```json { "message": "Do you offer international shipping?", "sender_info": { "name": "Michael", "id": "67890" }, "context": { "conversation_history": [] } } ``` ### Response #### Success Response (200) - **response** (string) - The generated response to the customer. - **intent** (string) - The classified intent of the customer's message. - **confidence** (string) - The confidence level of the intent classification (e.g., "high", "medium", "low"). - **needs_escalation** (boolean) - Indicates if the conversation needs to be escalated to a human agent. - **quick_replies** (array of objects) - Suggested quick replies for the user. - **title** (string) - The text displayed for the quick reply. - **payload** (string) - The data associated with the quick reply. #### Response Example ```json { "response": "Hi Michael! Yes, we do offer international shipping...", "intent": "GENERAL_QUESTION", "confidence": "high", "needs_escalation": false, "quick_replies": [ {"title": "View Shipping Rates", "payload": "SHIPPING_RATES"}, {"title": "Track Order", "payload": "TRACK_ORDER"} ] } ``` ``` -------------------------------- ### Content Agent API Endpoints Source: https://github.com/kritsanan1/facebook-gemini-agents/blob/main/SETUP_GUIDE.md Endpoints for generating, optimizing, and scheduling content using the Content Creation Agent. ```APIDOC ## POST /api/agents/content/generate ### Description Generates new content for Facebook posts. ### Method POST ### Endpoint /api/agents/content/generate ### Parameters #### Request Body - **topic** (string) - Required - The main topic for the content. - **tone** (string) - Optional - The desired tone of the content (e.g., 'friendly', 'professional'). - **length** (string) - Optional - The desired length of the content (e.g., 'short', 'medium', 'long'). ### Request Example { "topic": "summer vacation ideas", "tone": "friendly", "length": "medium" } ### Response #### Success Response (200) - **content** (string) - The generated post content. - **hashtags** (array) - A list of relevant hashtags. #### Response Example { "content": "Planning your summer vacation? Explore these amazing destinations and make unforgettable memories!", "hashtags": ["#SummerVacation", "#Travel", "#VacationIdeas"] } ## POST /api/agents/content/optimize ### Description Optimizes existing content for better engagement. ### Method POST ### Endpoint /api/agents/content/optimize ### Parameters #### Request Body - **content** (string) - Required - The content to be optimized. ### Response #### Success Response (200) - **optimized_content** (string) - The optimized version of the content. ## POST /api/agents/content/calendar ### Description Generates a content calendar based on specified criteria. ### Method POST ### Endpoint /api/agents/content/calendar ### Parameters #### Request Body - **start_date** (string) - Required - The start date for the calendar (YYYY-MM-DD). - **end_date** (string) - Required - The end date for the calendar (YYYY-MM-DD). - **topics** (array) - Optional - A list of topics to include in the calendar. ### Response #### Success Response (200) - **calendar** (object) - A structured content calendar. ``` -------------------------------- ### Python: Analyze Facebook Page Performance Source: https://github.com/kritsanan1/facebook-gemini-agents/blob/main/SETUP_GUIDE.md Python code snippet for using the `analytics_agent` to retrieve and print performance insights for a Facebook page over a specified date range. Requires the `analytics_agent` to be imported. ```python from src.agents.analytics_agent import analytics_agent # Analyze page performance insights = analytics_agent.analyze_page_performance( page_id="your_page_id", date_range="last_30d" ) print(insights['insights_summary']) ``` -------------------------------- ### POST /api/agents/analytics/insights Source: https://context7.com/kritsanan1/facebook-gemini-agents/llms.txt Retrieves page performance analytics and AI-generated recommendations. ```APIDOC ## POST /api/agents/analytics/insights ### Description Retrieves page performance analytics and AI-generated recommendations to help improve content strategy. ### Method POST ### Endpoint /api/agents/analytics/insights ### Parameters #### Request Body - **page_id** (string) - Required - The unique identifier of the page. - **date_range** (string) - Required - The time period for which to retrieve analytics (e.g., "last_7d", "last_30d", "last_90d"). - **metrics** (array of strings) - Optional - Specific metrics to retrieve (e.g., ["reach", "engagement", "impressions"]). If not provided, default metrics will be returned. ### Request Example ```json { "page_id": "123456789", "date_range": "last_30d", "metrics": ["reach", "engagement", "impressions"] } ``` ### Response #### Success Response (200) - **page_id** (string) - The ID of the analyzed page. - **date_range** (string) - The specified date range for the analytics. - **insights** (object) - Key performance indicators for the page. - **total_reach** (integer) - Total number of unique users who saw the content. - **total_engagement** (integer) - Total number of interactions (likes, comments, shares, clicks). - **engagement_rate** (number) - The percentage of reached users who engaged with the content. - **recommendations** (array of strings) - Actionable AI-generated recommendations for improving performance. - **performance_score** (number) - An overall performance score for the page. #### Response Example ```json { "page_id": "123456789", "date_range": "last_30d", "insights": { "total_reach": 45230, "total_engagement": 3421, "engagement_rate": 7.56 }, "recommendations": [ "Increase posting frequency on Tuesdays and Wednesdays", "Focus more on video content which shows 3x engagement" ], "performance_score": 75.6 } ``` ``` -------------------------------- ### Content Creation Agent: Generate Content Calendar (Python) Source: https://context7.com/kritsanan1/facebook-gemini-agents/llms.txt Creates a monthly content calendar with diverse post types and strategic scheduling. This function requires the month, year, and themes to generate a calendar of post plans, each including theme, type, suggested day, and content. It is part of the content creation agent. ```python from src.agents.content_agent import content_agent # Generate monthly content calendar calendar = content_agent.generate_content_calendar( month=7, # July year=2024, themes=["product launches", "customer stories", "industry tips"] ) for post_plan in calendar: print(f"Theme: {post_plan['theme']}") print(f"Type: {post_plan['post_type']}") # educational, promotional, engaging, behind_the_scenes print(f"Best Day: {post_plan['suggested_day']}") print(f"Content: {post_plan['post']['content']}") print("---") # Generates 12 posts (4 types × 3 themes) with optimal scheduling ``` -------------------------------- ### Facebook Webhook Verification Endpoint (Python/FastAPI) Source: https://context7.com/kritsanan1/facebook-gemini-agents/llms.txt This Python code sets up a FastAPI endpoint to handle Facebook webhook verification. It checks the `hub_mode`, `hub_challenge`, and `hub_verify_token` to confirm the webhook subscription. ```python from fastapi import FastAPI, Request from src.tools.facebook_tools import facebook_client from src.agents.customer_service_agent import customer_service_agent app = FastAPI() # Webhook verification endpoint @app.get("/api/webhook/facebook") async def verify_webhook(hub_mode: str, hub_challenge: str, hub_verify_token: str): if hub_mode == "subscribe" and hub_verify_token == "YOUR_VERIFY_TOKEN": return int(hub_challenge) return {"error": "Verification failed"} ``` -------------------------------- ### Generate Content via REST API Source: https://context7.com/kritsanan1/facebook-gemini-agents/llms.txt This API endpoint allows for the generation of content based on specified parameters like topic, tone, length, and target audience. It returns the generated content, relevant hashtags, and other metadata. The request body is a JSON object. ```bash curl -X POST http://localhost:8000/api/agents/content/generate \ -H "Content-Type: application/json" \ -d '{ "topic": "healthy breakfast recipes", "tone": "enthusiastic", "length": "medium", "target_audience": "health-conscious millennials" }' ```