| 10 | from app.services.scrapegraph import ScrapingService |
| 11 | |
| 12 | class KimiScrapingAgent: |
| 13 | def __init__(self): |
| 14 | self.llm = get_llm() |
| 15 | self.scraping_service = ScrapingService(settings.SCRAPEGRAPH_API_KEY) |
| 16 | self.memory = ConversationBufferMemory(return_messages=True) |
| 17 | self.agent_executor = self._create_agent() |
| 18 | |
| 19 | def _create_agent(self): |
| 20 | """Create the LangChain agent with tools.""" |
| 21 | |
| 22 | # Define tools |
| 23 | tools = [ |
| 24 | Tool( |
| 25 | name="add_url", |
| 26 | description="Add a URL to the scraping pipeline. Use this when the user wants to add a website to scrape.", |
| 27 | func=self._add_url_tool |
| 28 | ), |
| 29 | Tool( |
| 30 | name="list_urls", |
| 31 | description="List all URLs in the current pipeline.", |
| 32 | func=self._list_urls_tool |
| 33 | ), |
| 34 | Tool( |
| 35 | name="define_schema", |
| 36 | description="Define or update the data extraction schema. Use when user wants to specify what data to extract.", |
| 37 | func=self._define_schema_tool |
| 38 | ), |
| 39 | Tool( |
| 40 | name="generate_code", |
| 41 | description="Generate Python code for the scraping pipeline.", |
| 42 | func=self._generate_code_tool |
| 43 | ), |
| 44 | Tool( |
| 45 | name="validate_url", |
| 46 | description="Check if a URL is valid and accessible.", |
| 47 | func=self._validate_url_tool |
| 48 | ) |
| 49 | ] |
| 50 | |
| 51 | # Create prompt |
| 52 | prompt = ChatPromptTemplate.from_messages([ |
| 53 | ("system", """You are ScrapeCraft AI, an expert assistant for building web scraping pipelines using ScrapeGraphAI. |
| 54 | |
| 55 | Your role is to help users: |
| 56 | 1. Add and manage URLs they want to scrape |
| 57 | 2. Define data schemas (what information to extract) |
| 58 | 3. Generate Python code using the scrapegraph_py library |
| 59 | 4. Execute scraping pipelines |
| 60 | |
| 61 | Current pipeline state: |
| 62 | URLs: {urls} |
| 63 | Schema: {schema} |
| 64 | |
| 65 | Be helpful, concise, and guide users through the scraping process. When users want to add URLs or define schemas, use the appropriate tools. |
| 66 | Always explain what you're doing and provide clear next steps."""), |
| 67 | MessagesPlaceholder(variable_name="chat_history"), |
| 68 | ("human", "{input}"), |
| 69 | MessagesPlaceholder(variable_name="agent_scratchpad") |