Skip to main content

Feature-rich Python SDK for Meta AI - Chat, Image & Video Generation powered by Llama 3

Project description

๐Ÿค– Meta AI Python SDK

Python Version License PyPI GitHub

Unleash the Power of Meta AI with Python ๐Ÿš€

A modern, feature-rich Python SDK providing seamless access to Meta AI's cutting-edge capabilities: Chat with Llama 3, Generate Images, Create AI Videos - All Without API Keys!

๐ŸŽฏ Quick Start โ€ข ๐Ÿ“– Documentation โ€ข ๐Ÿ’ก Examples โ€ข ๐ŸŽฌ Video Generation


โœจ Why Choose This SDK?

๐ŸŽฏ Zero Configuration

No API keys needed! Just install and start coding

โšก Lightning Fast

Optimized for performance Real-time responses

๐Ÿ”ฅ Feature Complete

Chat โ€ข Images โ€ข Videos All in one SDK

๐ŸŒŸ Core Capabilities

โœ… Current Status Notice:
Chat, Image, and Video functionality are now working with cookie-based authentication plus the Meta AI OAuth token used by the SDK and API server.
Image & Video Generation remain fully functional using simple cookie-based authentication (only 2 required cookies).
See CHANGELOG.md for release history and implementation updates.

Feature Description Status
๐Ÿ’ฌ Intelligent Chat Powered by Llama 3 with internet access โœ… Working
๐Ÿ“ค Image Upload Upload images for generation/analysis โœ… Working
๐ŸŽจ Image Generation Create stunning AI-generated images โœ… Working
๐ŸŽฌ Video Generation Generate videos from text or uploaded images โœ… Working
๐Ÿ” Image Analysis Describe, analyze, and extract info from images โœ… Working
๐ŸŒ Real-time Data Get current information via Bing integration โœ… Working
๐Ÿ“š Source Citations Responses include verifiable sources โœ… Working
๐Ÿ”„ Streaming Support Real-time response streaming โœ… Working
๐Ÿ” Cookie Authentication Uses session cookies (no problematic tokens) โœ… Working
๐ŸŒ Proxy Support Route requests through proxies โœ… Working

๐Ÿ“ฆ Installation

SDK Only (Lightweight)

For using Meta AI as a Python library:

pip install metaai-sdk

SDK + API Server

For deploying as a REST API service:

pip install metaai-sdk[api]

From Source

git clone https://github.com/mir-ashiq/metaai-api.git
cd metaai-api
pip install -e .          # SDK only
pip install -e ".[api]"   # SDK + API server

System Requirements: Python 3.7+ โ€ข Internet Connection โ€ข That's it!


๐Ÿš€ Quick Start

Note: Chat functionality is available. Use the working Chat, Image Generation, and Video Generation features below.

Example 1: Generate Images (WORKING โœ…)

from metaai_api import MetaAI

# Initialize with cookie-based authentication
ai = MetaAI()

# Generate images
result = ai.generate_image_new(
    prompt="a beautiful sunset over mountains",
    orientation="LANDSCAPE"  # LANDSCAPE, VERTICAL, or SQUARE
)

if result["success"]:
    print(f"Generated {len(result['image_urls'])} images:")
    for url in result["image_urls"]:
        print(url)

Output:

Generated 4 images:
https://scontent-arn2-1.xx.fbcdn.net/o1/v/t0/f2/m421/AQN...
https://scontent-arn2-1.xx.fbcdn.net/o1/v/t0/f2/m421/AQM...
https://scontent-arn2-1.xx.fbcdn.net/o1/v/t0/f2/m421/AQO...
https://scontent-arn2-1.xx.fbcdn.net/o1/v/t0/f2/m421/AQM...

Example 2: Generate Videos (WORKING โœ…)

from metaai_api import MetaAI

ai = MetaAI()

# Generate video (auto-polls for URLs by default)
result = ai.generate_video_new("waves crashing on a beach at sunset")

if result["success"]:
    print(f"Generated {len(result['video_urls'])} videos:")
    for url in result["video_urls"]:
        print(url)

    # IDs for extension workflows
    print("Media IDs:", result.get("media_ids", []))

Output:

Generated 4 videos:
https://scontent.xx.fbcdn.net/o1/v/t6/f2/.../video1.mp4?...
https://scontent.xx.fbcdn.net/o1/v/t6/f2/.../video2.mp4?...
https://scontent.xx.fbcdn.net/o1/v/t6/f2/.../video3.mp4?...
https://scontent.xx.fbcdn.net/o1/v/t6/f2/.../video4.mp4?...

Media IDs: ['956278367576451', '956278364243118', '956278370909784', '956278374243117']

Quick Return (No Polling):

# For faster response (~17s), disable auto-polling
result = ai.generate_video_new(
    "waves crashing",
    auto_poll=False  # Returns immediately with conversation ID
)

if result["success"]:
    print(f"View your videos at: https://www.meta.ai/prompt/{result['conversation_id']}")

Example 3: Upload & Use Images (WORKING โœ…)

from metaai_api import MetaAI

ai = MetaAI()

# Complex calculation
question = "If I invest $10,000 at 7% annual interest compounded monthly for 5 years, how much will I have?"
response = ai.prompt(question)

print(response["message"])

Output:

With an initial investment of $10,000 at a 7% annual interest rate compounded monthly
over 5 years, you would have approximately $14,176.25.

Here's the breakdown:
- Principal: $10,000
- Interest Rate: 7% per year (0.583% per month)
- Time: 5 years (60 months)
- Compound Frequency: Monthly
- Total Interest Earned: $4,176.25
- Final Amount: $14,176.25

This calculation uses the compound interest formula: A = P(1 + r/n)^(nt)

๐Ÿ” Authentication Options

The SDK uses simple cookie-based authentication. Minimum required:

from metaai_api import MetaAI

# Minimum cookies required
cookies = {
    "datr": "your_datr_value",
    "ecto_1_sess": "your_ecto_1_sess_value"  # Most important for generation
}

ai = MetaAI(cookies=cookies)

Optional cookies (improves compatibility in some regions):

# More complete cookie set (recommended)
cookies = {
    "datr": "your_datr_value",
    "abra_sess": "your_abra_sess_value",  # Optional - some regions (e.g., Indonesia) may not have this
    "ecto_1_sess": "your_ecto_1_sess_value"  # Most important for generation
}

ai = MetaAI(cookies=cookies)

Alternative: Load from environment variables

import os
from metaai_api import MetaAI

# Cookies from .env file
ai = MetaAI()  # Automatically loads from META_AI_* environment variables

๐Ÿ’ก Note: Token fetching (lsd/fb_dtsg) has been removed. Generation APIs work perfectly with just datr + ecto_1_sess cookies!


๐Ÿ’ฌ Chat Features

Streaming Responses

Watch responses appear in real-time, like ChatGPT:

from metaai_api import MetaAI

ai = MetaAI()

print("๐Ÿค– AI: ", end="", flush=True)
for chunk in ai.prompt("Explain quantum computing in simple terms", stream=True):
    print(chunk["message"], end="", flush=True)
print("\n")

Output:

๐Ÿค– AI: Quantum computing is like having a super-powered calculator that can solve
problems in completely new ways. Instead of regular computer bits that are either
0 or 1, quantum computers use "qubits" that can be both 0 and 1 at the same time -
imagine flipping a coin that's both heads and tails until you look at it! This
special ability allows quantum computers to process massive amounts of information
simultaneously, making them incredibly fast for specific tasks like drug discovery,
cryptography, and complex simulations.

Conversation Context

Have natural back-and-forth conversations:

from metaai_api import MetaAI

ai = MetaAI()

# First question
response1 = ai.prompt("What are the three primary colors?")
print("Q1:", response1["message"][:100])

# Follow-up question (maintains context)
response2 = ai.prompt("How do you mix them to make purple?")
print("Q2:", response2["message"][:150])

# Start fresh conversation
response3 = ai.prompt("What's the capital of France?", new_conversation=True)
print("Q3:", response3["message"][:50])

Output:

Q1: The three primary colors are Red, Blue, and Yellow. These colors cannot be created by mixing...

Q2: To make purple, you mix Red and Blue together. The exact shade of purple depends on the ratio - more red creates a reddish-purple (like magenta)...

Q3: The capital of France is Paris, located in the...

Using Proxies

Route your requests through a proxy:

from metaai_api import MetaAI

# Configure proxy
proxy = {
    'http': 'http://your-proxy-server:8080',
    'https': 'https://your-proxy-server:8080'
}

ai = MetaAI(proxy=proxy)
response = ai.prompt("Hello from behind a proxy!")
print(response["message"])

๐ŸŒ REST API Server (Optional)

Deploy Meta AI as a REST API service! Chat, image, and video endpoints are fully functional.

Note: Chat now uses the OAuth token extracted from Meta AI and the same SDK flow is exposed through the API server.

Installation

pip install metaai-sdk[api]

Setup

  1. Get your Meta AI cookies (see Cookie Setup section)
  2. Create .env file:
META_AI_DATR=your_datr_cookie
META_AI_ECTO_1_SESS=your_ecto_1_sess_cookie

# Optional (recommended when available)
META_AI_ABRA_SESS=your_abra_sess_cookie
  1. Start the server:
uvicorn metaai_api.api_server:app --host 0.0.0.0 --port 8000

Server starts instantly (no token pre-fetching delays).

API Endpoints

Endpoint Method Description Status
/healthz GET Health check โœ… Working
/upload POST Upload images for generation โœ… Working
/image POST Generate images from text โœ… Working
/video POST Generate video (blocks until complete) โœ… Working
/video/extend POST Extend video from media ID โœ… Working
/video/async POST Start async video generation โœ… Working
/video/jobs/{job_id} GET Poll async job status โœ… Working
/chat POST Send chat messages โœ… Working

Example Usage (Working Endpoints)

import requests

BASE_URL = "http://localhost:8000"

# Health check
response = requests.get(f"{BASE_URL}/healthz")
print(response.json())  # {"status": "ok"}

# Image generation
images = requests.post(f"{BASE_URL}/image", json={
    "prompt": "Cyberpunk cityscape at night",
    "orientation": "LANDSCAPE"  # LANDSCAPE, VERTICAL, or SQUARE
}, timeout=200)
result = images.json()
if result["success"]:
    for url in result["image_urls"]:
        print(url)

# Video generation (synchronous)
video = requests.post(f"{BASE_URL}/video", json={
    "prompt": "waves crashing on beach"
}, timeout=400)
result = video.json()
if result["success"]:
    print("Video URLs:", result.get("video_urls", []))
    print("Media IDs:", result.get("media_ids", []))

# Extend video from media ID
extended = requests.post(f"{BASE_URL}/video/extend", json={
    "media_id": result["media_ids"][0]
}, timeout=400)
extend_result = extended.json()
if extend_result["success"]:
    print("Extended URLs:", extend_result.get("video_urls", []))
    print("Extended Media IDs:", extend_result.get("media_ids", []))

# Async video generation
job = requests.post(f"{BASE_URL}/video/async", json={
    "prompt": "sunset over ocean"
})
job_id = job.json()["job_id"]

# Poll for result
import time
while True:
    status = requests.get(f"{BASE_URL}/video/jobs/{job_id}")
    data = status.json()
    if data["status"] == "completed":
        print("Video URLs:", data["result"]["video_urls"])
        break
    time.sleep(5)

Performance

  • Image Generation: ~2 minutes (returns 4 images)
  • Video Generation: ~40-60 seconds (returns 3-4 videos)
  • Upload: < 5 seconds

Test All Features

Run test scripts in this order for fastest troubleshooting and full coverage:

  1. Chat flow (SDK + optional API):
python scripts/test_chat_feature.py --test-api --base-url http://127.0.0.1:8001 --output tests/integration/outputs/chat_feature_test_results.json
  1. Image upload + image generation + animation from uploaded image:
python scripts/test_upload_and_generation.py --base-url http://127.0.0.1:8001
  1. Full SDK + API validation (chat, upload, image, video, async, extend):
python scripts/test_all_features_complete.py --base-url http://127.0.0.1:8001 --output tests/integration/outputs/feature_test_report_sdk_api_final.json

Add --video-auto-poll if you want the runner to wait for final media URLs during video checks.

Extend Animation + Image Upload Workflow (SDK)

from metaai_api import MetaAI

ai = MetaAI()

# 1) Upload an image
upload = ai.upload_image("path/to/image.jpg")
if not upload.get("success"):
    raise RuntimeError("Upload failed")

media_id = upload["media_id"]
metadata = {
    "file_size": upload.get("file_size", 0),
    "mime_type": upload.get("mime_type", "image/jpeg"),
}

# 2) Animate the uploaded image into video
video = ai.generate_video_new(
    prompt="animate this image with smooth cinematic motion",
    media_ids=[media_id],
    attachment_metadata=metadata,
)

# 3) Extend one generated animation clip
if video.get("success") and video.get("media_ids"):
    extended = ai.extend_video(video["media_ids"][0])
    print("Extended video URLs:", extended.get("video_urls", []))

๐ŸŽฌ Video Generation

Create AI-generated videos from text descriptions!

Setup: Get Your Cookies

  1. Visit meta.ai in your browser and login

  2. Open DevTools (F12) โ†’ Application tab โ†’ Cookies โ†’ https://meta.ai

  3. Copy these required cookie values:

    • datr
    • ecto_1_sess (most important for generation)

    Optional (if available):

    • abra_sess

๐Ÿ’ก Note: Only datr and ecto_1_sess cookies are needed. No tokens (lsd/fb_dtsg) required!

๐Ÿ”„ Automatic Cookie Refresh

Cookies (especially ecto_1_sess) expire periodically. The SDK now includes automatic cookie refresh scripts!

Option 1: Manual Export (Recommended)

# 1. In your browser: Copy as cURL โ†’ save as curl.json
# 2. Run the extractor
python refresh_cookies.py

When to Refresh?

The SDK automatically detects expired cookies and will show:

โŒ Cookie Expired: ecto_1_sess needs to be refreshed
Run: python auto_refresh_cookies.py

Key Cookies:

  • ecto_1_sess โญ - Session token (expires frequently, must refresh)
  • rd_challenge - Challenge cookie (auto-updated by SDK)
  • ps_l, ps_n - Portal flags (optional, may improve reliability)

Example 1: Generate Your First Video

from metaai_api import MetaAI

# Your browser cookies (minimum required)
cookies = {
    "datr": "your_datr_value_here",
    "ecto_1_sess": "your_ecto_1_sess_value_here"
}

# Optional cookie (recommended when available)
# cookies["abra_sess"] = "your_abra_sess_value_here"

# Initialize with cookies
ai = MetaAI(cookies=cookies)

# Generate a video
result = ai.generate_video_new("A majestic lion walking through the African savanna at sunset")

if result["status"] == "READY":
    print("โœ… Video generated successfully!")
    print(f"๐ŸŽฌ Generated {len(result['video_urls'])} videos")
    for i, url in enumerate(result['video_urls'], 1):
        print(f"   Video {i}: {url[:80]}...")
    print(f"๐Ÿ“ Prompt: {result['prompt']}")
elif result["status"] == "PROCESSING":
    print("โณ Video request accepted and still processing")
    print("Media IDs:", result.get("media_ids", []))
else:
    print("โŒ Video generation failed")
    print(result.get("error"))
    print(result.get("graphql_errors", []))

Output:

โœ… Sending video generation request...
โœ… Video generation request sent successfully!
โณ Waiting before polling...
๐Ÿ”„ Polling for video URLs (Attempt 1/20)...
โœ… Video URLs found!

โœ… Video generated successfully!
๐ŸŽฌ Generated 3 videos
   Video 1: https://scontent.xx.fbcdn.net/v/t66.36240-6/video1.mp4?...
   Video 2: https://scontent.xx.fbcdn.net/v/t66.36240-6/video2.mp4?...
   Video 3: https://scontent.xx.fbcdn.net/v/t66.36240-6/video3.mp4?...
๐Ÿ“ Prompt: A majestic lion walking through the African savanna at sunset

How to Get Your Cookies

  1. Open https://meta.ai in your browser and login
  2. Press F12 โ†’ Application tab
  3. Navigate to Cookies โ†’ https://meta.ai
  4. Copy these required values:
    • datr
    • ecto_1_sess
    • optional: abra_sess
  5. Add to your Python code or .env file

Example 2: Generate Multiple Videos

from metaai_api import MetaAI
import time

ai = MetaAI(cookies=cookies)

prompts = [
    "A futuristic city with flying cars at night",
    "Ocean waves crashing on a tropical beach",
    "Northern lights dancing over a snowy mountain"
]

videos = []
for i, prompt in enumerate(prompts, 1):
    print(f"\n๐ŸŽฌ Generating video {i}/{len(prompts)}: {prompt}")
    result = ai.generate_video(prompt, verbose=False)

    if result["success"]:
        videos.append(result["video_urls"][0])
        print(f"โœ… Success! URL: {result['video_urls'][0][:50]}...")
    else:
        print("โณ Still processing...")

    time.sleep(5)  # Be nice to the API

print(f"\n๐ŸŽ‰ Generated {len(videos)} videos successfully!")

Output:

๐ŸŽฌ Generating video 1/3: A futuristic city with flying cars at night
โœ… Success! URL: https://scontent.xx.fbcdn.net/v/t66.36240-6/1234...

๐ŸŽฌ Generating video 2/3: Ocean waves crashing on a tropical beach
โœ… Success! URL: https://scontent.xx.fbcdn.net/v/t66.36240-6/5678...

๐ŸŽฌ Generating video 3/3: Northern lights dancing over a snowy mountain
โœ… Success! URL: https://scontent.xx.fbcdn.net/v/t66.36240-6/9012...

๐ŸŽ‰ Generated 3 videos successfully!

Example 3: Advanced Video Generation with Orientation

from metaai_api import MetaAI

ai = MetaAI(cookies=cookies)

# Generate video with specific orientation (default is VERTICAL)
result = ai.generate_video(
    prompt="A time-lapse of a flower blooming",
    orientation="VERTICAL",   # Options: "LANDSCAPE", "VERTICAL", "SQUARE"
    wait_before_poll=15,      # Wait 15 seconds before checking
    max_attempts=50,          # Try up to 50 times
    wait_seconds=3,           # Wait 3 seconds between attempts
    verbose=True              # Show detailed progress
)

# Generate landscape video for widescreen
result_landscape = ai.generate_video(
    prompt="Panoramic view of sunset over mountains",
    orientation="LANDSCAPE"   # Wide format (16:9)
)

if result["success"]:
    print(f"\n๐ŸŽฌ Your videos are ready!")
    print(f"๐Ÿ”— Generated {len(result['video_urls'])} videos:")
    for i, url in enumerate(result['video_urls'], 1):
        print(f"   Video {i}: {url}")
    print(f"โฑ๏ธ Generated at: {result['timestamp']}")

Supported Video Orientations:

  • "LANDSCAPE" - Wide/horizontal (16:9) - ideal for widescreen, cinematic content
  • "VERTICAL" - Tall/vertical (9:16) - ideal for mobile, stories, reels (default)
  • "SQUARE" - Equal dimensions (1:1) - ideal for social posts

๐Ÿ“– **Full Video Guide:** See [GENERATION_API.md](GENERATION_API.md) for complete documentation.

---

## ๐Ÿ“ค Image Upload & Analysis

Upload images to Meta AI for analysis, similar image generation, and video creation:

### Upload & Analyze Images

```python
from metaai_api import MetaAI

# Initialize with cookies (datr + ecto_1_sess required)
ai = MetaAI(cookies={
    "datr": "your_datr_cookie",
    "ecto_1_sess": "your_ecto_1_sess_cookie",
    # "abra_sess": "your_abra_sess_cookie"  # Optional
})

# Step 1: Upload an image
result = ai.upload_image("path/to/image.jpg")

if result["success"]:
    media_id = result["media_id"]
    metadata = {
        'file_size': result['file_size'],
        'mime_type': result['mime_type']
    }

    # Step 2: Analyze the image
    response = ai.prompt(
        message="What do you see in this image? Describe it in detail.",
        media_ids=[media_id],
        attachment_metadata=metadata
    )
    print(f"๐Ÿ” Analysis: {response['message']}")

    # Step 3: Generate similar images
    response = ai.prompt(
        message="Create a similar image in watercolor painting style",
        media_ids=[media_id],
        attachment_metadata=metadata,
        is_image_generation=True
    )
    print(f"๐ŸŽจ Generated {len(response['media'])} similar images")

    # Step 4: Generate video from image
    video = ai.generate_video(
        prompt="generate a video with zoom in effect on this image",
        media_ids=[media_id],
        attachment_metadata=metadata
    )
    if video["success"]:
        print(f"๐ŸŽฌ Video: {video['video_urls'][0]}")

Output:

๐Ÿ” Analysis: The image captures a serene lake scene set against a majestic mountain backdrop. In the foreground, there's a small, golden-yellow wooden boat with a bright yellow canopy floating on calm, glassโ€‘like water...

๐ŸŽจ Generated 4 similar images

๐ŸŽฌ Video: https://scontent.fsxr1-2.fna.fbcdn.net/o1/v/t6/f2/m421/video.mp4

๐Ÿ“– Full Image Upload Guide: See examples/image_upload_example.py for a practical upload workflow.


๐ŸŽจ Image Generation

Generate AI-powered images with customizable orientations (requires Facebook authentication):

from metaai_api import MetaAI

# Initialize with Facebook credentials
ai = MetaAI(fb_email="your_email@example.com", fb_password="your_password")

# Generate images with default orientation (VERTICAL)
response = ai.prompt("Generate an image of a cyberpunk cityscape at night with neon lights")

# Or specify orientation explicitly
response_landscape = ai.prompt(
    "Generate an image of a panoramic mountain landscape",
    orientation="LANDSCAPE"  # Options: "LANDSCAPE", "VERTICAL", "SQUARE"
)

response_vertical = ai.prompt(
    "Generate an image of a tall waterfall",
    orientation="VERTICAL"  # Tall/portrait format (default)
)

response_square = ai.prompt(
    "Generate an image of a centered mandala pattern",
    orientation="SQUARE"  # Square format (1:1)
)

# Display results (Meta AI generates 4 images by default)
print(f"๐ŸŽจ Generated {len(response['media'])} images:")
for i, image in enumerate(response['media'], 1):
    print(f"  Image {i}: {image['url']}")
    print(f"  Prompt: {image['prompt']}")

Supported Orientations:

  • "LANDSCAPE" - Wide/horizontal format (16:9) - ideal for panoramas, landscapes
  • "VERTICAL" - Tall/vertical format (9:16) - ideal for portraits, mobile content (default)
  • "SQUARE" - Equal dimensions (1:1) - ideal for social media, profile images

Output:

๐ŸŽจ Generated 4 images:
  Image 1: https://scontent.xx.fbcdn.net/o1/v/t0/f1/m247/img1.jpeg
  Prompt: a cyberpunk cityscape at night with neon lights

  Image 2: https://scontent.xx.fbcdn.net/o1/v/t0/f1/m247/img2.jpeg
  Prompt: a cyberpunk cityscape at night with neon lights

  Image 3: https://scontent.xx.fbcdn.net/o1/v/t0/f1/m247/img3.jpeg
  Prompt: a cyberpunk cityscape at night with neon lights

  Image 4: https://scontent.xx.fbcdn.net/o1/v/t0/f1/m247/img4.jpeg
  Prompt: a cyberpunk cityscape at night with neon lights

๐Ÿ’ก Examples

Explore working examples in the examples/ directory:

File Description Features
๐Ÿ“„ image_workflow_complete.py Complete image workflow Upload, analyze, generate images/video
๐Ÿ“„ simple_example.py Quick start guide Basic chat + video generation
๐Ÿ“„ video_generation.py Video generation Multiple examples, error handling
๐Ÿ“„ test_example.py Testing suite Validation and testing

Run an Example

# Clone the repository
git clone https://github.com/mir-ashiq/metaai-api.git
cd metaai-api

# Run simple example
python examples/simple_example.py

# Run video generation examples
python examples/video_generation.py

๐Ÿ“– Documentation

๐Ÿ“š Complete Guides

Document Description
๐Ÿ“˜ Quick Start SDK/API setup and first requests
๐Ÿ“˜ Generation API Image/video generation details
๐Ÿ“™ Changes & Cookies Cookie setup and known caveats
๐Ÿ“• Contributing Guide How to contribute to the project
๐Ÿ“” Changelog Version history and updates
๐Ÿ““ Security Policy Security best practices

๐Ÿ”ง API Reference

MetaAI Class

class MetaAI:
    def __init__(
        self,
        fb_email: Optional[str] = None,
        fb_password: Optional[str] = None,
        cookies: Optional[dict] = None,
        proxy: Optional[dict] = None
    )

Methods:

  • prompt(message, stream=False, new_conversation=False)

    • Send a chat message
    • Returns: dict with message, sources, and media
  • generate_video(prompt, wait_before_poll=10, max_attempts=30, wait_seconds=5, verbose=True)

    • Generate a video from text - Returns: dict with success, video_urls (actual media URLs), media_ids, conversation_id, prompt, timestamp
  • extend_video(media_id, source_media_url=None, conversation_id=None, wait_before_poll=10, max_attempts=30, wait_seconds=5, verbose=True)

    • Extend a previously generated video from a media ID
      • Returns: dict with success, video_urls (extended playable URLs), media_ids, conversation_id, source_media_id, timestamp

VideoGenerator Class

from metaai_api import VideoGenerator

# Direct video generation
generator = VideoGenerator(cookies_str="your_cookies_as_string")
result = generator.generate_video("your prompt here")

# One-liner generation
result = VideoGenerator.quick_generate(
    cookies_str="your_cookies",
    prompt="your prompt"
)

๐ŸŽฏ Use Cases

1. Research Assistant

ai = MetaAI()
research = ai.prompt("Summarize recent breakthroughs in fusion energy")
print(research["message"])
# Get cited sources
for source in research["sources"]:
    print(f"๐Ÿ“Œ {source['title']}: {source['link']}")

2. Content Creation

ai = MetaAI(cookies=cookies)

# Generate video content
promo_video = ai.generate_video("Product showcase with smooth camera movements")

# Generate images
thumbnails = ai.prompt("Generate a YouTube thumbnail for a tech review video")

3. Educational Tool

ai = MetaAI()

# Explain complex topics
explanation = ai.prompt("Explain blockchain technology to a 10-year-old")

# Get homework help
solution = ai.prompt("Solve: 2x + 5 = 13, show steps")

4. Real-time Information

ai = MetaAI()

# Current events
news = ai.prompt("What are the top technology news today?")

# Sports scores
scores = ai.prompt("Latest Premier League scores")

# Market data
stocks = ai.prompt("Current S&P 500 index value")

๐Ÿ› ๏ธ Advanced Configuration

Environment Variables

Store credentials securely:

# .env file
META_AI_DATR=your_datr_value
META_AI_ECTO_1_SESS=your_ecto_1_sess_value

# Optional
META_AI_ABRA_SESS=your_abra_sess_value

# Optional persisted-query hotfix overrides
META_AI_DOC_ID_TEXT_TO_IMAGE=override_doc_id
META_AI_DOC_ID_TEXT_TO_VIDEO=override_doc_id
# ...or use META_AI_DOC_ID for both text-to-image and text-to-video

Load in Python:

from metaai_api import MetaAI

# Automatically loads from environment variables
ai = MetaAI()

# Or manually load with dotenv
import os
from dotenv import load_dotenv

load_dotenv()
cookies = {
    "datr": os.getenv("META_AI_DATR"),
    "ecto_1_sess": os.getenv("META_AI_ECTO_1_SESS")
}

if os.getenv("META_AI_ABRA_SESS"):
    cookies["abra_sess"] = os.getenv("META_AI_ABRA_SESS")

ai = MetaAI(cookies=cookies)

Error Handling

from metaai_api import MetaAI

ai = MetaAI(cookies=cookies)

try:
    result = ai.generate_video_new("Your prompt")

    if result["status"] == "READY":
        print(f"โœ… Video: {result['video_urls'][0]}")
    elif result["status"] == "PROCESSING":
        print("โณ Video still processing")
        print("Media IDs:", result.get("media_ids", []))
    else:
        print("โŒ Video generation failed")
        print(result.get("error"))
        print(result.get("graphql_errors", []))

except ValueError as e:
    print(f"โŒ Configuration error: {e}")
except ConnectionError as e:
    print(f"โŒ Network error: {e}")
except Exception as e:
    print(f"โŒ Unexpected error: {e}")

๐ŸŒŸ Project Structure

metaai-api/
โ”‚
โ”œโ”€โ”€ ๐Ÿ“ src/metaai_api/        # Core package
โ”‚   โ”œโ”€โ”€ __init__.py            # Package initialization
โ”‚   โ”œโ”€โ”€ main.py                # MetaAI class
โ”‚   โ”œโ”€โ”€ video_generation.py    # Video generation
โ”‚   โ”œโ”€โ”€ client.py              # Client utilities
โ”‚   โ”œโ”€โ”€ utils.py               # Helper functions
โ”‚   โ””โ”€โ”€ exceptions.py          # Custom exceptions
โ”‚
โ”œโ”€โ”€ ๐Ÿ“ examples/               # Usage examples
โ”‚   โ”œโ”€โ”€ simple_example.py      # Quick start
โ”‚   โ”œโ”€โ”€ video_generation.py    # Video examples
โ”‚   โ””โ”€โ”€ test_example.py        # Testing
โ”‚
โ”œโ”€โ”€ ๐Ÿ“ .github/                # GitHub configuration
โ”‚   โ”œโ”€โ”€ workflows/             # CI/CD pipelines
โ”‚   โ””โ”€โ”€ README.md
โ”‚
โ”œโ”€โ”€ ๐Ÿ“„ README.md               # This file
โ”œโ”€โ”€ ๐Ÿ“„ QUICK_START.md
โ”œโ”€โ”€ ๐Ÿ“„ GENERATION_API.md
โ”œโ”€โ”€ ๐Ÿ“„ CHANGES_AND_COOKIES.md
โ”œโ”€โ”€ ๐Ÿ“„ CONTRIBUTING.md
โ”œโ”€โ”€ ๐Ÿ“„ CHANGELOG.md
โ”œโ”€โ”€ ๐Ÿ“„ SECURITY.md
โ”œโ”€โ”€ ๐Ÿ“„ LICENSE                 # MIT License
โ”œโ”€โ”€ ๐Ÿ“„ pyproject.toml          # Project metadata
โ””โ”€โ”€ ๐Ÿ“„ requirements.txt        # Dependencies

๐Ÿค Contributing

We welcome contributions! Here's how you can help:

  1. ๐Ÿ› Report Bugs - Open an issue
  2. ๐Ÿ’ก Suggest Features - Share your ideas
  3. ๐Ÿ“ Improve Docs - Help us document better
  4. ๐Ÿ”ง Submit PRs - Fix bugs or add features

See CONTRIBUTING.md for detailed guidelines.


๐Ÿ“œ License

This project is licensed under the MIT License - see LICENSE for details.

โš–๏ธ Disclaimer

This project is an independent implementation and is not officially affiliated with Meta Platforms, Inc. or any of its affiliates.

  • โœ… Educational and development purposes
  • โœ… Use responsibly and ethically
  • โœ… Comply with Meta's Terms of Service
  • โœ… Respect usage limits and policies

Llama 3 License: Visit llama.com/llama3/license for Llama 3 usage terms.


๐Ÿ™ Acknowledgments

  • Meta AI - For providing the AI capabilities
  • Llama 3 - The powerful language model
  • Open Source Community - For inspiration and support

๐Ÿ“ž Support & Community


๐Ÿš€ Quick Links

Resource Link
๐Ÿ“ฆ PyPI Package pypi.org/project/metaai-sdk
๐Ÿ™ GitHub Repository github.com/mir-ashiq/metaai-api
๐Ÿ“– Full Documentation Quick Start โ€ข Generation API
๐Ÿ’ฌ Get Help Issues โ€ข Discussions

Meta AI Python SDK v2.0.0 | Made with โค๏ธ by mir-ashiq | MIT License

โญ Star this repo if you find it useful!

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

metaai_sdk-4.4.0.tar.gz (139.4 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

metaai_sdk-4.4.0-py3-none-any.whl (80.8 kB view details)

Uploaded Python 3

File details

Details for the file metaai_sdk-4.4.0.tar.gz.

File metadata

  • Download URL: metaai_sdk-4.4.0.tar.gz
  • Upload date:
  • Size: 139.4 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.12

File hashes

Hashes for metaai_sdk-4.4.0.tar.gz
Algorithm Hash digest
SHA256 ca334ef9393a1ceb6554bc4c508c2fc0bf1e42fb9035bc440e5ec4aa774654a3
MD5 ce160724e50cd80842fe05407a3aa8b6
BLAKE2b-256 71bcc8611f66e31239eeaed3cec94cd7cce8e202b784e2af058b11935e13aae6

See more details on using hashes here.

Provenance

The following attestation bundles were made for metaai_sdk-4.4.0.tar.gz:

Publisher: publish.yml on mir-ashiq/metaai-api

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file metaai_sdk-4.4.0-py3-none-any.whl.

File metadata

  • Download URL: metaai_sdk-4.4.0-py3-none-any.whl
  • Upload date:
  • Size: 80.8 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.12

File hashes

Hashes for metaai_sdk-4.4.0-py3-none-any.whl
Algorithm Hash digest
SHA256 bb937413d656d9fc2e6a988b722f2d6570084bdd9391925f07657609bdc8c179
MD5 502bae74f1b530e3fa32d8770ac53940
BLAKE2b-256 519fe71bd606361c9f46f1a65096f87922be92e0aef91b9d4660fa1bf5b1218b

See more details on using hashes here.

Provenance

The following attestation bundles were made for metaai_sdk-4.4.0-py3-none-any.whl:

Publisher: publish.yml on mir-ashiq/metaai-api

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page