File size: 4,560 Bytes
76dbf6e
6924c65
6db4648
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3417789
6db4648
 
 
 
 
 
 
 
 
 
 
 
f6e10f4
6db4648
 
 
 
 
 
 
 
6924c65
 
 
 
 
 
 
 
 
6db4648
 
6924c65
76dbf6e
6db4648
 
 
f6e10f4
 
 
 
 
 
 
 
4b85f1d
 
 
 
f6e10f4
 
 
 
6db4648
 
76dbf6e
 
6db4648
6924c65
 
 
 
 
 
 
 
 
6db4648
4b85f1d
6db4648
 
 
6924c65
 
6db4648
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d3d49f1
4b85f1d
d3d49f1
 
 
6db4648
6924c65
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
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()