A curated collection of practical AI projects implementing OCR systems, RAG, AI agents, and other AI use cases.
Add Instagram Post Crew - CrewAI multi-agent pipeline with Kimi K3 via Baseten
Tiioluwanidd7a5a7decaf
diff --git a/ai_agents/instagram_post_crew/.env.example b/ai_agents/instagram_post_crew/.env.examplenew file mode 100644index 0000000..06ffa74--- /dev/null+++ b/ai_agents/instagram_post_crew/.env.example@@ -0,0 +1,2 @@+BASETEN_API_KEY=your-baseten-api-key-here+FIRECRAWL_API_KEY=your-firecrawl-api-key-herediff --git a/ai_agents/instagram_post_crew/README.md b/ai_agents/instagram_post_crew/README.mdnew file mode 100644index 0000000..2d0d3bd--- /dev/null+++ b/ai_agents/instagram_post_crew/README.md@@ -0,0 +1,102 @@+# Instagram Post Crew++A CrewAI multi-agent pipeline that takes a topic or product idea and produces a strategically reasoned Instagram content package. Four specialized agents work sequentially: a Trend Intelligence agent analyzes why specific formats and hooks are performing for the niche, a Copywriter agent generates three caption variants and reasons about which fits best, a Visual Strategist agent produces a trend-grounded image generation prompt, and a Posting Strategist agent recommends a publish time tied to niche audience behavior. Agent reasoning is fully visible in the UI.++++## Features++- Trend analysis that goes beyond what is trending to explain why it is trending+- Three caption variants (educational, emotional, provocative) with model-reasoned selection+- Image generation prompt grounded in color psychology and visual style trends+- Posting time recommendation with niche-specific reasoning+- Full agent reasoning chain visible in the Streamlit UI++## Tech Stack++- **LLM:** Kimi K3 via Baseten+- **Orchestration:** CrewAI+- **Search:** DuckDuckGo+- **Scraping:** Firecrawl+- **UI:** Streamlit++## Prerequisites++- Python 3.10++- Baseten API key from https://baseten.co+- Firecrawl API key from https://firecrawl.dev++## Setup++### 1. Clone the Repository++```bash+git clone https://github.com/Sumanth077/Hands-On-AI-Engineering.git+cd Hands-On-AI-Engineering/ai_agents/instagram_post_crew+```++### 2. Create Virtual Environment++```bash+python -m venv .venv+.venv\Scripts\activate+```++### 3. Install Dependencies++```bash+pip install -r requirements.txt+```++### 4. Configure Environment Variables++```bash+copy .env.example .env+```++Open `.env` and add your API keys.++### 5. Run the App++```bash+streamlit run app.py+```++## Usage++Enter a topic or product idea in the text input and click Run. The four agents work sequentially and display their full reasoning alongside the final output for each section.++Example inputs:++- Sustainable fashion for Gen Z+- Home workout equipment for busy professionals+- Nigerian street food catering business++## Environment Variables++| Variable | Description |+|---|---|+| `BASETEN_API_KEY` | Your Baseten API key |+| `FIRECRAWL_API_KEY` | Your Firecrawl API key |++## Project Structure++instagram_post_crew/+├── app.py+├── agents.py+├── tasks.py+├── crew.py+├── tools.py+├── requirements.txt+├── .env.example+├── README.md+└── assets/+ └── demo.gif+++## How It Works++1. **Trend Intelligence** searches and scrapes current Instagram content for the topic, analyzes why specific formats are performing, and produces a structured creative brief+2. **Copywriting** uses the brief to generate three caption variants across different angles, reasons about which fits the niche, and selects the strongest one with hashtags+3. **Visual Strategy** produces a detailed image generation prompt grounded in trending aesthetics and color psychology for the topic+4. **Posting Strategy** recommends a publish time with reasoning tied to the specific niche audience behaviordiff --git a/ai_agents/instagram_post_crew/agents.py b/ai_agents/instagram_post_crew/agents.pynew file mode 100644index 0000000..c14ebb2--- /dev/null+++ b/ai_agents/instagram_post_crew/agents.py@@ -0,0 +1,86 @@+import os+from dotenv import load_dotenv+from crewai import Agent, LLM++from tools import duckduckgo_search_tool, firecrawl_scrape_tool++load_dotenv()++llm = LLM(+ model="moonshotai/Kimi-K3",+ base_url="https://inference.baseten.co/v1",+ api_key=os.getenv("BASETEN_API_KEY"),+ max_tokens=500,+ custom_openai=True,+ extra_body={"reasoning_effort": "none"},+)++trend_intelligence_agent = Agent(+ role="Trend Intelligence Agent",+ goal=(+ "Do at most 2 searches, then immediately produce a short structured creative brief "+ "for Instagram on the given topic. Prefer finishing over more research."+ ),+ backstory=(+ "You are a social media trend analyst. You gather just enough signal to explain "+ "why formats, hooks, and visuals are working, then you stop searching and write "+ "a concise brief. You never run long research loops."+ ),+ tools=[duckduckgo_search_tool, firecrawl_scrape_tool],+ llm=llm,+ verbose=True,+ allow_delegation=False,+ max_iter=3,+ max_retry_limit=1+)++copywriter_agent = Agent(+ role="Copywriter Agent",+ goal=(+ "Write three short caption variants (educational, emotional, provocative), pick "+ "the best one for the niche, and include hashtags. Keep the whole answer concise."+ ),+ backstory=(+ "You are a direct response copywriter for short form Instagram captions. "+ "You write tight copy and choose one clear winner quickly."+ ),+ llm=llm,+ verbose=True,+ allow_delegation=False,+ max_iter=1,+ max_retry_limit=1+)++visual_strategist_agent = Agent(+ role="Visual Strategist Agent",+ goal=(+ "Write one short reasoning note plus one ready to use image generation prompt "+ "grounded in trending aesthetics for the topic."+ ),+ backstory=(+ "You are a visual creative director. You briefly justify color and style choices, "+ "then deliver one detailed image prompt."+ ),+ llm=llm,+ verbose=True,+ allow_delegation=False,+ max_iter=1,+ max_retry_limit=1+)++posting_strategist_agent = Agent(+ role="Posting Strategist Agent",+ goal=(+ "Recommend one best day and time to post for this specific niche, with brief "+ "audience-behavior reasoning."+ ),+ backstory=(+ "You are a social media scheduling strategist. You give niche-specific timing "+ "advice in a short, decisive answer."+ ),+ llm=llm,+ verbose=True,+ allow_delegation=False,+ max_iter=1,+ max_retry_limit=1+)diff --git a/ai_agents/instagram_post_crew/app.py b/ai_agents/instagram_post_crew/app.pynew file mode 100644index 0000000..9f084d2--- /dev/null+++ b/ai_agents/instagram_post_crew/app.py@@ -0,0 +1,93 @@+from dotenv import load_dotenv+import streamlit as st++from crew import run_instagram_post_crew++load_dotenv()+++def extract_final_section(raw_text: str, markers):+ if not raw_text:+ return raw_text++ lowered = raw_text.lower()+ for marker in markers:+ idx = lowered.find(marker)+ if idx != -1:+ candidate = raw_text[idx:].strip()+ if candidate:+ return candidate++ return raw_text.strip()+++def get_task_raw_output(task_output):+ if task_output is None:+ return ""+ if hasattr(task_output, "raw"):+ return task_output.raw or ""+ return str(task_output)+++st.set_page_config(page_title="Instagram Post Crew", page_icon="📸", layout="wide")++st.title("Instagram Post Crew")+st.caption("A CrewAI multi-agent pipeline that turns a topic into a full Instagram content package.")++topic = st.text_input("Enter your topic or product idea")++run_clicked = st.button("Run")++if run_clicked:+ if not topic.strip():+ st.warning("Please enter a topic or product idea before running the crew.")+ else:+ with st.spinner("Agents working..."):+ try:+ result, crew = run_instagram_post_crew(topic)+ except Exception as error:+ st.error(f"The crew run failed: {error}")+ result, crew = None, None++ if crew is not None:+ task_outputs = list(crew.tasks_output) if hasattr(crew, "tasks_output") else []++ if len(task_outputs) < 4:+ task_outputs = [task.output for task in crew.tasks]++ trend_output = get_task_raw_output(task_outputs[0]) if len(task_outputs) > 0 else ""+ caption_output = get_task_raw_output(task_outputs[1]) if len(task_outputs) > 1 else ""+ visual_output = get_task_raw_output(task_outputs[2]) if len(task_outputs) > 2 else ""+ posting_output = get_task_raw_output(task_outputs[3]) if len(task_outputs) > 3 else ""++ st.header("1. Trend Intelligence Brief")+ with st.expander("Show agent reasoning"):+ st.markdown(trend_output if trend_output else "No output produced.")+ st.success(trend_output if trend_output else "No output produced.")++ st.header("2. Caption (with hashtags)")+ with st.expander("Show agent reasoning"):+ st.markdown(caption_output if caption_output else "No output produced.")+ final_caption = extract_final_section(+ caption_output,+ ["final caption", "selected caption", "final selected caption"]+ )+ st.success(final_caption if final_caption else "No output produced.")++ st.header("3. Image Generation Prompt")+ with st.expander("Show agent reasoning"):+ st.markdown(visual_output if visual_output else "No output produced.")+ final_prompt = extract_final_section(+ visual_output,+ ["final image generation prompt", "final prompt", "image generation prompt:"]+ )+ st.success(final_prompt if final_prompt else "No output produced.")++ st.header("4. Posting Strategy")+ with st.expander("Show agent reasoning"):+ st.markdown(posting_output if posting_output else "No output produced.")+ final_posting = extract_final_section(+ posting_output,+ ["final recommendation", "recommendation:"]+ )+ st.success(final_posting if final_posting else "No output produced.")diff --git a/ai_agents/instagram_post_crew/assets/demo.gif b/ai_agents/instagram_post_crew/assets/demo.gifnew file mode 100644index 0000000..71db37aBinary files /dev/null and b/ai_agents/instagram_post_crew/assets/demo.gif differdiff --git a/ai_agents/instagram_post_crew/crew.py b/ai_agents/instagram_post_crew/crew.pynew file mode 100644index 0000000..6de8599--- /dev/null+++ b/ai_agents/instagram_post_crew/crew.py@@ -0,0 +1,52 @@+import os+from dotenv import load_dotenv+from crewai import Crew, Process, LLM++from agents import (+ trend_intelligence_agent,+ copywriter_agent,+ visual_strategist_agent,+ posting_strategist_agent+)+from tasks import (+ trend_research_task,+ caption_writing_task,+ visual_prompt_task,+ posting_strategy_task+)++load_dotenv()++llm = LLM(+ model="moonshotai/Kimi-K3",+ base_url="https://inference.baseten.co/v1",+ api_key=os.getenv("BASETEN_API_KEY"),+ max_tokens=500,+ custom_openai=True,+ extra_body={"reasoning_effort": "none"},+)+++def build_instagram_post_crew():+ return Crew(+ agents=[+ trend_intelligence_agent,+ copywriter_agent,+ visual_strategist_agent,+ posting_strategist_agent+ ],+ tasks=[+ trend_research_task,+ caption_writing_task,+ visual_prompt_task,+ posting_strategy_task+ ],+ process=Process.sequential,+ verbose=True+ )+++def run_instagram_post_crew(topic: str):+ crew = build_instagram_post_crew()+ result = crew.kickoff(inputs={"topic": topic})+ return result, crewdiff --git a/ai_agents/instagram_post_crew/requirements.txt b/ai_agents/instagram_post_crew/requirements.txtnew file mode 100644index 0000000..0cb3540--- /dev/null+++ b/ai_agents/instagram_post_crew/requirements.txt@@ -0,0 +1,9 @@+crewai+crewai-tools+langchain-openai+langchain-community+ddgs+firecrawl-py+litellm+streamlit+python-dotenvdiff --git a/ai_agents/instagram_post_crew/tasks.py b/ai_agents/instagram_post_crew/tasks.pynew file mode 100644index 0000000..5008b7d--- /dev/null+++ b/ai_agents/instagram_post_crew/tasks.py@@ -0,0 +1,70 @@+from dotenv import load_dotenv+from crewai import Task++from agents import (+ trend_intelligence_agent,+ copywriter_agent,+ visual_strategist_agent,+ posting_strategist_agent+)++load_dotenv()++trend_research_task = Task(+ description=(+ "Research Instagram trends for the topic: '{topic}'. "+ "Use at most 2 tool calls total, then stop researching. "+ "Write a SHORT creative brief with these sections: "+ "1. Trending Formats, 2. Winning Hooks, 3. Visual Style Patterns, 4. Why These Work. "+ "Keep the entire brief under 350 words."+ ),+ expected_output=(+ "A short markdown creative brief with four labelled sections: "+ "Trending Formats, Winning Hooks, Visual Style Patterns, and Why These Work. "+ "Under 350 words total."+ ),+ agent=trend_intelligence_agent+)++caption_writing_task = Task(+ description=(+ "Using the creative brief for '{topic}', write three short Instagram caption "+ "variants: educational, emotional, and provocative. Briefly say which fits the "+ "niche best, then output the selected final caption with hashtags. "+ "Keep the entire response under 250 words."+ ),+ expected_output=(+ "Three labelled caption variants, one short selection reason, and one final "+ "caption with hashtags. Under 250 words total."+ ),+ agent=copywriter_agent,+ context=[trend_research_task]+)++visual_prompt_task = Task(+ description=(+ "Using the creative brief for '{topic}', briefly note color psychology and "+ "visual style choices, then give one ready to use image generation prompt. "+ "Keep the entire response under 200 words."+ ),+ expected_output=(+ "A short reasoning note followed by one detailed image generation prompt. "+ "Under 200 words total."+ ),+ agent=visual_strategist_agent,+ context=[trend_research_task]+)++posting_strategy_task = Task(+ description=(+ "Using the creative brief for '{topic}', recommend the best day and time to "+ "publish. Tie the reason to this niche's audience behavior. "+ "Keep the entire response under 150 words."+ ),+ expected_output=(+ "A short niche-specific reasoning note and one clear day/time recommendation. "+ "Under 150 words total."+ ),+ agent=posting_strategist_agent,+ context=[trend_research_task]+)diff --git a/ai_agents/instagram_post_crew/tools.py b/ai_agents/instagram_post_crew/tools.pynew file mode 100644index 0000000..50ed8cf--- /dev/null+++ b/ai_agents/instagram_post_crew/tools.py@@ -0,0 +1,20 @@+import os+from dotenv import load_dotenv+from crewai.tools import tool+from langchain_community.tools import DuckDuckGoSearchRun+from crewai_tools import FirecrawlScrapeWebsiteTool++load_dotenv()++_duckduckgo_search_run = DuckDuckGoSearchRun()+++@tool("DuckDuckGo Search")+def duckduckgo_search_tool(query: str) -> str:+ """Search DuckDuckGo for the given query and return the top results as text."""+ return _duckduckgo_search_run.run(query)+++firecrawl_scrape_tool = FirecrawlScrapeWebsiteTool(+ api_key=os.getenv("FIRECRAWL_API_KEY")+)