import { tool } from 'ai'; import { z } from "zod"; import axios from 'axios'; const searchTweets = async (query) => { const options = { method: 'GET', url: 'https://twitter-api45.p.rapidapi.com/search.php', params: { query, search_type: 'Top' }, headers: { 'x-rapidapi-key': process.env.TWITTER_RAPIDAPI, 'x-rapidapi-host': 'twitter-api45.p.rapidapi.com', }, }; try { const { data } = await axios.request(options); const tweets = []; if (data.timeline) { for (const tweet of data.timeline) { const { lang, type, media, user_info, entities, conversation_id, text, ...res } = tweet; const cleanText = text .replace(/\n/g, " ") .replace(/&/g, "") .replace(/[^\x00-\x7F]/g, "") .replace(/\s+/g, " ") .trim(); tweets.push({ ...res, text: cleanText }); if (tweets.length === 20) break; } } return tweets; } catch (error) { throw Error("Failed to search Twitter. Please try again later") } }; export const searchTweetsTool = (userId, chatId,responseId, dataStream) => tool({ description: "Search for tweets based on a query.", parameters: z.object({ query: z.string().describe("Search query for tweets"), }), execute: async ({ query }) => { try { console.log(`${userId} ${chatId} called searchTweets with query: ${query}`); const tweets = await searchTweets(query); if (tweets) { tweets.forEach(tweet => { dataStream.writeMessageAnnotation({ id: responseId, tool_type: 'tweet', content: tweet.tweet_id.toString(), }); }); tweets.map(async (tweet) => { }) } return JSON.stringify(tweets); } catch (error) { console.error("Error occurred while executing searchTweetsTool:", error); return "An error occurred while searching for tweets. Please try again later."; } }, });