langchain-nvidia-ai-endpoints 0.0.1__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2023 LangChain, Inc.
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,374 @@
1
+ Metadata-Version: 2.1
2
+ Name: langchain-nvidia-ai-endpoints
3
+ Version: 0.0.1
4
+ Summary: An integration package connecting NVIDIA AI Endpoints and LangChain
5
+ Home-page: https://github.com/langchain-ai/langchain/tree/master/libs/partners/nvidia-ai-endpoints
6
+ Requires-Python: >=3.8.1,<4.0
7
+ Classifier: Programming Language :: Python :: 3
8
+ Classifier: Programming Language :: Python :: 3.9
9
+ Classifier: Programming Language :: Python :: 3.10
10
+ Classifier: Programming Language :: Python :: 3.11
11
+ Requires-Dist: aiohttp (>=3.9.1,<4.0.0)
12
+ Requires-Dist: langchain-core (>=0.1.0,<0.2.0)
13
+ Project-URL: Repository, https://github.com/langchain-ai/langchain/tree/master/libs/partners/nvidia-ai-endpoints
14
+ Description-Content-Type: text/markdown
15
+
16
+ # langchain-nvidia-ai-endpoints
17
+
18
+ The `langchain-nvidia-ai-endpoints` package contains LangChain integrations for chat models and embeddings powered by the [NVIDIA AI Foundation Model](https://www.nvidia.com/en-us/ai-data-science/foundation-models/) playground environment.
19
+
20
+ > [NVIDIA AI Foundation Endpoints](https://www.nvidia.com/en-us/ai-data-science/foundation-models/) give users easy access to hosted endpoints for generative AI models like Llama-2, SteerLM, Mistral, etc. Using the API, you can query live endpoints available on the [NVIDIA GPU Cloud (NGC)](https://catalog.ngc.nvidia.com/ai-foundation-models) to get quick results from a DGX-hosted cloud compute environment. All models are source-accessible and can be deployed on your own compute cluster.
21
+
22
+ Below is an example on how to use some common functionality surrounding text-generative and embedding models
23
+
24
+ ## Installation
25
+
26
+
27
+ ```python
28
+ %pip install -U --quiet langchain-nvidia-ai-endpoints
29
+ ```
30
+
31
+ ## Setup
32
+
33
+ **To get started:**
34
+ 1. Create a free account with the [NVIDIA GPU Cloud](https://catalog.ngc.nvidia.com/) service, which hosts AI solution catalogs, containers, models, etc.
35
+ 2. Navigate to `Catalog > AI Foundation Models > (Model with API endpoint)`.
36
+ 3. Select the `API` option and click `Generate Key`.
37
+ 4. Save the generated key as `NVIDIA_API_KEY`. From there, you should have access to the endpoints.
38
+
39
+
40
+ ```python
41
+ import getpass
42
+ import os
43
+
44
+ if not os.environ.get("NVIDIA_API_KEY", "").startswith("nvapi-"):
45
+ nvidia_api_key = getpass.getpass("Enter your NVIDIA AIPLAY API key: ")
46
+ assert nvidia_api_key.startswith("nvapi-"), f"{nvidia_api_key[:5]}... is not a valid key"
47
+ os.environ["NVIDIA_API_KEY"] = nvidia_api_key
48
+ ```
49
+
50
+
51
+ ```python
52
+ ## Core LC Chat Interface
53
+ from langchain_nvidia_ai_endpoints import ChatNVIDIA
54
+
55
+ llm = ChatNVIDIA(model="mixtral_8x7b")
56
+ result = llm.invoke("Write a ballad about LangChain.")
57
+ print(result.content)
58
+ ```
59
+
60
+
61
+ ## Stream, Batch, and Async
62
+
63
+ These models natively support streaming, and as is the case with all LangChain LLMs they expose a batch method to handle concurrent requests, as well as async methods for invoke, stream, and batch. Below are a few examples.
64
+
65
+
66
+ ```python
67
+ print(llm.batch(["What's 2*3?", "What's 2*6?"]))
68
+ # Or via the async API
69
+ # await llm.abatch(["What's 2*3?", "What's 2*6?"])
70
+ ```
71
+
72
+
73
+ ```python
74
+ for chunk in llm.stream("How far can a seagull fly in one day?"):
75
+ # Show the token separations
76
+ print(chunk.content, end="|")
77
+ ```
78
+
79
+
80
+ ```python
81
+ async for chunk in llm.astream("How long does it take for monarch butterflies to migrate?"):
82
+ print(chunk.content, end="|")
83
+ ```
84
+
85
+ ## Supported models
86
+
87
+ Querying `available_models` will still give you all of the other models offered by your API credentials.
88
+
89
+ The `playground_` prefix is optional.
90
+
91
+
92
+ ```python
93
+ list(llm.available_models)
94
+
95
+
96
+ # ['playground_llama2_13b',
97
+ # 'playground_llama2_code_13b',
98
+ # 'playground_clip',
99
+ # 'playground_fuyu_8b',
100
+ # 'playground_mistral_7b',
101
+ # 'playground_nvolveqa_40k',
102
+ # 'playground_yi_34b',
103
+ # 'playground_nemotron_steerlm_8b',
104
+ # 'playground_nv_llama2_rlhf_70b',
105
+ # 'playground_llama2_code_34b',
106
+ # 'playground_mixtral_8x7b',
107
+ # 'playground_neva_22b',
108
+ # 'playground_steerlm_llama_70b',
109
+ # 'playground_nemotron_qa_8b',
110
+ # 'playground_sdxl']
111
+ ```
112
+
113
+
114
+ ## Model types
115
+
116
+ All of these models above are supported and can be accessed via `ChatNVIDIA`.
117
+
118
+ Some model types support unique prompting techniques and chat messages. We will review a few important ones below.
119
+
120
+
121
+ **To find out more about a specific model, please navigate to the API section of an AI Foundation Model [as linked here](https://catalog.ngc.nvidia.com/orgs/nvidia/teams/ai-foundation/models/codellama-13b/api).**
122
+
123
+ ### General Chat
124
+
125
+ Models such as `llama2_13b` and `mixtral_8x7b` are good all-around models that you can use for with any LangChain chat messages. Example below.
126
+
127
+
128
+ ```python
129
+ from langchain_nvidia_ai_endpoints import ChatNVIDIA
130
+ from langchain_core.prompts import ChatPromptTemplate
131
+ from langchain_core.output_parsers import StrOutputParser
132
+
133
+ prompt = ChatPromptTemplate.from_messages(
134
+ [
135
+ ("system", "You are a helpful AI assistant named Fred."),
136
+ ("user", "{input}")
137
+ ]
138
+ )
139
+ chain = (
140
+ prompt
141
+ | ChatNVIDIA(model="llama2_13b")
142
+ | StrOutputParser()
143
+ )
144
+
145
+ for txt in chain.stream({"input": "What's your name?"}):
146
+ print(txt, end="")
147
+ ```
148
+
149
+
150
+ ### Code Generation
151
+
152
+ These models accept the same arguments and input structure as regular chat models, but they tend to perform better on code-genreation and structured code tasks. An example of this is `llama2_code_13b`.
153
+
154
+
155
+ ```python
156
+ prompt = ChatPromptTemplate.from_messages(
157
+ [
158
+ ("system", "You are an expert coding AI. Respond only in valid python; no narration whatsoever."),
159
+ ("user", "{input}")
160
+ ]
161
+ )
162
+ chain = (
163
+ prompt
164
+ | ChatNVIDIA(model="llama2_code_13b")
165
+ | StrOutputParser()
166
+ )
167
+
168
+ for txt in chain.stream({"input": "How do I solve this fizz buzz problem?"}):
169
+ print(txt, end="")
170
+ ```
171
+
172
+ ## Steering LLMs
173
+
174
+ > [SteerLM-optimized models](https://developer.nvidia.com/blog/announcing-steerlm-a-simple-and-practical-technique-to-customize-llms-during-inference/) supports "dynamic steering" of model outputs at inference time.
175
+
176
+ This lets you "control" the complexity, verbosity, and creativity of the model via integer labels on a scale from 0 to 9. Under the hood, these are passed as a special type of assistant message to the model.
177
+
178
+ The "steer" models support this type of input, such as `steerlm_llama_70b`
179
+
180
+
181
+ ```python
182
+ from langchain_nvidia_ai_endpoints import ChatNVIDIA
183
+
184
+ llm = ChatNVIDIA(model="steerlm_llama_70b")
185
+ # Try making it uncreative and not verbose
186
+ complex_result = llm.invoke(
187
+ "What's a PB&J?",
188
+ labels={"creativity": 0, "complexity": 3, "verbosity": 0}
189
+ )
190
+ print("Un-creative\n")
191
+ print(complex_result.content)
192
+
193
+ # Try making it very creative and verbose
194
+ print("\n\nCreative\n")
195
+ creative_result = llm.invoke(
196
+ "What's a PB&J?",
197
+ labels={"creativity": 9, "complexity": 3, "verbosity": 9}
198
+ )
199
+ print(creative_result.content)
200
+ ```
201
+
202
+
203
+ #### Use within LCEL
204
+
205
+ The labels are passed as invocation params. You can `bind` these to the LLM using the `bind` method on the LLM to include it within a declarative, functional chain. Below is an example.
206
+
207
+
208
+ ```python
209
+ from langchain_nvidia_ai_endpoints import ChatNVIDIA
210
+ from langchain_core.prompts import ChatPromptTemplate
211
+ from langchain_core.output_parsers import StrOutputParser
212
+
213
+ prompt = ChatPromptTemplate.from_messages(
214
+ [
215
+ ("system", "You are a helpful AI assistant named Fred."),
216
+ ("user", "{input}")
217
+ ]
218
+ )
219
+ chain = (
220
+ prompt
221
+ | ChatNVIDIA(model="steerlm_llama_70b").bind(labels={"creativity": 9, "complexity": 0, "verbosity": 9})
222
+ | StrOutputParser()
223
+ )
224
+
225
+ for txt in chain.stream({"input": "Why is a PB&J?"}):
226
+ print(txt, end="")
227
+ ```
228
+
229
+ ## Multimodal
230
+
231
+ NVIDIA also supports multimodal inputs, meaning you can provide both images and text for the model to reason over.
232
+
233
+ These models also accept `labels`, similar to the Steering LLMs above. In addition to `creativity`, `complexity`, and `verbosity`, these models support a `quality` toggle.
234
+
235
+ An example model supporting multimodal inputs is `playground_neva_22b`.
236
+
237
+ These models accept LangChain's standard image formats. Below are examples.
238
+
239
+
240
+ ```python
241
+ import requests
242
+
243
+ image_url = "https://picsum.photos/seed/kitten/300/200"
244
+ image_content = requests.get(image_url).content
245
+ ```
246
+
247
+ Initialize the model like so:
248
+
249
+ ```python
250
+ from langchain_nvidia_ai_endpoints import ChatNVIDIA
251
+
252
+ llm = ChatNVIDIA(model="playground_neva_22b")
253
+ ```
254
+
255
+ #### Passing an image as a URL
256
+
257
+
258
+ ```python
259
+ from langchain_core.messages import HumanMessage
260
+
261
+ llm.invoke(
262
+ [
263
+ HumanMessage(content=[
264
+ {"type": "text", "text": "Describe this image:"},
265
+ {"type": "image_url", "image_url": {"url": image_url}},
266
+ ])
267
+ ])
268
+ ```
269
+
270
+
271
+ ```python
272
+ ### You can specify the labels for steering here as well. You can try setting a low verbosity, for instance
273
+
274
+ from langchain_core.messages import HumanMessage
275
+
276
+ llm.invoke(
277
+ [
278
+ HumanMessage(content=[
279
+ {"type": "text", "text": "Describe this image:"},
280
+ {"type": "image_url", "image_url": {"url": image_url}},
281
+ ])
282
+ ],
283
+ labels={
284
+ "creativity": 0,
285
+ "quality": 9,
286
+ "complexity": 0,
287
+ "verbosity": 0
288
+ }
289
+ )
290
+ ```
291
+
292
+
293
+
294
+ #### Passing an image as a base64 encoded string
295
+
296
+
297
+ ```python
298
+ import base64
299
+ b64_string = base64.b64encode(image_content).decode('utf-8')
300
+ llm.invoke(
301
+ [
302
+ HumanMessage(content=[
303
+ {"type": "text", "text": "Describe this image:"},
304
+ {"type": "image_url", "image_url": {"url": f"data:image/png;base64,{b64_string}"}},
305
+ ])
306
+ ])
307
+ ```
308
+
309
+ #### Directly within the string
310
+
311
+ The NVIDIA API uniquely accepts images as base64 images inlined within <img> HTML tags. While this isn't interoperable with other LLMs, you can directly prompt the model accordingly.
312
+
313
+
314
+ ```python
315
+ base64_with_mime_type = f"data:image/png;base64,{b64_string}"
316
+ llm.invoke(
317
+ f'What\'s in this image?\n<img src="{base64_with_mime_type}" />'
318
+ )
319
+ ```
320
+
321
+
322
+
323
+ ## RAG: Context models
324
+
325
+ NVIDIA also has Q&A models that support a special "context" chat message containing retrieved context (such as documents within a RAG chain). This is useful to avoid prompt-injecting the model.
326
+
327
+ **Note:** Only "user" (human) and "context" chat messages are supported for these models, not system or AI messages useful in conversational flows.
328
+
329
+ The `_qa_` models like `nemotron_qa_8b` support this.
330
+
331
+
332
+ ```python
333
+ from langchain_nvidia_ai_endpoints import ChatNVIDIA
334
+ from langchain_core.prompts import ChatPromptTemplate
335
+ from langchain_core.output_parsers import StrOutputParser
336
+ from langchain_core.messages import ChatMessage
337
+ prompt = ChatPromptTemplate.from_messages(
338
+ [
339
+ ChatMessage(role="context", content="Parrots and Cats have signed the peace accord."),
340
+ ("user", "{input}")
341
+ ]
342
+ )
343
+ llm = ChatNVIDIA(model="nemotron_qa_8b")
344
+ chain = (
345
+ prompt
346
+ | llm
347
+ | StrOutputParser()
348
+ )
349
+ chain.invoke({"input": "What was signed?"})
350
+ ```
351
+
352
+ ## Embeddings
353
+
354
+ You can also connect to embeddings models through this package. Below is an example:
355
+
356
+ ```
357
+ from langchain_nvidia_ai_endpoints import NVIDIAEmbeddings
358
+
359
+ embedder = NVIDIAEmbeddings(model="nvolveqa_40k")
360
+ embedder.embed_query("What's the temperature today?")
361
+ embedder.embed_documents([
362
+ "The temperature is 42 degrees.",
363
+ "Class is dismissed at 9 PM."
364
+ ])
365
+ ```
366
+
367
+ By default the embedding model will use the "passage" type for documents and "query" type for queries, but you can fix this on the instance.
368
+
369
+ ```python
370
+ query_embedder = NVIDIAEmbeddings(model="nvolveqa_40k", model_type="query")
371
+ doc_embeddder = NVIDIAEmbeddings(model="nvolveqa_40k", model_type="passage")
372
+ ```
373
+
374
+