function AICopilot() { const [isOpen, setIsOpen] = useState(false); const [messages, setMessages] = useState([ { role: 'assistant', content: 'สวัสดีครับ! ผมคือ AI ผู้เชี่ยวชาญด้าน Meta Ads ผมสามารถดึงข้อมูลแคมเปญของคุณมาวิเคราะห์ให้ได้ คุณอยากทราบอะไรเกี่ยวกับโฆษณาของคุณบ้างครับ?' } ]); const [input, setInput] = useState(''); const [loading, setLoading] = useState(false); const messagesEndRef = useRef(null); // Auto-scroll useEffect(() => { if (messagesEndRef.current) { messagesEndRef.current.scrollIntoView({ behavior: 'smooth' }); } }, [messages, isOpen]); const META_TOOLS = [ { type: 'function', function: { name: 'get_meta_dashboard', description: 'Fetch the 7-day performance dashboard and placement breakdown from Meta Ads API. Use this when user asks about overall spend, revenue, ROAS, or placement performance.', parameters: { type: 'object', properties: {} } } }, { type: 'function', function: { name: 'get_meta_campaigns', description: 'Fetch the list of active campaigns and their performance (spend, roas, conversions, cpc, ctr) from Meta Ads API. Use this when the user asks about specific campaigns or wants a breakdown by campaign.', parameters: { type: 'object', properties: {} } } } ]; const handleSend = async () => { if (!input.trim() || loading) return; const userMsg = { role: 'user', content: input.trim() }; const newMessages = [...messages, userMsg]; setMessages(newMessages); setInput(''); setLoading(true); try { // call aiChatWithTools which handles tool execution autonomously const finalMsgs = await aiChatWithTools( [ { role: 'system', content: 'คุณเป็น AI ผู้เชี่ยวชาญด้าน Meta Ads (Data Analyst) ของแบรนด์ Earthlab. ตอบเป็นภาษาไทย ให้คำแนะนำที่เป็นประโยชน์. หากข้อมูลยาวให้จัดรูปแบบเป็น Bullet points. คุณมีเครื่องมือในการดึงข้อมูลจาก Meta Ads API.' }, ...newMessages ], META_TOOLS ); // finalMsgs contains system, user, tool, and assistant messages. // we only want to display user and assistant content messages in the UI // filter out system and tool messages const displayMsgs = finalMsgs.filter(m => (m.role === 'user' || m.role === 'assistant') && (typeof m.content === 'string' && m.content.length > 0) ); // the displayMsgs includes the system prompt at index 0. Let's slice it out and prepend the initial greeting. // Wait, finalMsgs has the system prompt at [0]. const filtered = finalMsgs.filter(m => m.role !== 'system' && m.role !== 'tool' && !m.tool_calls); // Merge with the first greeting message setMessages([messages[0], ...filtered]); } catch (err) { setMessages(prev => [...prev, { role: 'assistant', content: `เกิดข้อผิดพลาด: ${err.message}` }]); } setLoading(false); }; if (!isOpen) { return ( ); } return (