一个非官方的 Meta AI Python SDK 与 FastAPI 封装,通过浏览器 Cookie 实现对 Llama 3 聊天、图像及视频生成功能的免费调用与服务化部署。
# 🤖 Meta AI Python SDK
[](https://www.python.org/downloads/)
[](LICENSE)
[](https://pypi.org/project/metaai-api/)
[](https://github.com/mir-ashiq/metaai-api)
**使用 Python 释放 Meta AI 的强大力量** 🚀
一个现代、功能丰富的 Python SDK,提供对 Meta AI 尖端功能的无缝访问:
与 Llama 3 聊天,生成图像,创建 AI 视频 —— 无需 API Key!
[🎯 快速开始](#-quick-start) • [📖 文档](#-documentation) • [💡 示例](#-examples) • [🎬 视频生成](#-video-generation)
## ✨ 为什么选择此 SDK?
|
### 🎯 **零配置**
无需 API Key!
安装即可开始编码
|
### ⚡ **极速**
性能优化
实时响应
|
### 🔥 **功能完备**
聊天 • 图像 • 视频
集成于一个 SDK
|
### 🌟 核心功能
| 功能 | 描述 | 状态 |
| ---------------------------- | ----------------------------------------------- | ---------- |
| 💬 **智能聊天** | 由 Llama 3 驱动,支持互联网访问 | ✅ 正常 |
| 📤 **图像上传** | 上传图像以进行生成/分析 | ✅ 正常 |
| 🎨 **图像生成** | 创建令人惊叹的 AI 生成图像 | ✅ 正常 |
| 🎬 **视频生成** | 从文本或上传的图像生成视频 | ✅ 正常 |
| 🔍 **图像分析** | 描述、分析并从图像中提取信息 | ✅ 正常 |
| 🌐 **实时数据** | 通过 Bing 集成获取当前信息 | ✅ 正常 |
| 📚 **来源引用** | 回复包含可验证的来源 | ✅ 正常 |
| 🔄 **流式支持** | 实时响应流 | ✅ 正常 |
| 🔐 **Cookie 认证** | 使用会话 Cookie(无问题令牌) | ✅ 正常 |
| 🌍 **代理支持** | 通过代理路由请求 | ✅ 正常 |
## 📦 安装
### 仅 SDK(轻量级)
将 Meta AI 用作 Python 库:
```
pip install metaai-sdk
```
### SDK + API 服务器
部署为 REST API 服务:
```
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 server
```
**系统要求:** Python 3.7+ • 互联网连接 • 仅此而已!
## 🚀 快速开始
### 示例 1:生成图像(正常工作 ✅)
```
from metaai_api import MetaAI
# 使用基于 cookie 的认证进行初始化
ai = MetaAI()
# 生成图像
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)
```
**输出:**
```
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...
```
### 示例 2:生成视频(正常工作 ✅)
```
from metaai_api import MetaAI
ai = MetaAI()
# 生成视频 (默认自动轮询 URL)
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", []))
```
**输出:**
```
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']
```
**快速返回(无轮询):**
```
# 如需更快响应 (~17秒),禁用自动轮询
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']}")
```
### 示例 3:上传并使用图像(正常工作 ✅)
```
from metaai_api import MetaAI
ai = MetaAI()
# 复杂计算
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"])
```
**输出:**
```
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)
```
## 🔐 认证选项
SDK 使用简单的 **基于 Cookie 的认证**,仅需 3 个必需的 Cookie:
```
from metaai_api import MetaAI
# 仅需 3 个 cookie
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)
```
**替代方案:从环境变量加载**
```
import os
from metaai_api import MetaAI
# 来自 .env 文件的 cookie
ai = MetaAI() # Automatically loads from META_AI_* environment variables
```
## 💬 聊天功能
### 流式响应
观看实时出现的回复,就像 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")
```
**输出:**
```
🤖 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.
```
### 对话上下文
进行自然流畅的来回对话:
```
from metaai_api import MetaAI
ai = MetaAI()
# 首个问题
response1 = ai.prompt("What are the three primary colors?")
print("Q1:", response1["message"][:100])
# 后续问题 (保持上下文)
response2 = ai.prompt("How do you mix them to make purple?")
print("Q2:", response2["message"][:150])
# 开始新对话
response3 = ai.prompt("What's the capital of France?", new_conversation=True)
print("Q3:", response3["message"][:50])
```
**输出:**
```
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...
```
### 使用代理
通过代理路由您的请求:
```
from metaai_api import MetaAI
# 配置代理
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 服务器(可选)
将 Meta AI 部署为 REST API 服务!**聊天、图像和视频端点功能齐全。**
### 安装
```
pip install metaai-sdk[api]
```
### 设置
1. **获取您的 Meta AI Cookie**(参见 [Cookie 设置](#-cookie-setup) 部分)
2. **创建 `.env` 文件:**
```
META_AI_DATR=your_datr_cookie
META_AI_ABRA_SESS=your_abra_sess_cookie
META_AI_ECTO_1_SESS=your_ecto_1_sess_cookie
```
3. **启动服务器:**
```
uvicorn metaai_api.api_server:app --host 0.0.0.0 --port 8000
```
服务器立即启动(无 Token 预取延迟)。
### API 端点
| 端点 | 方法 | 描述 | 状态 |
| ---------------------- | ------ | -------------------------------------- | ---------- |
| `/healthz` | GET | 健康检查 | ✅ 正常 |
| `/upload` | POST | 上传图像以进行生成 | ✅ 正常 |
| `/image` | POST | 从文本生成图像 | ✅ 正常 |
| `/video` | POST | 生成视频(阻塞直到完成) | ✅ 正常 |
| `/video/extend` | POST | 从媒体 ID 延伸视频 | ✅ 正常 |
| `/video/async` | POST | 启动异步视频生成 | ✅ 正常 |
| `/video/jobs/{job_id}` | GET | 轮询异步作业状态 | ✅ 正常 |
| `/chat` | POST | 发送聊天消息 | ✅ 正常 |
### 示例用法(正常工作的端点)
```
import requests
BASE_URL = "http://localhost:8000"
# 健康检查
response = requests.get(f"{BASE_URL}/healthz")
print(response.json()) # {"status": "ok"}
# 图像生成
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 = 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", []))
# 基于 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", []))
# 异步视频生成
job = requests.post(f"{BASE_URL}/video/async", json={
"prompt": "sunset over ocean"
})
job_id = job.json()["job_id"]
# 轮询结果
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)
```
### 性能
- **图像生成**:约 2 分钟(返回 4 张图像)
- **视频生成**:约 40-60 秒(返回 3-4 个视频)
- **上传**:< 5 秒
### 测试所有功能
运行全面的 SDK + API 测试运行器,以端到端验证聊天、上传、图像、视频、异步和延伸流程:
```
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
```
如果您希望运行器在视频检查期间等待最终的媒体 URL,请添加 `--video-auto-poll`。
## 🎬 视频生成
从文本描述创建 AI 生成的视频!
### 设置:获取您的 Cookie
1. 在浏览器中访问 [meta.ai](https://www.meta.ai) 并登录
2. 打开开发者工具 (F12) → **Application** 标签页 → **Cookies** → https://meta.ai
3. 复制这 3 个 Cookie 值:
- `datr`
- `abra_sess`
- `ecto_1_sess`(对于生成最重要)
### 🔄 自动刷新 Cookie
Cookie(尤其是 `ecto_1_sess`)会定期过期。SDK 现在包含 **自动 Cookie 刷新** 脚本!
#### 选项 1:手动导出(推荐)
```
# 1. 在浏览器中:复制为 cURL → 另存为 curl.json
# 2. 运行提取器
python refresh_cookies.py
```
#### 何时刷新?
SDK 会自动检测过期的 Cookie 并会显示:
```
❌ Cookie Expired: ecto_1_sess needs to be refreshed
Run: python auto_refresh_cookies.py
```
**关键 Cookie:**
- `ecto_1_sess` ⭐ - 会话 Token(经常过期,**必须刷新**)
- `rd_challenge` - 挑战 Cookie(由 SDK 自动更新)
- `ps_l`, `ps_n` - Portal 标志(生成所需)
### 示例 1:生成您的第一个视频
```
from metaai_api import MetaAI
# 您的浏览器 cookie (仅需 3 个!)
cookies = {
"datr": "your_datr_value_here",
"abra_sess": "your_abra_sess_value_here",
"ecto_1_sess": "your_ecto_1_sess_value_here"
}
# 使用 cookie 初始化
ai = MetaAI(cookies=cookies)
# 生成视频
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")
```
**输出:**
```
✅ 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
```
### 如何获取您的 Cookie
1. 在浏览器中打开 https://meta.ai 并登录
2. 按 **F12** → **Application** 标签页
3. 导航到 **Cookies** → `https://meta.ai`
4. 复制这 3 个值:
- `datr`
- `abra_sess`
- `ecto_1_sess`
5. 添加到您的 Python 代码或 `.env` 文件
6. 或者,右键点击 → **查看页面源代码** → 搜索 `"LSD",[],{"token":"` 和 `DTSGInitData",[],{"token":"`
### 示例 2:生成多个视频
```
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!")
```
**输出:**
```
🎬 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!
```
### 示例 3:带方向的高级视频生成
```
from metaai_api import MetaAI
ai = MetaAI(cookies=cookies)
# 生成特定方向的视频 (默认为 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
)
# 生成适用于宽屏的横屏视频
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']}")
```
**支持的视频方向:**
- `"LANDSCAPE"` - 宽屏/横向 (16:9) - 适合宽屏、电影内容
- `"VERTICAL"` - 高屏/竖向 (9:16) - 适合移动端、Stories、Reels(默认)
- `"SQUARE"` - 等边 (1:1) - 适合社交帖子
```
📖 **Full Video Guide:** See [GENERATION_API.md](GENERATION_API.md) for complete documentation.
---
## 📤 图像上传与分析
Upload images to Meta AI for analysis, similar image generation, and video creation:
### 上传与分析图像
```python
from metaai_api import MetaAI
# 使用 Facebook cookie 初始化 (图像操作必需)
ai = MetaAI(cookies={
"datr": "your_datr_cookie",
"abra_sess": "your_abra_sess_cookie"
})
# 步骤 1:上传图像
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]}")
```
**输出:**
```
🔍 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
```
📖 **完整图像上传指南:** 参见 [examples/image_upload_example.py](examples/image_upload_example.py) 了解实际上传工作流程。
## 🎨 图像生成
生成具有可自定义方向的 AI 驱动图像(需要 Facebook 认证):
```
from metaai_api import MetaAI
# 使用 Facebook 凭证初始化
ai = MetaAI(fb_email="your_email@example.com", fb_password="your_password")
# 使用默认方向 (VERTICAL) 生成图像
response = ai.prompt("Generate an image of a cyberpunk cityscape at night with neon lights")
# 或明确指定方向
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)
)
# 显示结果 (Meta AI 默认生成 4 张图像)
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']}")
```
**支持的方向:**
- `"LANDSCAPE"` - 宽屏/横向格式 (16:9) - 适合全景、风景
- `"VERTICAL"` - 高屏/竖向格式 (9:16) - 适合人像、移动内容(默认)
- `"SQUARE"` - 等边 (1:1) - 适合社交媒体、个人资料图片
**输出:**
```
🎨 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/` 目录中探索可运行的示例:
| 文件 | 描述 | 功能 |
| ------------------------------------------------------------------------ | ----------------------- | -------------------------------------- |
| 📄 **[image_workflow_complete.py](examples/image_workflow_complete.py)** | 完整图像工作流程 | 上传、分析、生成图像/视频 |
| 📄 **[simple_example.py](examples/simple_example.py)** | 快速入门指南 | 基础聊天 + 视频生成 |
| 📄 **[video_generation.py](examples/video_generation.py)** | 视频生成 | 多个示例,错误处理 |
| 📄 **[test_example.py](examples/test_example.py)** | 测试套件 | 验证和测试 |
### 运行示例
```
# 克隆仓库
git clone https://github.com/mir-ashiq/metaai-api.git
cd meta-ai-python
# 运行简单示例
python examples/simple_example.py
# 运行视频生成示例
python examples/video_generation.py
```
## 📖 文档
### 📚 完整指南
| 文档 | 描述 |
| -------------------------------------------------- | -------------------------------- |
| 📘 **[快速开始](QUICK_START.md)** | SDK/API 设置和首次请求 |
| 📘 **[生成 API](GENERATION_API.md)** | 图像/视频生成详情 |
| 📙 **[变更与 Cookie](CHANGES_AND_COOKIES.md)** | Cookie 设置和已知注意事项 |
| 📕 **[贡献指南](CONTRIBUTING.md)** | 如何为项目做出贡献 |
| 📔 **[更新日志](CHANGELOG.md)** | 版本历史和更新 |
| 📓 **[安全政策](SECURITY.md)** | 安全最佳实践 |
### 🔧 API 参考
#### MetaAI 类
```
class MetaAI:
def __init__(
self,
fb_email: Optional[str] = None,
fb_password: Optional[str] = None,
cookies: Optional[dict] = None,
proxy: Optional[dict] = None
)
```
**方法:**
- **`prompt(message, stream=False, new_conversation=False)`**
- 发送聊天消息
- 返回:包含 `message`、`sources` 和 `media` 的 `dict`
- **`generate_video(prompt, wait_before_poll=10, max_attempts=30, wait_seconds=5, verbose=True)`**
- 从文本生成视频 - 返回:包含 `success`、`video_urls`(实际媒体 URL)、`media_ids`、`conversation_id`、`prompt`、`timestamp` 的 `dict`
- **`extend_video(media_id, source_media_url=None, conversation_id=None, wait_before_poll=10, max_attempts=30, wait_seconds=5, verbose=True)`**
- 从媒体 ID 延伸之前生成的视频
- 返回:包含 `success`、`video_urls`(延伸后的可播放 URL)、`media_ids`、`conversation_id`、`source_media_id`、`timestamp` 的 `dict`
#### VideoGenerator 类
```
from metaai_api import VideoGenerator
# 直接视频生成
generator = VideoGenerator(cookies_str="your_cookies_as_string")
result = generator.generate_video("your prompt here")
# 单行生成
result = VideoGenerator.quick_generate(
cookies_str="your_cookies",
prompt="your prompt"
)
```
## 🎯 使用案例
### 1. **研究助手**
```
ai = MetaAI()
research = ai.prompt("Summarize recent breakthroughs in fusion energy")
print(research["message"])
# 获取引用来源
for source in research["sources"]:
print(f"📌 {source['title']}: {source['link']}")
```
### 2. **内容创作**
```
ai = MetaAI(cookies=cookies)
# 生成视频内容
promo_video = ai.generate_video("Product showcase with smooth camera movements")
# 生成图像
thumbnails = ai.prompt("Generate a YouTube thumbnail for a tech review video")
```
### 3. **教育工具**
```
ai = MetaAI()
# 解释复杂主题
explanation = ai.prompt("Explain blockchain technology to a 10-year-old")
# 获取作业帮助
solution = ai.prompt("Solve: 2x + 5 = 13, show steps")
```
### 4. **实时信息**
```
ai = MetaAI()
# 时事
news = ai.prompt("What are the top technology news today?")
# 体育比分
scores = ai.prompt("Latest Premier League scores")
# 市场数据
stocks = ai.prompt("Current S&P 500 index value")
```
## 🛠️ 高级配置
### 环境变量
安全存储凭据:
```
# .env 文件
META_AI_DATR=your_datr_value
META_AI_ABRA_SESS=your_abra_sess_value
META_AI_ECTO_1_SESS=your_ecto_1_sess_value
```
在 Python 中加载:
```
from metaai_api import MetaAI
# 自动从环境变量加载
ai = MetaAI()
# 或使用 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
├── 📄 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
```
## 🤝 贡献
我们欢迎各种贡献!以下是您可以提供帮助的方式:
1. **🐛 报告 Bug** - [提出 Issue](https://github.com/mir-ashiq/metaai-api/issues)
2. **💡 建议功能** - 分享您的想法
3. **📝 改进文档** - 帮助我们更好地记录
4. **🔧 提交 PR** - 修复 Bug 或添加功能
详见 [CONTRIBUTING.md](CONTRIBUTING.md)。
## 📜 许可证
本项目采用 **MIT 许可证** 授权 - 详情见 [LICENSE](LICENSE)。
### ⚖️ 免责声明
本项目是一个 **独立实现**,与 Meta Platforms, Inc. 或其任何关联公司 **没有官方关联**。
- ✅ 教育和开发目的
✅ 负责任且符合道德地使用
- ✅ 遵守 Meta 的服务条款
- ✅ 尊重使用限制和政策
**Llama 3 许可证:** 访问 [llama.com/llama3/license](https://www.llama.com/llama3/license/) 查看 Llama 3 使用条款。
## 🙏 致谢
- **Meta AI** - 提供 AI 功能
- **Llama 3** - 强大的语言模型
- **开源社区** - 提供灵感和支持
## 📞 支持与社区
- 💬 **有问题?** [GitHub Discussions](https://github.com/mir-ashiq/metaai-api/discussions)
- 🐛 **Bug 报告** [GitHub Issues](https://github.com/mir-ashiq/metaai-api/issues)
- 📧 **联系** imseldrith@gmail.com
- ⭐ **在 [GitHub](https://github.com/mir-ashiq/metaai-api) 上给我们点星**
## 🚀 快速链接
| 资源 | 链接 |
| ------------------------- | ----------------------------------------------------------------------------------------------------------------------------- |
| 📦 **PyPI 包** | [pypi.org/project/metaai_api](https://pypi.org/project/metaai_api/) |
| 🐙 **GitHub 仓库** | [github.com/mir-ashiq/meta-ai-python](https://github.com/mir-ashiq/metaai-api) |
| 📖 **完整文档** | [快速开始](QUICK_START.md) • [生成 API](GENERATION_API.md) |
| 💬 **获取帮助** | [Issues](https://github.com/mir-ashiq/metaai-api/issues) • [Discussions](https://github.com/mir-ashiq/metaai-api/discussions) |
**Meta AI Python SDK v2.0.0** | 由 [mir-ashiq](https://github.com/mir-ashiq) 用 ❤️ 制作 | MIT 许可证
**⭐ 如果您觉得有用,请给个星!**