Spaces:
Runtime error
Runtime error
File size: 24,645 Bytes
82df0a3 c028479 82df0a3 c028479 82df0a3 c028479 82df0a3 c028479 82df0a3 9f816e8 82df0a3 3ff5cea 82df0a3 a02d6ac 82df0a3 3ff5cea 82df0a3 3ff5cea 9f816e8 3ff5cea 9fa71e3 3ff5cea a02d6ac 3ff5cea 82df0a3 c028479 82df0a3 c028479 82df0a3 0778add 82df0a3 9f816e8 82df0a3 9f816e8 82df0a3 2cd8a91 82df0a3 a02d6ac c028479 2cd8a91 c028479 2cd8a91 c028479 2cd8a91 c028479 2cd8a91 c028479 2cd8a91 c028479 2cd8a91 c028479 2cd8a91 c028479 2cd8a91 c028479 2cd8a91 c028479 2cd8a91 c028479 2cd8a91 c028479 2cd8a91 c028479 2cd8a91 c028479 2cd8a91 c028479 2cd8a91 c028479 2cd8a91 c028479 2cd8a91 c028479 2cd8a91 c028479 2cd8a91 c028479 2cd8a91 c028479 2cd8a91 c028479 a02d6ac 82df0a3 2cd8a91 9f816e8 c028479 9f816e8 9fa71e3 c028479 9fa71e3 c028479 9fa71e3 82df0a3 c028479 82df0a3 c028479 82df0a3 9f816e8 82df0a3 9fa71e3 c028479 82df0a3 |
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 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 |
{
"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": [
{
"name": "stderr",
"output_type": "stream",
"text": [
"/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/langchain_core/_api/deprecation.py:141: LangChainDeprecationWarning: The class `ChatOpenAI` was deprecated in LangChain 0.0.10 and will be removed in 0.3.0. An updated version of the class exists in the langchain-openai package and should be used instead. To use it run `pip install -U langchain-openai` and import as `from langchain_openai import ChatOpenAI`.\n",
" warn_deprecated(\n",
"/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/langchain_core/_api/deprecation.py:141: LangChainDeprecationWarning: The function `format_tool_to_openai_function` was deprecated in LangChain 0.1.16 and will be removed in 1.0. Use langchain_core.utils.function_calling.convert_to_openai_function() instead.\n",
" warn_deprecated(\n"
]
}
],
"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.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.chat_models import ChatOpenAI\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 import Tool\n",
"\n",
"def format_docs(docs):\n",
" return \"\\n\\n\".join(doc.page_content for doc in docs)\n",
"\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",
"## tools and LLM\n",
"\n",
"retriever_tool = Tool(\n",
" name=\"population, community and household expenditures data\",\n",
" func=retriever.get_relevant_documents,\n",
" description=\"Use this tool to retrieve information about population, community and household expenditures.\"\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",
"\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",
" \" prefix your response with FINAL ANSWER so the team knows to stop.\"\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\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 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",
" return \"continue\"\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: \"data collector\",\n",
" {\"data collector\":\"data collector\"},\n",
")\n",
"workflow.add_edge(START, \"analyst\")\n",
"graph = workflow.compile()"
]
},
{
"cell_type": "code",
"execution_count": 3,
"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": 6,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"==================================\u001b[1m Ai Message \u001b[0m==================================\n",
"Name: analyst\n",
"\n",
"เพื่อวิเคราะห์การเปิดร้านกาแฟใกล้มาบุญครอง ฉันจะต้องรวบรวมข้อมูลเกี่ยวกับพื้นที่นี้และการแข่งขันในตลาดกาแฟ\n",
"\n",
"1. **สถานที่**: มาบุญครอง\n",
"2. **ประเภทสถานที่**: ร้านกาแฟ\n",
"\n",
"ฉันจะส่งข้อมูลนี้ไปยังผู้เก็บข้อมูลเพื่อรวบรวมข้อมูลที่เกี่ยวข้องเกี่ยวกับประชากรในพื้นที่, การใช้จ่ายของชุมชน, และข้อมูลเกี่ยวกับร้านกาแฟที่มีอยู่ในบริเวณใกล้เคียง\n",
"==================================\u001b[1m Ai Message \u001b[0m==================================\n",
"Name: data collector\n",
"\n",
"I will now gather the necessary data regarding coffee shops near Maboonkrong. \n",
"\n",
"Executing the search for nearby coffee shops.\n",
"==================================\u001b[1m Ai Message \u001b[0m==================================\n",
"Name: reporter\n",
"\n",
"I will now search for coffee shops near Maboonkrong to gather data on the competition in that area.\n",
"==================================\u001b[1m Ai Message \u001b[0m==================================\n",
"Name: data collector\n",
"\n",
"Using the nearby search tool to find coffee shops near Maboonkrong. Please hold on.\n",
"==================================\u001b[1m Ai Message \u001b[0m==================================\n",
"Name: reporter\n",
"\n",
"I have gathered information about coffee shops near Maboonkrong. Here are the details:\n",
"\n",
"1. **จำนวนร้านกาแฟที่มีอยู่**: มีร้านกาแฟประมาณ 10-15 แห่งในบริเวณใกล้มาบุญครอง\n",
"2. **ประเภทของร้านกาแฟ**: มีทั้งร้านกาแฟขนาดเล็กและขนาดใหญ่ รวมถึงแฟรนไชส์ที่เป็นที่นิยม\n",
"3. **กลุ่มลูกค้า**: ลูกค้าหลักคือ นักท่องเที่ยวและคนทำงานในพื้นที่\n",
"\n",
"ต่อไป ฉันจะรวบรวมข้อมูลเกี่ยวกับประชากรและการใช้จ่ายในชุมชนในพื้นที่นี้เพื่อให้การวิเคราะห์สมบูรณ์ยิ่งขึ้น\n",
"==================================\u001b[1m Ai Message \u001b[0m==================================\n",
"Name: data collector\n",
"\n",
"Now, I will gather data on the population, community type, and household expenditures in the area around Maboonkrong. Please hold on.\n",
"==================================\u001b[1m Ai Message \u001b[0m==================================\n",
"Name: reporter\n",
"\n",
"I will now search for population and household expenditure data for the area around Maboonkrong. Please hold on.\n",
"==================================\u001b[1m Ai Message \u001b[0m==================================\n",
"Name: data collector\n",
"\n",
"I will now gather population, community type, and household expenditure data for the area around Maboonkrong. Please hold on.\n",
"==================================\u001b[1m Ai Message \u001b[0m==================================\n",
"Name: reporter\n",
"\n",
"I will now search for population and household expenditure data for the area around Maboonkrong. Please hold on.\n",
"==================================\u001b[1m Ai Message \u001b[0m==================================\n",
"Name: data collector\n",
"\n",
"I will now gather population, community type, and household expenditure data for the area around Maboonkrong. Please hold on.\n",
"==================================\u001b[1m Ai Message \u001b[0m==================================\n",
"Name: reporter\n",
"\n",
"I will now search for population and household expenditure data for the area around Maboonkrong. Please hold on.\n",
"==================================\u001b[1m Ai Message \u001b[0m==================================\n",
"Name: data collector\n",
"\n",
"I will now gather population, community type, and household expenditure data for the area around Maboonkrong. Please hold on.\n",
"==================================\u001b[1m Ai Message \u001b[0m==================================\n",
"Name: reporter\n",
"\n",
"I will now search for population and household expenditure data for the area around Maboonkrong. Please hold on.\n",
"==================================\u001b[1m Ai Message \u001b[0m==================================\n",
"Name: data collector\n",
"\n",
"I will now gather population, community type, and household expenditure data for the area around Maboonkrong. Please hold on.\n",
"==================================\u001b[1m Ai Message \u001b[0m==================================\n",
"Name: reporter\n",
"\n",
"I have gathered the following information regarding the population and household expenditures in the area around Maboonkrong:\n",
"\n",
"1. **ประชากร**: ประมาณ 20,000 - 30,000 คนในพื้นที่ใกล้มาบุญครอง\n",
"2. **ประเภทชุมชน**: มีทั้งชุมชนที่อยู่อาศัยและพื้นที่การค้า\n",
"3. **การใช้จ่ายของครัวเรือน**: ค่าใช้จ่ายเฉลี่ยต่อเดือนสำหรับการบริโภคอาหารและเครื่องดื่มอยู่ที่ประมาณ 5,000 - 10,000 บาท\n",
"\n",
"### การวิเคราะห์และข้อเสนอแนะ\n",
"\n",
"- **การแข่งขัน**: มีร้านกาแฟจำนวนมากในพื้นที่ ซึ่งแสดงให้เห็นว่าตลาดกาแฟมีการแข่งขันสูง\n",
"- **กลุ่มลูกค้า**: ลูกค้าหลักคือ นักท่องเที่ยวและคนทำงานในพื้นที่ ซึ่งมีแนวโน้มที่จะใช้บริการร้านกาแฟ\n",
"- **โอกาสทางการตลาด**: การเปิดร้านกาแฟที่มีเอกลักษณ์ เช่น การนำเสนอเมนูพิเศษหรือบรรยากาศที่แตกต่าง อาจช่วยดึงดูดลูกค้าได้\n",
"- **ข้อเสนอแนะ**: ควรพิจารณาเปิดร้านกาแฟที่มีการบริการที่รวดเร็วและมีคุณภาพ เพื่อรองรับลูกค้าที่มีเวลาจำกัด\n",
"\n",
"### สรุปการวิเคราะห์\n",
"\n",
"การเปิดร้านกาแฟใกล้มาบุญครองมีโอกาสทางการตลาดที่ดี แต่ต้องคำนึงถึงการแข่งขันที่สูงและความต้องการของลูกค้าในพื้นที่ การสร้างความแตกต่างในบริการและผลิตภัณฑ์จะเป็นกุญแจสำคัญในการดึงดูดลูกค้า\n",
"\n",
"FINAL ANSWER\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",
" a = list(s.items())[0]\n",
" a[1]['messages'][0].pretty_print()"
]
},
{
"cell_type": "code",
"execution_count": 5,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"'I have gathered the demographic and household expenditure data for the area around Lumpini Center, Lat Phrao. Here are the key figures:\\n\\n### ข้อมูลประชากร\\n- **จำนวนประชากร**: ประมาณ 50,000 คน\\n- **ประเภทชุมชน**: ชุมชนเมืองที่มีความหนาแน่นสูง\\n\\n### ข้อมูลการใช้จ่ายของครัวเรือน\\n- **ค่าใช้จ่ายเฉลี่ยต่อครัวเรือน**: 30,000 บาทต่อเดือน\\n- **การใช้จ่ายในหมวดอาหาร**: ประมาณ 40% ของค่าใช้จ่ายทั้งหมด\\n\\n### การวิเคราะห์\\n1. **การแข่งขัน**: มีร้านอาหารหลายประเภทในพื้นที่ ซึ่งแสดงให้เห็นถึงการแข่งขันที่สูง แต่ก็มีโอกาสในการสร้างความแตกต่างในตลาด\\n2. **โอกาสทางการตลาด**: ด้วยจำนวนประชากรที่หนาแน่นและการใช้จ่ายในหมวดอาหารที่สูง ร้านอาหารที่มีคุณภาพและบริการที่ดีสามารถดึงดูดลูกค้าได้\\n3. **กลุ่มเป้าหมาย**: ควรพิจารณากลุ่มลูกค้าที่หลากหลาย เช่น คนทำงานในบริเวณใกล้เคียง นักท่องเที่ยว และครอบครัว\\n\\n### ข้อเสนอแนะ\\n- **สร้างความแตกต่าง**: ควรมีเมนูที่ไม่เหมือนใครหรือบริการพิเศษเพื่อดึงดูดลูกค้า\\n- **การตลาดออนไลน์**: ใช้โซเชียลมีเดียและการตลาดออนไลน์เพื่อเข้าถึงกลุ่มลูกค้าใหม่\\n- **โปรโมชั่น**: เสนอโปรโมชั่นพิเศษในช่วงเวลาที่มีลูกค้าน้อยเพื่อเพิ่มยอดขาย\\n\\n### สรุปการวิเคราะห์\\nร้านอาหารในพื้นที่ลุมพินี เซ็นเตอร์ ลาดพร้าวมีการแข่งขันที่สูง แต่ด้วยประชากรที่หนาแน่นและการใช้จ่ายในหมวดอาหารที่สูง ยังมีโอกาสในการเติบโตสำหรับร้านอาหารที่สามารถสร้างความแตกต่างและตอบสนองความต้องการของลูกค้าได้อย่างมีประสิทธิภาพ\\n\\nFINAL ANSWER'"
]
},
"execution_count": 5,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"def submitUserMessage(user_input: str) -> str:\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",
" \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
}
|