File size: 7,838 Bytes
cfd3735
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "6eaf7e66-f49c-42da-8d11-22ea13bef718",
   "metadata": {},
   "source": [
    "# How to stream LLM and Chat Model responses\n",
    "\n",
    "LangChain provides streaming support for LLMs. Currently, we support streaming for the `OpenAI`, `ChatOpenAI`, and `ChatAnthropic` implementations, but streaming support for other LLM implementations is on the roadmap. To utilize streaming, use a [`CallbackHandler`](https://github.com/hwchase17/langchain/blob/master/langchain/callbacks/base.py) that implements `on_llm_new_token`. In this example, we are using [`StreamingStdOutCallbackHandler`]()."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "4ac0ff54-540a-4f2b-8d9a-b590fec7fe07",
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "from langchain.llms import OpenAI\n",
    "from langchain.chat_models import ChatOpenAI, ChatAnthropic\n",
    "from langchain.callbacks.streaming_stdout import StreamingStdOutCallbackHandler\n",
    "from langchain.schema import HumanMessage"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "77f60a4b-f786-41f2-972e-e5bb8a48dcd5",
   "metadata": {
    "tags": []
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "\n",
      "Verse 1\n",
      "I'm sippin' on sparkling water,\n",
      "It's so refreshing and light,\n",
      "It's the perfect way to quench my thirst\n",
      "On a hot summer night.\n",
      "\n",
      "Chorus\n",
      "Sparkling water, sparkling water,\n",
      "It's the best way to stay hydrated,\n",
      "It's so crisp and so clean,\n",
      "It's the perfect way to stay refreshed.\n",
      "\n",
      "Verse 2\n",
      "I'm sippin' on sparkling water,\n",
      "It's so bubbly and bright,\n",
      "It's the perfect way to cool me down\n",
      "On a hot summer night.\n",
      "\n",
      "Chorus\n",
      "Sparkling water, sparkling water,\n",
      "It's the best way to stay hydrated,\n",
      "It's so crisp and so clean,\n",
      "It's the perfect way to stay refreshed.\n",
      "\n",
      "Verse 3\n",
      "I'm sippin' on sparkling water,\n",
      "It's so light and so clear,\n",
      "It's the perfect way to keep me cool\n",
      "On a hot summer night.\n",
      "\n",
      "Chorus\n",
      "Sparkling water, sparkling water,\n",
      "It's the best way to stay hydrated,\n",
      "It's so crisp and so clean,\n",
      "It's the perfect way to stay refreshed."
     ]
    }
   ],
   "source": [
    "llm = OpenAI(streaming=True, callbacks=[StreamingStdOutCallbackHandler()], temperature=0)\n",
    "resp = llm(\"Write me a song about sparkling water.\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "61fb6de7-c6c8-48d0-a48e-1204c027a23c",
   "metadata": {
    "tags": []
   },
   "source": [
    "We still have access to the end `LLMResult` if using `generate`. However, `token_usage` is not currently supported for streaming."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "a35373f1-9ee6-4753-a343-5aee749b8527",
   "metadata": {
    "tags": []
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "\n",
      "Q: What did the fish say when it hit the wall?\n",
      "A: Dam!"
     ]
    },
    {
     "data": {
      "text/plain": [
       "LLMResult(generations=[[Generation(text='\\n\\nQ: What did the fish say when it hit the wall?\\nA: Dam!', generation_info={'finish_reason': 'stop', 'logprobs': None})]], llm_output={'token_usage': {}, 'model_name': 'text-davinci-003'})"
      ]
     },
     "execution_count": 3,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "llm.generate([\"Tell me a joke.\"])"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "a93a4d61-0476-49db-8321-7de92bd74059",
   "metadata": {},
   "source": [
    "Here's an example with the `ChatOpenAI` chat model implementation:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "22665f16-e05b-473c-a4bd-ad75744ea024",
   "metadata": {
    "tags": []
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Verse 1:\n",
      "Bubbles rising to the top\n",
      "A refreshing drink that never stops\n",
      "Clear and crisp, it's oh so pure\n",
      "Sparkling water, I can't ignore\n",
      "\n",
      "Chorus:\n",
      "Sparkling water, oh how you shine\n",
      "A taste so clean, it's simply divine\n",
      "You quench my thirst, you make me feel alive\n",
      "Sparkling water, you're my favorite vibe\n",
      "\n",
      "Verse 2:\n",
      "No sugar, no calories, just H2O\n",
      "A drink that's good for me, don't you know\n",
      "With lemon or lime, you're even better\n",
      "Sparkling water, you're my forever\n",
      "\n",
      "Chorus:\n",
      "Sparkling water, oh how you shine\n",
      "A taste so clean, it's simply divine\n",
      "You quench my thirst, you make me feel alive\n",
      "Sparkling water, you're my favorite vibe\n",
      "\n",
      "Bridge:\n",
      "You're my go-to drink, day or night\n",
      "You make me feel so light\n",
      "I'll never give you up, you're my true love\n",
      "Sparkling water, you're sent from above\n",
      "\n",
      "Chorus:\n",
      "Sparkling water, oh how you shine\n",
      "A taste so clean, it's simply divine\n",
      "You quench my thirst, you make me feel alive\n",
      "Sparkling water, you're my favorite vibe\n",
      "\n",
      "Outro:\n",
      "Sparkling water, you're the one for me\n",
      "I'll never let you go, can't you see\n",
      "You're my drink of choice, forevermore\n",
      "Sparkling water, I adore."
     ]
    }
   ],
   "source": [
    "chat = ChatOpenAI(streaming=True, callbacks=[StreamingStdOutCallbackHandler()], temperature=0)\n",
    "resp = chat([HumanMessage(content=\"Write me a song about sparkling water.\")])"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "909ae48b-0f07-4990-bbff-e627f706c93e",
   "metadata": {},
   "source": [
    "Here is an example with the `ChatAnthropic` chat model implementation, which uses their `claude` model."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "eadae4ba-9f21-4ec8-845d-dd43b0edc2dc",
   "metadata": {
    "tags": []
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      " Here is my attempt at a song about sparkling water:\n",
      "\n",
      "Sparkling water, bubbles so bright, \n",
      "Dancing in the glass with delight.\n",
      "Refreshing and crisp, a fizzy delight,\n",
      "Quenching my thirst with each sip I take.\n",
      "The carbonation tickles my tongue,\n",
      "As the refreshing water song is sung.\n",
      "Lime or lemon, a citrus twist,\n",
      "Makes sparkling water such a bliss.\n",
      "Healthy and hydrating, a drink so pure,\n",
      "Sparkling water, always alluring.\n",
      "Bubbles ascending in a stream, \n",
      "Sparkling water, you're my dream!"
     ]
    }
   ],
   "source": [
    "chat = ChatAnthropic(streaming=True, callbacks=[StreamingStdOutCallbackHandler()], temperature=0)\n",
    "resp = chat([HumanMessage(content=\"Write me a song about sparkling water.\")])"
   ]
  }
 ],
 "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.10.9"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}