Back to Blog
Developer Tutorial

Give Your AI Agent Social Media Hands with ViralGhost Agent API

Your AI agent can browse the web, send emails, and query databases. But can it post to Instagram? Learn how to add social media as a tool in your agent's toolkit with a single REST API.

February 26, 202610 min read

Give Your AI Agent Social Media Hands with ViralGhost Agent API

AI agents are getting remarkably capable. They browse the web, send emails, write code, query databases, and manage files. But ask most agents to post to Instagram or schedule a LinkedIn update and they hit a wall.

The reason is simple: social media platform APIs are a nightmare. Each platform has its own authentication flow, its own content format, its own rate limits, and its own set of gotchas. Implementing OAuth for four separate services, handling image uploads differently for each one, and managing token refresh cycles is nobody's idea of a good time.

The ViralGhost Agent API solves this by giving your agent a single, unified tool for social media. One API key. One endpoint pattern. Post to Instagram, Facebook, X, and LinkedIn with the same request shape. Generate AI-powered captions. Schedule posts for optimal times. Check analytics. All through a clean REST API designed specifically for agent integration.

In this tutorial, we'll walk through adding social media capabilities to an AI agent step by step.

What the Agent API Does

Before we write any code, let's understand what you're getting:

  • Post to 4 platforms — Instagram, Facebook Pages, X (Twitter), and LinkedIn — with a single API call

  • AI content generation — Generate platform-optimized captions from a brief or topic

  • Scheduling — Schedule posts for specific dates/times or publish immediately

  • Analytics — Check how posts performed after publishing

  • Dry run mode — Validate posts without actually publishing (great for agent testing)
  • The typical agent flow looks like this:

    1. Brief — Your agent receives a request like "post about our product launch to Instagram and LinkedIn"
    2. Generate — Optionally call the AI generation endpoint to draft a caption
    3. Schedule — Send the post to the scheduling endpoint with target platforms and timing

    Let's build this.

    Prerequisites

  • A ViralGhost account ([free at viralghost.xyz](https://viralghost.xyz) — no credit card required)

  • An API key from Settings → API in your dashboard

  • At least one social account linked (Instagram, Facebook, X, or LinkedIn)

  • Node.js 18+ installed
  • Step 1: Get Your API Key

    Sign up at [viralghost.xyz](https://viralghost.xyz) and link your social accounts. Then navigate to Settings → API → Create API Key. You'll get a key that looks like vg_live_your_api_key.

    Also note your account IDs from the Accounts page. Each linked social account gets an ID like acc_instagram_123.

    Step 2: Define the Tool Schema

    If you're building an agent with OpenAI function calling, here's the tool definition:

    javascript
    const socialMediaTool = {
    type: "function",
    function: {
    name: "schedule_social_post",
    description: "Schedule a social media post to Instagram, Facebook, X, or LinkedIn via ViralGhost. Use this when the user wants to publish or schedule social media content.",
    parameters: {
    type: "object",
    properties: {
    text: {
    type: "string",
    description: "The post text/caption"
    },
    platforms: {
    type: "array",
    items: { type: "string", enum: ["instagram", "facebook", "x", "linkedin"] },
    description: "Which platforms to post to"
    },
    image_url: {
    type: "string",
    description: "Optional URL of an image to include"
    },
    schedule_at: {
    type: "string",
    description: "Optional ISO 8601 datetime to schedule the post. Omit to publish immediately."
    }
    },
    required: ["text", "platforms"]
    }
    }
    };

    This schema tells the LLM exactly what parameters are available and when to use the tool.

    Step 3: Implement the Tool Handler

    Here's the function that actually calls the ViralGhost API:

    javascript
    const VIRALGHOST_API_KEY = "vg_live_your_api_key";
    const BASE_URL = "https://api.viralghost.xyz/v1";

    const ACCOUNT_MAP = {
    instagram: "acc_instagram_123",
    facebook: "acc_facebook_456",
    x: "acc_x_789",
    linkedin: "acc_linkedin_012"
    };

    async function scheduleSocialPost({ text, platforms, image_url, schedule_at }) {
    const accounts = platforms
    .filter(p => p in ACCOUNT_MAP)
    .map(p => ACCOUNT_MAP[p]);

    const payload = {
    accounts,
    content: { text }
    };

    if (image_url) payload.content.image_url = image_url;
    if (schedule_at) payload.schedule_at = schedule_at;

    const resp await fetch(${BASE_URL}/posts, {
    method: "POST",
    headers: {
    "Authorization": Bearer ${VIRALGHOST_API_KEY},
    "Content-Type": "application/json"
    },
    body: JSON.stringify(payload)
    });

    return response.json();
    }

    That's the core of it. A single fetch call that posts to as many platforms as you want.

    Step 4: Wire It Into Your Agent Loop

    Here's a complete agent that can handle social media requests:

    javascript
    import OpenAI from "openai";

    const openai = new OpenAI();

    const messages = [
    {
    role: "system",
    content: "You are a helpful assistant that can post to social media. When the user asks you to post something, use the schedule_social_post tool. Always confirm the content and platforms before posting."
    },
    {
    role: "user",
    content: "Post 'Just shipped our v2 launch! 🚀' to Instagram and X, scheduled for tomorrow at 9am PST"
    }
    ];

    const resp await openai.chat.completions.create({
    model: "gpt-4",
    messages,
    tools: [socialMediaTool]
    });

    // Handle the tool call
    const toolCall = response.choices[0].message.tool_calls[0];
    const args = JSON.parse(toolCall.function.arguments);
    const result = await scheduleSocialPost(args);

    console.log("Post scheduled:", result);
    // { post_id: "pst_abc123", status: "scheduled", scheduled_at: "2026-02-28T17:00:00Z" }

    Step 5: Add AI Content Generation

    Sometimes you don't want to write the caption yourself. Let ViralGhost's AI generate it:

    javascript
    async function generateCaption(topic, { t "professional", platform = "instagram" } = {}) {
    const resp await fetch(${BASE_URL}/ai/generate, {
    method: "POST",
    headers: {
    "Authorization": Bearer ${VIRALGHOST_API_KEY},
    "Content-Type": "application/json"
    },
    body: JSON.stringify({
    type: "caption",
    prompt: topic,
    tone,
    platform
    })
    });

    const data = await response.json();
    return data.content;
    }

    // Usage
    const caption = await generateCaption(
    "We just hit 10,000 users on our SaaS platform",
    { tone: "excited", platform: "linkedin" }
    );
    console.log(caption);
    // "We just crossed 10,000 users. 🎉 What started as a weekend project..."

    Now you can chain the two: generate a caption, then schedule the post. The full brief → generate → schedule flow in one agent turn.

    Step 6: The Complete Brief → Generate → Schedule Flow

    Here's everything wired together:

    javascript
    async function briefToPost(brief, platforms, scheduleAt) {
    // 1. Generate content
    const caption = await generateCaption(brief, {
    tone: "casual",
    platform: platforms[0]
    });

    console.log("Generated caption:", caption);

    // 2. Schedule the post
    const result = await scheduleSocialPost({
    text: caption,
    platforms,
    schedule_at: scheduleAt
    });

    console.log("Scheduled:", result);
    return result;
    }

    // One function call: brief in, scheduled post out
    await briefToPost(
    "Announce our new API launch with excitement",
    ["instagram", "x", "linkedin"],
    "2026-03-01T09:00:00-08:00"
    );

    Error Handling and Dry Runs

    For production agents, always validate before publishing:

    javascript
    // Dry run — validates without publishing
    const validation = await fetch(${BASE_URL}/posts, {
    method: "POST",
    headers: {
    "Authorization": Bearer ${VIRALGHOST_API_KEY},
    "Content-Type": "application/json"
    },
    body: JSON.stringify({
    accounts: [ACCOUNT_MAP.instagram],
    content: { text: "Test post" },
    dry_run: true
    })
    });

    const result = await validation.json();
    // { valid: true, estimated_reach: 1200, warnings: [] }

    This is especially useful for agents that run autonomously — you can validate in a dry run, present the result to the user, and only publish after confirmation.

    Pricing: What You Get for Free

    The [free tier](/docs/agent-api) gives you everything you need to build and test:

  • 2 social accounts — enough for Instagram + one more

  • 30 posts/month — about one per day

  • 15 AI generations — for testing the content generation flow
  • No credit card required. The API is the same across all plans — the limits are on volume, not functionality. When you need more, Pro ($49/mo) gives you 10 accounts and 500 posts/month.

    What's Next

    You've just given your AI agent the ability to post to social media. From here you can:

  • Add analytics checking to monitor post performance

  • Build approval flows where the agent drafts and a human confirms

  • Create automated content calendars that run weekly

  • Integrate with your CRM to post when deals close or users sign up
  • Ready to get started? [Sign up for free at viralghost.xyz](https://viralghost.xyz) and grab your API key. Full documentation is at [/docs/agent-api](/docs/agent-api).


    Start free at [viralghost.xyz](https://viralghost.xyz) — 2 accounts, 30 posts/month, 15 AI generations. No credit card. Upgrade when you need more room.

    Topics covered:

    AI agent social media APILLM social media automationagent API for postingViralGhost Agent APIAI agent toolssocial media automation API

    Share this article:

    Deploy Your AI Social Agent

    Stop spending hours on social media. Train your AI agent on your voice and maintain consistent presence in just 30 minutes daily.

    Start Free Trial