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
|
No API keys needed! Just install and start coding |
Optimized for performance Real-time responses |
Chat β’ Images β’ Videos All in one SDK |
β οΈ Current Status Notice:
Chat functionality is currently unavailable due to authentication challenges.
Image & Video Generation are fully functional using simple cookie-based authentication (only 3 cookies needed).
See SPEED_TEST_REPORT.md for performance benchmarks.
| Feature | Description | Status |
|---|---|---|
| π¬ Intelligent Chat | Powered by Llama 3 with internet access | |
| π€ 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 | |
| π Real-time Data | Get current information via Bing integration | |
| π Source Citations | Responses include verifiable sources | |
| π Streaming Support | Real-time response streaming | |
| π Cookie Authentication | Uses session cookies (no problematic tokens) | β Working |
| π Proxy Support | Route requests through proxies | β Working |
For using Meta AI as a Python library:
pip install metaai-sdkFor deploying as a REST API service:
pip install metaai-sdk[api]git clone https://github.com/mir-ashiq/metaai-api.git
cd metaai-api
pip install -e . # SDK only
pip install -e ".[api]" # SDK + API serverSystem Requirements: Python 3.7+ β’ Internet Connection β’ That's it!
β οΈ Note: Chat functionality is currently unavailable. Use the working Image Generation and Video Generation features below.
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...
from metaai_api import MetaAI
ai = MetaAI()
# Generate video
result = ai.generate_video_new(
prompt="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)Output:
Generated 3 videos:
https://scontent-arn2-1.xx.fbcdn.net/o1/v/t6/f2/m477/AQO...
https://scontent-arn2-1.xx.fbcdn.net/o1/v/t6/f2/m259/AQN...
https://scontent-arn2-1.xx.fbcdn.net/o1/v/t6/f2/m260/AQP...
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)
The SDK uses simple cookie-based authentication with just 3 required cookies:
from metaai_api import MetaAI
# Only 3 cookies required
cookies = {
"datr": "your_datr_value",
"abra_sess": "your_abra_sess_value",
"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 these 3 cookies!
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.
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...
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"])Deploy Meta AI as a REST API service! Image and video generation endpoints are fully functional.
β οΈ Note: Chat endpoint is currently unavailable due to token authentication issues.
pip install metaai-sdk[api]- Get your Meta AI cookies (see Cookie Setup section)
- Create
.envfile:
META_AI_DATR=your_datr_cookie
META_AI_ABRA_SESS=your_abra_sess_cookie
META_AI_ECTO_1_SESS=your_ecto_1_sess_cookie- Start the server:
uvicorn metaai_api.api_server:app --host 0.0.0.0 --port 8000Server starts instantly (no token pre-fetching delays).
| 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/async |
POST | Start async video generation | β Working |
/video/jobs/{job_id} |
GET | Poll async job status | β Working |
/chat |
POST | Send chat messages |
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"]:
for url in result["video_urls"]:
print(url)
# 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)- Image Generation: ~2 minutes (returns 4 images)
- Video Generation: ~40-60 seconds (returns 3-4 videos)
- Upload: < 5 seconds
Create AI-generated videos from text descriptions!
- Visit meta.ai in your browser and login
- Open DevTools (F12) β Application tab β Cookies β https://meta.ai
- Copy these 3 cookie values:
datrabra_sessecto_1_sess(most important for generation)
π‘ Note: Only these 3 cookies are needed. No tokens (lsd/fb_dtsg) required!
Cookies (especially ecto_1_sess) expire periodically. The SDK now includes automatic cookie refresh scripts!
# 1. In your browser: Copy as cURL β save as curl.json
# 2. Run the extractor
python refresh_cookies.pyThe 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 (required for generation)
from metaai_api import MetaAI
# Your browser cookies (only 3 required!)
cookies = {
"datr": "your_datr_value_here",
"abra_sess": "your_abra_sess_value_here",
"ecto_1_sess": "your_ecto_1_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["success"]:
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']}")
else:
print("β³ Video generation failed, check your cookies")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
- Open https://meta.ai in your browser and login
- Press F12 β Application tab
- Navigate to Cookies β
https://meta.ai - Copy these 3 values:
datrabra_sessecto_1_sess
- Add to your Python code or
.envfile - Alternatively, right-click β View Page Source β Search for
"LSD",[],{"token":"andDTSGInitData",[],{"token":"
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!
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 [VIDEO_GENERATION_README.md](https://github.com/mir-ashiq/metaai-api/blob/main/VIDEO_GENERATION_README.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 Facebook cookies (required for image operations)
ai = MetaAI(cookies={
"datr": "your_datr_cookie",
"abra_sess": "your_abra_sess_cookie"
})
# 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 IMAGE_UPLOAD_README.md for complete documentation!
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
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 |
# Clone the repository
git clone https://github.com/mir-ashiq/metaai-api.git
cd meta-ai-python
# Run simple example
python examples/simple_example.py
# Run video generation examples
python examples/video_generation.py| Document | Description |
|---|---|
| π Image Upload Guide | Complete image upload documentation |
| π Video Generation Guide | Complete video generation documentation |
| π Quick Reference | Fast lookup for common tasks |
| π Quick Usage | Image upload quick reference |
| π Architecture Guide | Technical architecture details |
| π Contributing Guide | How to contribute to the project |
| π Changelog | Version history and updates |
| π Security Policy | Security best practices |
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:
dictwithmessage,sources, andmedia
-
generate_video(prompt, wait_before_poll=10, max_attempts=30, wait_seconds=5, verbose=True)- Generate a video from text
- Returns:
dictwithsuccess,video_urls,conversation_id,prompt,timestamp
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"
)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']}")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")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")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")Store credentials securely:
# .env file
META_AI_DATR=your_datr_value
META_AI_ABRA_SESS=your_abra_sess_value
META_AI_ECTO_1_SESS=your_ecto_1_sess_valueLoad 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"),
"abra_sess": os.getenv("META_AI_ABRA_SESS"),
"ecto_1_sess": os.getenv("META_AI_ECTO_1_SESS")
}
ai = MetaAI(cookies=cookies)from metaai_api import MetaAI
ai = MetaAI(cookies=cookies)
try:
result = ai.generate_video("Your prompt")
if result["success"]:
print(f"β
Video: {result['video_urls'][0]}")
else:
print("β³ Video still processing, try again later")
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}")meta-ai-python/
β
βββ π 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
βββ π VIDEO_GENERATION_README.md
βββ π QUICK_REFERENCE.md
βββ π ARCHITECTURE.md
βββ π CONTRIBUTING.md
βββ π CHANGELOG.md
βββ π SECURITY.md
βββ π LICENSE # MIT License
βββ π setup.py # Package setup
βββ π pyproject.toml # Project metadata
βββ π requirements.txt # Dependencies
We welcome contributions! Here's how you can help:
- π Report Bugs - Open an issue
- π‘ Suggest Features - Share your ideas
- π Improve Docs - Help us document better
- π§ Submit PRs - Fix bugs or add features
See CONTRIBUTING.md for detailed guidelines.
This project is licensed under the MIT License - see LICENSE for details.
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.
- Meta AI - For providing the AI capabilities
- Llama 3 - The powerful language model
- Open Source Community - For inspiration and support
- π¬ Questions? GitHub Discussions
- π Bug Reports GitHub Issues
- π§ Contact imseldrith@gmail.com
- β Star us on GitHub
| Resource | Link |
|---|---|
| π¦ PyPI Package | pypi.org/project/metaai_api |
| π GitHub Repository | github.com/mir-ashiq/meta-ai-python |
| π Full Documentation | Video Guide β’ Quick Ref |
| π¬ 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!