Spaces:
Sleeping
Sleeping
| import os | |
| import gradio as gr | |
| from smolagents import CodeAgent, LiteLLMModel | |
| from tools.meta_ads_tools import ( | |
| GetAdAccountsTool, | |
| GetCampaignsTool, | |
| GetAdSetsTool, | |
| GetAdsTool, | |
| GetAdInsightsTool, | |
| ) | |
| # Initialize the agent with custom Meta Ads tools | |
| def create_agent(): | |
| """Create and return a Code Agent with Meta Ads tools.""" | |
| # Load OpenAI API key from Hugging Face Space secret | |
| api_key = os.environ.get("OPENAI_API_KEY") | |
| if not api_key: | |
| raise ValueError("OPENAI_API_KEY not found in Space secrets.") | |
| # Create the model | |
| model = LiteLLMModel( | |
| model_id="gpt-4o", | |
| api_key=api_key, | |
| ) | |
| # Create tools | |
| tools = [ | |
| GetAdAccountsTool(), | |
| GetCampaignsTool(), | |
| GetAdSetsTool(), | |
| GetAdsTool(), | |
| GetAdInsightsTool(), | |
| ] | |
| # Create the agent | |
| agent = CodeAgent( | |
| tools=tools, | |
| model=model, | |
| max_steps=10, | |
| verbosity_level=1, | |
| ) | |
| return agent | |
| def respond( | |
| message, | |
| history: list[dict[str, str]], | |
| system_message, | |
| max_tokens, | |
| ): | |
| """ | |
| Uses smolagents Code Agent with custom Meta Ads tools. | |
| The agent can retrieve information about Meta ad accounts, campaigns, ad sets, ads, and insights. | |
| """ | |
| try: | |
| # Create the agent | |
| agent = create_agent() | |
| # Add optimized instructions to make the agent execute code immediately | |
| optimized_message = f"""Execute the following request immediately using the available tools. Do NOT explain what you will do - just write and execute the code directly. | |
| User request: {message} | |
| Instructions: | |
| - Write code in <code> tags and execute it immediately | |
| - Use the available tools: get_ad_accounts(), get_campaigns(), get_adsets(), get_ads(), get_ad_insights() | |
| - The tools return structured data (lists of dictionaries) | |
| - Format the results in a user-friendly markdown format before calling final_answer() | |
| - For lists of items, use markdown tables or bullet lists with clear formatting | |
| - Include relevant fields and make the output easy to read | |
| - Be direct and efficient""" | |
| # Run the agent | |
| response = agent.run(optimized_message) | |
| yield str(response) | |
| except Exception as e: | |
| yield f"Error: {str(e)}\n\nPlease make sure you have set up the following Space secrets:\n- OPENAI_API_KEY: Your OpenAI API key\n- META_ACCESS_TOKEN: Your Meta access token\n- META_APP_ID (optional): Your Meta app ID\n- META_APP_SECRET (optional): Your Meta app secret" | |
| """ | |
| For information on how to customize the ChatInterface, peruse the gradio docs: https://www.gradio.app/docs/chatinterface | |
| """ | |
| chatbot = gr.ChatInterface( | |
| respond, | |
| type="messages", | |
| additional_inputs=[ | |
| gr.Textbox( | |
| value="You are a Meta Ads assistant. You can help users retrieve information about their ad accounts, campaigns, ad sets, ads, and performance insights using the Meta Ads API. The tools return structured data (lists of dictionaries) that you can process, filter, and analyze. Always format the results in user-friendly markdown (tables, bullet lists, etc.) before presenting them to the user.", | |
| label="System message", | |
| lines=3 | |
| ), | |
| gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max new tokens"), | |
| ], | |
| title="Meta Ads API Agent", | |
| description=""" | |
| This is an AI agent powered by smolagents that can help you retrieve information about your Meta advertising campaigns. | |
| **Available capabilities:** | |
| - Get ad accounts | |
| - Get campaigns for an account | |
| - Get ad sets for a campaign | |
| - Get ads for an ad set | |
| - Get performance insights | |
| **Required Space Secrets:** | |
| - `OPENAI_API_KEY`: Your OpenAI API key | |
| - `META_ACCESS_TOKEN`: Your Meta access token | |
| - `META_APP_ID` (optional): Your Meta app ID | |
| - `META_APP_SECRET` (optional): Your Meta app secret | |
| **Example queries:** | |
| - "Show me all my ad accounts" | |
| - "Get campaigns for account act_123456789" | |
| - "What are the insights for campaign 123456789 in the last 7 days?" | |
| """, | |
| examples=[ | |
| ["Show me all my ad accounts"], | |
| ["List my ad accounts and tell me which ones are active"], | |
| ["Get campaigns for account act_123456789"], | |
| ["Get ad sets for campaign 123456789"], | |
| ["What are the insights for my account in the last 30 days?"], | |
| ], | |
| ) | |
| with gr.Blocks() as demo: | |
| chatbot.render() | |
| if __name__ == "__main__": | |
| demo.launch() | |