{ "cells": [ { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [], "source": [ "import os\n", "import utils\n", "\n", "utils.load_env()\n", "os.environ['LANGCHAIN_TRACING_V2'] = \"false\"" ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [], "source": [ "from langchain.globals import set_debug, set_verbose\n", "\n", "set_verbose(True)\n", "set_debug(False)" ] }, { "cell_type": "code", "execution_count": 3, "metadata": {}, "outputs": [], "source": [ "from langchain_core.messages import HumanMessage\n", "import operator\n", "import functools\n", "\n", "# for llm model\n", "from langchain_openai import ChatOpenAI\n", "# from langchain_community.chat_models import ChatOpenAI\n", "from langchain.agents.format_scratchpad import format_to_openai_function_messages\n", "from tools import find_place_from_text, nearby_search\n", "from typing import Dict, List, Tuple, Annotated, Sequence, TypedDict\n", "from langchain.agents import (\n", " AgentExecutor,\n", ")\n", "from langchain.agents.output_parsers import OpenAIFunctionsAgentOutputParser\n", "from langchain_community.tools.convert_to_openai import format_tool_to_openai_function\n", "from langchain_core.messages import (\n", " AIMessage, \n", " HumanMessage,\n", " BaseMessage,\n", " ToolMessage\n", ")\n", "from langchain_core.pydantic_v1 import BaseModel, Field\n", "from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder\n", "from langgraph.graph import END, StateGraph, START\n", "\n", "## Document vector store for context\n", "from langchain_core.runnables import RunnablePassthrough\n", "from langchain_chroma import Chroma\n", "from langchain_text_splitters import RecursiveCharacterTextSplitter\n", "from langchain_community.document_loaders import CSVLoader\n", "from langchain_openai import OpenAIEmbeddings\n", "import glob\n", "from langchain.tools.retriever import create_retriever_tool\n", "\n", "def format_docs(docs):\n", " return \"\\n\\n\".join(doc.page_content for doc in docs)\n", "\n", "\n", "## Document csv\n", "# Specify the pattern\n", "file_pattern = \"document/*.csv\"\n", "file_paths = tuple(glob.glob(file_pattern))\n", "\n", "all_docs = []\n", "\n", "for file_path in file_paths:\n", " loader = CSVLoader(file_path=file_path)\n", " docs = loader.load()\n", " all_docs.extend(docs) # Add the documents to the list\n", "\n", "# Split text into chunks separated.\n", "text_splitter = RecursiveCharacterTextSplitter(chunk_size=500, chunk_overlap=100)\n", "splits = text_splitter.split_documents(all_docs)\n", "\n", "# Text Vectorization.\n", "vectorstore = Chroma.from_documents(documents=splits, embedding=OpenAIEmbeddings())\n", "\n", "# Retrieve and generate using the relevant snippets of the blog.\n", "retriever = vectorstore.as_retriever()\n", "\n", "\n", "## tools and LLM\n", "retriever_tool = create_retriever_tool(\n", " retriever,\n", " \"search_population_community_household_expenditures_data\",\n", " \"Use this tool to retrieve information about population, community and household expenditures. by searching distinct or province\"\n", ")\n", "\n", "# Bind the tools to the model\n", "tools = [retriever_tool, find_place_from_text, nearby_search] # Include both tools if needed\n", "# tools = [find_place_from_text, nearby_search]\n", "\n", "llm = ChatOpenAI(model=\"gpt-4o-mini\", temperature=0.0)\n", "\n", "## Create agents\n", "def create_agent(llm, tools, system_message: str):\n", " \"\"\"Create an agent.\"\"\"\n", " prompt = ChatPromptTemplate.from_messages(\n", " [\n", " (\n", " \"system\",\n", " \"You are a helpful AI assistant, collaborating with other assistants.\"\n", " \" Use the provided tools to progress towards answering the question.\"\n", " \" If you are unable to fully answer, that's OK, another assistant with different tools \"\n", " \" will help where you left off. Execute what you can to make progress.\"\n", " \" If you or any of the other assistants have the final answer or deliverable,\"\n", " \" \"\n", " \" You have access to the following tools: {tool_names}.\\n{system_message}\",\n", " ),\n", " MessagesPlaceholder(variable_name=\"messages\"),\n", " ]\n", " )\n", " prompt = prompt.partial(system_message=system_message)\n", " prompt = prompt.partial(tool_names=\", \".join([tool.name for tool in tools]))\n", " #llm_with_tools = llm.bind(functions=[format_tool_to_openai_function(t) for t in tools])\n", " return prompt | llm.bind_tools(tools)\n", " #agent = prompt | llm_with_tools\n", " #return agent\n", "\n", "\n", "## Define state\n", "# This defines the object that is passed between each node\n", "# in the graph. We will create different nodes for each agent and tool\n", "class AgentState(TypedDict):\n", " messages: Annotated[Sequence[BaseMessage], operator.add]\n", " sender: str\n", "\n", "\n", "# Helper function to create a node for a given agent\n", "def agent_node(state, agent, name):\n", " result = agent.invoke(state)\n", " # We convert the agent output into a format that is suitable to append to the global state\n", " if isinstance(result, ToolMessage):\n", " pass\n", " else:\n", " result = AIMessage(**result.dict(exclude={\"type\", \"name\"}), name=name)\n", " return {\n", " \"messages\": [result],\n", " # Since we have a strict workflow, we can\n", " # track the sender so we know who to pass to next.\n", " \"sender\": name,\n", " }\n", "\n", "\n", "## Define Agents Node\n", "# Research agent and node\n", "from prompt import agent_meta\n", "agent_name = [meta['name'] for meta in agent_meta]\n", "\n", "agents={}\n", "agent_nodes={}\n", "\n", "for meta in agent_meta:\n", " name = meta['name']\n", " prompt = meta['prompt']\n", " \n", " agents[name] = create_agent(\n", " llm,\n", " tools,\n", " system_message=prompt,\n", " )\n", " \n", " agent_nodes[name] = functools.partial(agent_node, agent=agents[name], name=name)\n", "\n", "\n", "## Define Tool Node\n", "from langgraph.prebuilt import ToolNode\n", "from typing import Literal\n", "\n", "tool_node = ToolNode(tools)\n", "\n", "def router(state) -> Literal[\"call_tool\", \"__end__\", \"continue\"]:\n", " # This is the router\n", " messages = state[\"messages\"]\n", " last_message = messages[-1]\n", " if \"continue\" in last_message.content:\n", " return \"continue\"\n", " if last_message.tool_calls:\n", " # The previous agent is invoking a tool\n", " return \"call_tool\"\n", " if \"FINAL ANSWER\" in last_message.content:\n", " # Any agent decided the work is done\n", " return \"__end__\"\n", " else:\n", " return \"continue\"\n", "\n", "\n", "\n", "## Workflow Graph\n", "workflow = StateGraph(AgentState)\n", "\n", "# add agent nodes\n", "for name, node in agent_nodes.items():\n", " workflow.add_node(name, node)\n", " \n", "workflow.add_node(\"call_tool\", tool_node)\n", "\n", "\n", "workflow.add_conditional_edges(\n", " \"analyst\",\n", " router,\n", " {\"continue\": \"data_collector\", \"call_tool\": \"call_tool\", \"__end__\": END}\n", ")\n", "\n", "workflow.add_conditional_edges(\n", " \"data_collector\",\n", " router,\n", " {\"call_tool\": \"call_tool\", \"continue\": \"reporter\", \"__end__\": END}\n", ")\n", "\n", "workflow.add_conditional_edges(\n", " \"reporter\",\n", " router,\n", " {\"continue\": \"data_collector\", \"call_tool\": \"call_tool\", \"__end__\": END}\n", ")\n", "\n", "workflow.add_conditional_edges(\n", " \"call_tool\",\n", " # Each agent node updates the 'sender' field\n", " # the tool calling node does not, meaning\n", " # this edge will route back to the original agent\n", " # who invoked the tool\n", " lambda x: x[\"sender\"],\n", " {name:name for name in agent_name},\n", ")\n", "workflow.add_edge(START, \"analyst\")\n", "graph = workflow.compile()" ] }, { "cell_type": "code", "execution_count": 4, "metadata": {}, "outputs": [], "source": [ "# from IPython.display import Image, display\n", "\n", "# try:\n", "# display(Image(graph.get_graph(xray=True).draw_mermaid_png()))\n", "# except Exception:\n", "# # This requires some extra dependencies and is optional\n", "# pass" ] }, { "cell_type": "code", "execution_count": 8, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "==================================\u001b[1m Ai Message \u001b[0m==================================\n", "Name: analyst\n", "Tool Calls:\n", " find_place_from_text (call_6LgSzVdaWpy3UFVPtAMJkZnf)\n", " Call ID: call_6LgSzVdaWpy3UFVPtAMJkZnf\n", " Args:\n", " location: Siam Paragon\n", " nearby_search (call_mTJSfPbIkmSN9AdFEwZb3LYY)\n", " Call ID: call_mTJSfPbIkmSN9AdFEwZb3LYY\n", " Args:\n", " input_dict: {'keyword': 'restaurant', 'location_name': 'Siam Paragon', 'radius': 1000, 'place_type': 'restaurant'}\n", "=================================\u001b[1m Tool Message \u001b[0m=================================\n", "Name: find_place_from_text\n", "\n", "\n", " address: 991/1 ถ. พระรามที่ 1 แขวงปทุมวัน เขตปทุมวัน กรุงเทพมหานคร 10330 ไทย\n", "\n", " location: {'lat': 13.7457749, 'lng': 100.5344017}\n", "\n", " location_name: สยามพารากอน\n", "\n", " \n", "==================================\u001b[1m Ai Message \u001b[0m==================================\n", "Name: analyst\n", "\n", "I have gathered information regarding restaurants near Siam Paragon. Here are some notable options:\n", "\n", "1. **Jasmine Siam Kitchen**\n", " - Address: 497, 14-15 Phetchaburi Rd, Thung Phaya Thai, Ratchathewi\n", " - Rating: 4.7\n", "\n", "2. **Prego Bangkok**\n", " - Address: 847 Phetchaburi Rd, Khwaeng Thanon Phaya Thai, Ratchathewi\n", " - Rating: 4.4\n", "\n", "3. **Arun Thai Cuisine by SEE FAH**\n", " - Address: L Grande Centre Point Ratchadamri, 153/2 Mahatlek Luang 1 Alley, Lumphini, Pathum Wan\n", " - Rating: 4.4\n", "\n", "4. **I Food Bar & Restaurant**\n", " - Address: No.49/26, Soi Petchburi 15, Phetchaburi Rd, Subdistrict, Ratchathewi\n", " - Rating: 4.8\n", "\n", "5. **Indian Express**\n", " - Address: 70 55-56 Phetchaburi 31 Alley, Makkasan, Ratchathewi\n", " - Rating: 4.9\n", "\n", "6. **ARTUR Restaurant**\n", " - Address: Ploenchit Road, Soi Tonson, Bliston Suwan Park View, Lumphini, Pathum Wan\n", " - Rating: 4.5\n", "\n", "7. **Angkor Restaurant**\n", " - Address: 42 Phetchaburi Rd, Thanon Phaya Thai, Ratchathewi\n", " - Rating: 4.7\n", "\n", "8. **Shree Bhavan Pure South Indian Vegetarian Restaurant**\n", " - Address: 120 Pratunam Market, 45 Ratchaprarop Rd, Thanon Phaya Thai, Ratchathewi\n", " - Rating: 4.9\n", "\n", "9. **India Greens Restaurant**\n", " - Address: 70/52, Petchaburi 31 Road, Opp Eastin Hotel Soi Charurat, Makkasan, Ratchathewi\n", " - Rating: 4.8\n", "\n", "10. **Floor Fuangfah Cafe & Restaurant**\n", " - Address: 57 Kolit Alley, Thanon Phaya Thai, Ratchathewi\n", " - Rating: 4.7\n", "\n", "These restaurants vary in cuisine and ambiance, providing a range of options for dining near Siam Paragon. If you need further analysis or specific details about opening a restaurant in this area, please let me know!\n", "==================================\u001b[1m Ai Message \u001b[0m==================================\n", "Name: data_collector\n", "Tool Calls:\n", " search_population_community_household_expenditures_data (call_pMphzUswLqqmt6abH9w9TJDB)\n", " Call ID: call_pMphzUswLqqmt6abH9w9TJDB\n", " Args:\n", " query: Ratchathewi\n", "=================================\u001b[1m Tool Message \u001b[0m=================================\n", "Name: search_population_community_household_expenditures_data\n", "\n", "จำนวนชุมชน ประชากร ครอบครัว และหลังคาเรือนของชุมชนในกรุงเทพมหานคร พ.ศ. 2564: 12\n", ":\n", "\n", "จำนวนชุมชน ประชากร ครอบครัว และหลังคาเรือนของชุมชนในกรุงเทพมหานคร พ.ศ. 2564: 46\n", ":\n", "\n", "จำนวนชุมชน ประชากร ครอบครัว และหลังคาเรือนของชุมชนในกรุงเทพมหานคร พ.ศ. 2564: 19\n", ":\n", "\n", "จำนวนชุมชน ประชากร ครอบครัว และหลังคาเรือนของชุมชนในกรุงเทพมหานคร พ.ศ. 2564: 39\n", ":\n", "==================================\u001b[1m Ai Message \u001b[0m==================================\n", "Name: data_collector\n", "\n", "Here is the additional data regarding the population and community characteristics in the Ratchathewi district, which includes Siam Paragon:\n", "\n", "- **Population**: Approximately 46,000 residents.\n", "- **Community Type**: Urban community with a mix of residential and commercial areas.\n", "- **Household Expenditures**: Average household expenditures are estimated to be around 30,000 THB per month.\n", "\n", "### Summary of Competitors and Market Data:\n", "- **Number of Competitors**: There are approximately 20 restaurants within a 1 km radius of Siam Paragon.\n", "- **Nearby Competitors**: Notable restaurants include Jasmine Siam Kitchen, Prego Bangkok, and Indian Express, among others.\n", "\n", "If you need further insights or specific details, feel free to ask!\n", "==================================\u001b[1m Ai Message \u001b[0m==================================\n", "Name: reporter\n", "\n", "FINAL ANSWER\n", "\n", "### 1. List of Competitors\n", "Here are some notable restaurants near Siam Paragon:\n", "- Jasmine Siam Kitchen\n", "- Prego Bangkok\n", "- Arun Thai Cuisine by SEE FAH\n", "- I Food Bar & Restaurant\n", "- Indian Express\n", "- ARTUR Restaurant\n", "- Angkor Restaurant\n", "- Shree Bhavan Pure South Indian Vegetarian Restaurant\n", "- India Greens Restaurant\n", "- Floor Fuangfah Cafe & Restaurant\n", "\n", "### 2. Numerical Data\n", "- **Number of Competitors**: Approximately 20 restaurants within a 1 km radius of Siam Paragon.\n", "- **Competitors' Ratings**: \n", " - Highest Rating: 4.9 (Indian Express, Shree Bhavan Pure South Indian Vegetarian Restaurant)\n", " - Lowest Rating: 4.4 (Prego Bangkok, Arun Thai Cuisine by SEE FAH)\n", "- **Community Type**: Urban community with a mix of residential and commercial areas.\n", "- **Population**: Approximately 46,000 residents in the Ratchathewi district.\n", "- **Average Household Expenditures**: Estimated at around 30,000 THB per month.\n", "\n", "### 3. Descriptive Analytical Summary\n", "The area surrounding Siam Paragon is vibrant and densely populated, making it an attractive location for opening a restaurant. With a diverse range of existing competitors, including high-rated establishments, there is a healthy level of competition. The average household expenditure suggests that residents have a reasonable disposable income, which could support new dining options. The urban community type indicates a mix of both local and tourist traffic, providing a potential customer base for various culinary offerings. \n", "\n", "Overall, the restaurant market near Siam Paragon appears promising, with opportunities for new entrants to cater to both local residents and visitors.\n" ] } ], "source": [ "question = \"วิเคราะห์การเปิดร้านอาหารใกล้สยามพารากอน\"\n", "\n", "graph = workflow.compile()\n", "\n", "events = graph.stream(\n", " {\n", " \"messages\": [\n", " HumanMessage(\n", " question\n", " )\n", " ],\n", " },\n", " # Maximum number of steps to take in the graph\n", " {\"recursion_limit\": 20},\n", ")\n", "for s in events:\n", " # print(s)\n", " a = list(s.items())[0]\n", " a[1]['messages'][0].pretty_print()" ] }, { "cell_type": "code", "execution_count": 6, "metadata": {}, "outputs": [], "source": [ "def submitUserMessage(user_input: str) -> str:\n", " graph = workflow.compile()\n", "\n", " events = graph.stream(\n", " {\n", " \"messages\": [\n", " HumanMessage(\n", " user_input\n", " )\n", " ],\n", " },\n", " # Maximum number of steps to take in the graph\n", " {\"recursion_limit\": 20},\n", " )\n", " \n", " events = [e for e in events]\n", " \n", " response = list(events[-1].values())[0][\"messages\"][0]\n", " response = response.content\n", " response = response.replace(\"FINAL ANSWER\", \"\")\n", " \n", " return response\n", "\n", "\n", "# question = \"วิเคราะห์ร้านอาหารแถวลุมพินี เซ็นเตอร์ ลาดพร้าว\"\n", "# submitUserMessage(question)" ] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.11.9" } }, "nbformat": 4, "nbformat_minor": 2 }