{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "f6574496-b360-4ffa-9523-7fd34a590164",
   "metadata": {},
   "source": [
    "# Async API\n",
    "\n",
    "All `LLM`s implement the `Runnable` interface, which comes with default implementations of all methods, ie. ainvoke, batch, abatch, stream, astream. This gives all `LLM`s basic support for asynchronous calls.\n",
    "\n",
    "Async support defaults to calling the `LLM`'s respective sync method in asyncio's default thread pool executor. This lets other async functions in your application make progress while the `LLM` is being executed, by moving this call to a background thread. Where `LLM`s providers have native implementations for async, that is used instead of the default `LLM` implementation.\n",
    "\n",
    "See which [integrations provide native async support here](/docs/integrations/llms/).\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "5e49e96c-0f88-466d-b3d3-ea0966bdf19e",
   "metadata": {
    "tags": []
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\u001b[1mConcurrent executed in 1.03 seconds.\u001b[0m\n",
      "\u001b[1mSerial executed in 6.80 seconds.\u001b[0m\n"
     ]
    }
   ],
   "source": [
    "import asyncio\n",
    "import time\n",
    "\n",
    "from langchain.llms import OpenAI\n",
    "\n",
    "llm = OpenAI(model=\"gpt-3.5-turbo-instruct\", temperature=0.9)\n",
    "\n",
    "\n",
    "def invoke_serially():\n",
    "    for _ in range(10):\n",
    "        resp = llm.invoke(\"Hello, how are you?\")\n",
    "\n",
    "\n",
    "async def async_invoke(llm):\n",
    "    resp = await llm.ainvoke(\"Hello, how are you?\")\n",
    "\n",
    "\n",
    "async def invoke_concurrently():\n",
    "    tasks = [async_invoke(llm) for _ in range(10)]\n",
    "    await asyncio.gather(*tasks)\n",
    "\n",
    "\n",
    "s = time.perf_counter()\n",
    "# If running this outside of Jupyter, use asyncio.run(generate_concurrently())\n",
    "await invoke_concurrently()\n",
    "elapsed = time.perf_counter() - s\n",
    "print(\"\\033[1m\" + f\"Concurrent executed in {elapsed:0.2f} seconds.\" + \"\\033[0m\")\n",
    "\n",
    "s = time.perf_counter()\n",
    "invoke_serially()\n",
    "elapsed = time.perf_counter() - s\n",
    "print(\"\\033[1m\" + f\"Serial executed in {elapsed:0.2f} seconds.\" + \"\\033[0m\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "e0b60caf-f99e-46a6-bdad-46b2cfea29ac",
   "metadata": {},
   "source": [
    "To simplify things we could also just use `abatch` to run a batch concurrently:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "bd11000f-2232-491a-9f70-abcbb4611fbf",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\u001b[1mBatch executed in 1.31 seconds.\u001b[0m\n"
     ]
    }
   ],
   "source": [
    "s = time.perf_counter()\n",
    "# If running this outside of Jupyter, use asyncio.run(generate_concurrently())\n",
    "await llm.abatch([\"Hello, how are you?\"] * 10)\n",
    "elapsed = time.perf_counter() - s\n",
    "print(\"\\033[1m\" + f\"Batch executed in {elapsed:0.2f} seconds.\" + \"\\033[0m\")"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "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.9.1"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
