{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "51466c8d-8ce4-4b3d-be4e-18fdbeda5f53",
   "metadata": {},
   "source": [
    "# How to kick off background runs\n",
    "\n",
    "This guide covers how to kick off background runs for your agent.\n",
    "This can be useful for long running jobs."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "b8e6408a-b37e-428f-9567-077fa55d58e8",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Initialize the client\n",
    "from langgraph_sdk import get_client\n",
    "\n",
    "client = get_client()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "4947e9bc-111f-4991-8c41-1041da9bf0ba",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'assistant_id': 'e90fee30-be91-43aa-a33c-d54bd219072e',\n",
       " 'graph_id': 'agent',\n",
       " 'created_at': '2024-06-18T18:06:55.102231+00:00',\n",
       " 'updated_at': '2024-06-18T18:06:55.102231+00:00',\n",
       " 'config': {'configurable': {'model_name': 'anthropic'}},\n",
       " 'metadata': {}}"
      ]
     },
     "execution_count": 2,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# List available assistants\n",
    "assistants = await client.assistants.search()\n",
    "assistants[0]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "230c0464-a6e5-420f-9e38-ca514e5634ce",
   "metadata": {},
   "outputs": [],
   "source": [
    "# NOTE: we can use `assistant_id` UUID from the above response, or just pass graph ID instead when creating runs. we'll use graph ID here\n",
    "assistant_id = \"agent\""
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "56aa5159-5583-4134-9210-709b969bda6f",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'thread_id': '5fc20631-47b7-48cd-8aa2-9f2eace9778d',\n",
       " 'created_at': '2024-06-21T14:58:02.079462+00:00',\n",
       " 'updated_at': '2024-06-21T14:58:02.079462+00:00',\n",
       " 'metadata': {}}"
      ]
     },
     "execution_count": 4,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# Create a new thread\n",
    "thread = await client.threads.create()\n",
    "thread"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "147c3f98-f889-4f05-a090-6b31f2a0b291",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[]"
      ]
     },
     "execution_count": 5,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# If we list runs on this thread, we can see it is empty\n",
    "runs = await client.runs.list(thread[\"thread_id\"])\n",
    "runs"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "8c7b44ef-4816-496d-88a1-2f7327cf576d",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Let's kick off a run\n",
    "input = {\"messages\": [{\"role\": \"human\", \"content\": \"what's the weather in sf\"}]}\n",
    "run = await client.runs.create(thread[\"thread_id\"], assistant_id, input=input)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "d84b4d80-b0aa-4d9f-a05d-0744b2fe8f72",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'run_id': '1ef2fdea-814c-6165-8b2a-a40e2a028198',\n",
       " 'thread_id': '5fc20631-47b7-48cd-8aa2-9f2eace9778d',\n",
       " 'assistant_id': 'fe096781-5601-53d2-b2f6-0d3403f7e9ca',\n",
       " 'created_at': '2024-06-21T14:58:02.095911+00:00',\n",
       " 'updated_at': '2024-06-21T14:58:02.095911+00:00',\n",
       " 'metadata': {},\n",
       " 'status': 'pending',\n",
       " 'kwargs': {'input': {'messages': [{'role': 'human',\n",
       "     'content': 'what's the weather in sf'}]},\n",
       "  'config': {'metadata': {'created_by': 'system'},\n",
       "   'configurable': {'run_id': '1ef2fdea-814c-6165-8b2a-a40e2a028198',\n",
       "    'user_id': '',\n",
       "    'graph_id': 'agent',\n",
       "    'thread_id': '5fc20631-47b7-48cd-8aa2-9f2eace9778d',\n",
       "    'thread_ts': None,\n",
       "    'assistant_id': 'fe096781-5601-53d2-b2f6-0d3403f7e9ca'}},\n",
       "  'webhook': None,\n",
       "  'temporary': False,\n",
       "  'stream_mode': ['events'],\n",
       "  'feedback_keys': None,\n",
       "  'interrupt_after': None,\n",
       "  'interrupt_before': None},\n",
       " 'multitask_strategy': 'reject'}"
      ]
     },
     "execution_count": 7,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# The first time we poll it, we can see `status=pending`\n",
    "await client.runs.get(thread[\"thread_id\"], run[\"run_id\"])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "3639da3c-bfe5-454c-ab1e-8ed7af394dfe",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Wait until the run finishes\n",
    "await client.runs.join(thread[\"thread_id\"], run[\"run_id\"])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "8fa206ed-515e-4607-9a80-bebafe76cc24",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'run_id': '1ef2fdea-814c-6165-8b2a-a40e2a028198',\n",
       " 'thread_id': '5fc20631-47b7-48cd-8aa2-9f2eace9778d',\n",
       " 'assistant_id': 'fe096781-5601-53d2-b2f6-0d3403f7e9ca',\n",
       " 'created_at': '2024-06-21T14:58:02.095911+00:00',\n",
       " 'updated_at': '2024-06-21T14:58:02.095911+00:00',\n",
       " 'metadata': {},\n",
       " 'status': 'success',\n",
       " 'kwargs': {'input': {'messages': [{'role': 'human',\n",
       "     'content': 'what's the weather in sf'}]},\n",
       "  'config': {'metadata': {'created_by': 'system'},\n",
       "   'configurable': {'run_id': '1ef2fdea-814c-6165-8b2a-a40e2a028198',\n",
       "    'user_id': '',\n",
       "    'graph_id': 'agent',\n",
       "    'thread_id': '5fc20631-47b7-48cd-8aa2-9f2eace9778d',\n",
       "    'thread_ts': None,\n",
       "    'assistant_id': 'fe096781-5601-53d2-b2f6-0d3403f7e9ca'}},\n",
       "  'webhook': None,\n",
       "  'temporary': False,\n",
       "  'stream_mode': ['events'],\n",
       "  'feedback_keys': None,\n",
       "  'interrupt_after': None,\n",
       "  'interrupt_before': None},\n",
       " 'multitask_strategy': 'reject'}"
      ]
     },
     "execution_count": 9,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# Eventually, it should finish and we should see `status=success`\n",
    "await client.runs.get(thread[\"thread_id\"], run[\"run_id\"])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "id": "8de4495f-7873-487c-b1a8-ad2a78a1ff35",
   "metadata": {},
   "outputs": [],
   "source": [
    "# We can get the final results\n",
    "final_result = await client.threads.get_state(thread[\"thread_id\"])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "id": "9da76fce-66e4-4f1b-8c24-09759889e50e",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'values': {'messages': [{'content': 'what's the weather in sf',\n",
       "    'additional_kwargs': {},\n",
       "    'response_metadata': {},\n",
       "    'type': 'human',\n",
       "    'name': None,\n",
       "    'id': 'bfe07fff-cb40-40be-84d5-a061d2c40006',\n",
       "    'example': False},\n",
       "   {'content': [{'id': 'toolu_01QUzhhfDQkpbPSediUrXvQb',\n",
       "      'input': {'query': 'weather in san francisco'},\n",
       "      'name': 'tavily_search_results_json',\n",
       "      'type': 'tool_use'}],\n",
       "    'additional_kwargs': {},\n",
       "    'response_metadata': {},\n",
       "    'type': 'ai',\n",
       "    'name': None,\n",
       "    'id': 'run-6d8665ca-a77d-4b44-9a7b-4e975b155fb1',\n",
       "    'example': False,\n",
       "    'tool_calls': [{'name': 'tavily_search_results_json',\n",
       "      'args': {'query': 'weather in san francisco'},\n",
       "      'id': 'toolu_01QUzhhfDQkpbPSediUrXvQb'}],\n",
       "    'invalid_tool_calls': [],\n",
       "    'usage_metadata': None},\n",
       "   {'content': '[{\"url\": \"https://www.timeanddate.com/weather/usa/san-francisco/historic\", \"content\": \"San Francisco Weather History for the Previous 24 Hours Show weather for: Previous 24 hours June 17, 2024 June 16, 2024 June 15, 2024 June 14, 2024 June 13, 2024 June 12, 2024 June 11, 2024 June 10, 2024 June 9, 2024 June 8, 2024 June 7, 2024 June 6, 2024 June 5, 2024 June 4, 2024 June 3, 2024 June 2, 2024\"}]',\n",
       "    'additional_kwargs': {},\n",
       "    'response_metadata': {},\n",
       "    'type': 'tool',\n",
       "    'name': 'tavily_search_results_json',\n",
       "    'id': '257a1f29-2f66-4f9e-b35d-c8818dbbaa3f',\n",
       "    'tool_call_id': 'toolu_01QUzhhfDQkpbPSediUrXvQb'},\n",
       "   {'content': [{'text': 'The search results provide historic weather data for San Francisco, but do not give the current weather conditions. To get the current weather forecast for San Francisco, I would need to refine my search query. Here is an updated search:',\n",
       "      'type': 'text'},\n",
       "     {'id': 'toolu_01RLJEcWYRvRoBhiHdrhoRZx',\n",
       "      'input': {'query': 'san francisco weather forecast today'},\n",
       "      'name': 'tavily_search_results_json',\n",
       "      'type': 'tool_use'}],\n",
       "    'additional_kwargs': {},\n",
       "    'response_metadata': {},\n",
       "    'type': 'ai',\n",
       "    'name': None,\n",
       "    'id': 'run-ca41dbf8-7e89-4ff2-a245-87098d7928ba',\n",
       "    'example': False,\n",
       "    'tool_calls': [{'name': 'tavily_search_results_json',\n",
       "      'args': {'query': 'san francisco weather forecast today'},\n",
       "      'id': 'toolu_01RLJEcWYRvRoBhiHdrhoRZx'}],\n",
       "    'invalid_tool_calls': [],\n",
       "    'usage_metadata': None},\n",
       "   {'content': '[{\"url\": \"https://www.weatherapi.com/\", \"content\": \"{\\'location\\': {\\'name\\': \\'San Francisco\\', \\'region\\': \\'California\\', \\'country\\': \\'United States of America\\', \\'lat\\': 37.78, \\'lon\\': -122.42, \\'tz_id\\': \\'America/Los_Angeles\\', \\'localtime_epoch\\': 1718981382, \\'localtime\\': \\'2024-06-21 7:49\\'}, \\'current\\': {\\'last_updated_epoch\\': 1718981100, \\'last_updated\\': \\'2024-06-21 07:45\\', \\'temp_c\\': 12.8, \\'temp_f\\': 55.0, \\'is_day\\': 1, \\'condition\\': {\\'text\\': \\'Overcast\\', \\'icon\\': \\'//cdn.weatherapi.com/weather/64x64/day/122.png\\', \\'code\\': 1009}, \\'wind_mph\\': 6.9, \\'wind_kph\\': 11.2, \\'wind_degree\\': 200, \\'wind_dir\\': \\'SSW\\', \\'pressure_mb\\': 1011.0, \\'pressure_in\\': 29.84, \\'precip_mm\\': 0.01, \\'precip_in\\': 0.0, \\'humidity\\': 86, \\'cloud\\': 100, \\'feelslike_c\\': 12.2, \\'feelslike_f\\': 53.9, \\'windchill_c\\': 11.2, \\'windchill_f\\': 52.1, \\'heatindex_c\\': 12.0, \\'heatindex_f\\': 53.5, \\'dewpoint_c\\': 9.4, \\'dewpoint_f\\': 48.8, \\'vis_km\\': 16.0, \\'vis_miles\\': 9.0, \\'uv\\': 3.0, \\'gust_mph\\': 7.6, \\'gust_kph\\': 12.2}}\"}]',\n",
       "    'additional_kwargs': {},\n",
       "    'response_metadata': {},\n",
       "    'type': 'tool',\n",
       "    'name': 'tavily_search_results_json',\n",
       "    'id': 'c80a3720-6a9f-4ff0-9ce2-6112e66a6f81',\n",
       "    'tool_call_id': 'toolu_01RLJEcWYRvRoBhiHdrhoRZx'},\n",
       "   {'content': 'The updated search provides the current weather forecast for San Francisco. According to the results, as of 7:49am on June 21, 2024 in San Francisco, the temperature is 55°F (12.8°C), it is overcast with 100% cloud cover, and there are light winds from the south-southwest around 7 mph (11 km/h). The forecast also shows low precipitation of 0.01 mm, high humidity of 86%, and visibility of 9 miles (16 km).\\n\\nIn summary, the current weather in San Francisco is cool, overcast, and breezy based on this weather forecast data. Let me know if you need any other details!',\n",
       "    'additional_kwargs': {},\n",
       "    'response_metadata': {},\n",
       "    'type': 'ai',\n",
       "    'name': None,\n",
       "    'id': 'run-4f23b53d-a8ec-4038-b3ed-08b2560bf81c',\n",
       "    'example': False,\n",
       "    'tool_calls': [],\n",
       "    'invalid_tool_calls': [],\n",
       "    'usage_metadata': None}]},\n",
       " 'next': [],\n",
       " 'config': {'configurable': {'thread_id': '5fc20631-47b7-48cd-8aa2-9f2eace9778d',\n",
       "   'thread_ts': '1ef2fdea-f879-65a5-8005-443b6a4039aa'}},\n",
       " 'metadata': {'step': 5,\n",
       "  'run_id': '1ef2fdea-814c-6165-8b2a-a40e2a028198',\n",
       "  'source': 'loop',\n",
       "  'writes': {'agent': {'messages': [{'id': 'run-4f23b53d-a8ec-4038-b3ed-08b2560bf81c',\n",
       "      'name': None,\n",
       "      'type': 'ai',\n",
       "      'content': 'The updated search provides the current weather forecast for San Francisco. According to the results, as of 7:49am on June 21, 2024 in San Francisco, the temperature is 55°F (12.8°C), it is overcast with 100% cloud cover, and there are light winds from the south-southwest around 7 mph (11 km/h). The forecast also shows low precipitation of 0.01 mm, high humidity of 86%, and visibility of 9 miles (16 km).\\n\\nIn summary, the current weather in San Francisco is cool, overcast, and breezy based on this weather forecast data. Let me know if you need any other details!',\n",
       "      'example': False,\n",
       "      'tool_calls': [],\n",
       "      'usage_metadata': None,\n",
       "      'additional_kwargs': {},\n",
       "      'response_metadata': {},\n",
       "      'invalid_tool_calls': []}]}},\n",
       "  'user_id': '',\n",
       "  'graph_id': 'agent',\n",
       "  'thread_id': '5fc20631-47b7-48cd-8aa2-9f2eace9778d',\n",
       "  'created_by': 'system',\n",
       "  'assistant_id': 'fe096781-5601-53d2-b2f6-0d3403f7e9ca'},\n",
       " 'created_at': '2024-06-21T14:58:14.591805+00:00',\n",
       " 'parent_config': {'configurable': {'thread_id': '5fc20631-47b7-48cd-8aa2-9f2eace9778d',\n",
       "   'thread_ts': '1ef2fdea-d44c-6fc4-8004-d2713436777d'}}}"
      ]
     },
     "execution_count": 11,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "final_result"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "id": "ddd6e698-4609-4389-b84a-bb8939fff08b",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'The updated search provides the current weather forecast for San Francisco. According to the results, as of 7:49am on June 21, 2024 in San Francisco, the temperature is 55°F (12.8°C), it is overcast with 100% cloud cover, and there are light winds from the south-southwest around 7 mph (11 km/h). The forecast also shows low precipitation of 0.01 mm, high humidity of 86%, and visibility of 9 miles (16 km).\\n\\nIn summary, the current weather in San Francisco is cool, overcast, and breezy based on this weather forecast data. Let me know if you need any other details!'"
      ]
     },
     "execution_count": 12,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# We can get the content of the final message\n",
    "final_result[\"values\"][\"messages\"][-1][\"content\"]"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "langgraph-example-dev",
   "language": "python",
   "name": "langgraph-example-dev"
  },
  "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": 5
}
