Skip to content

Commit d6ef5fe

Browse files
NutlopeErick Friis
andauthored
together: add chat models, use openai base (#21337)
**Description:** Adding chat completions to the Together AI package, which is our most popular API. Also staying backwards compatible with the old API so folks can continue to use the completions API as well. Also moved the embedding API to use the OpenAI library to standardize it further. **Twitter handle:** @Nutlope - [x] **Add tests and docs**: If you're adding a new integration, please include - [x] **Lint and test**: Run `make format`, `make lint` and `make test` from the root of the package(s) you've modified. See contribution guidelines for more: https://python.langchain.com/docs/contributing/ If no one reviews your PR within a few days, please @-mention one of baskaryan, efriis, eyurtsev, hwchase17. --------- Co-authored-by: Erick Friis <erick@langchain.dev>
1 parent a2d3130 commit d6ef5fe

22 files changed

Lines changed: 1494 additions & 466 deletions

docs/docs/integrations/llms/together.ipynb

Lines changed: 37 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -7,15 +7,21 @@
77
"source": [
88
"# Together AI\n",
99
"\n",
10-
"> The Together API makes it easy to fine-tune or run leading open-source models with a couple lines of code. We have integrated the world’s leading open-source models, including Llama-2, RedPajama, Falcon, Alpaca, Stable Diffusion XL, and more. Read more: https://together.ai\n",
10+
"> The Together API makes it easy to query and fine-tune leading open-source models with a couple lines of code. We have integrated the world’s leading open-source models, including Llama-3, Mixtral, DBRX, Stable Diffusion XL, and more. Read more: https://together.ai\n",
1111
"\n",
1212
"To use, you'll need an API key which you can find here:\n",
13-
"https://api.together.xyz/settings/api-keys. This can be passed in as init param\n",
13+
"https://api.together.ai/settings/api-keys. This can be passed in as init param\n",
1414
"``together_api_key`` or set as environment variable ``TOGETHER_API_KEY``.\n",
1515
"\n",
16-
"Together API reference: https://docs.together.ai/reference"
16+
"Together API reference: https://docs.together.ai"
1717
]
1818
},
19+
{
20+
"cell_type": "markdown",
21+
"id": "1c47fc36",
22+
"metadata": {},
23+
"source": []
24+
},
1925
{
2026
"cell_type": "code",
2127
"execution_count": null,
@@ -28,40 +34,43 @@
2834
},
2935
{
3036
"cell_type": "code",
31-
"execution_count": 3,
37+
"execution_count": null,
38+
"id": "637bb53f",
39+
"metadata": {},
40+
"outputs": [],
41+
"source": [
42+
"# Running chat completions with Together AI\n",
43+
"\n",
44+
"from langchain_core.prompts import ChatPromptTemplate\n",
45+
"from langchain_together import ChatTogether\n",
46+
"\n",
47+
"chat = ChatTogether()\n",
48+
"\n",
49+
"# using chat invoke\n",
50+
"chat.invoke(\"Tell me fun things to do in NYC\")\n",
51+
"\n",
52+
"# using chat stream\n",
53+
"for m in chat.stream(\"Tell me fun things to do in NYC\"):\n",
54+
" print(m)"
55+
]
56+
},
57+
{
58+
"cell_type": "code",
59+
"execution_count": null,
3260
"id": "e7b7170d-d7c5-4890-9714-a37238343805",
3361
"metadata": {},
34-
"outputs": [
35-
{
36-
"name": "stdout",
37-
"output_type": "stream",
38-
"text": [
39-
"\n",
40-
"\n",
41-
"A: A large language model is a neural network that is trained on a large amount of text data. It is able to generate text that is similar to the training data, and can be used for tasks such as language translation, question answering, and text summarization.\n",
42-
"\n",
43-
"A: A large language model is a neural network that is trained on a large amount of text data. It is able to generate text that is similar to the training data, and can be used for tasks such as language translation, question answering, and text summarization.\n",
44-
"\n",
45-
"A: A large language model is a neural network that is trained on\n"
46-
]
47-
}
48-
],
62+
"outputs": [],
4963
"source": [
64+
"# Running completions with Together AI\n",
65+
"\n",
5066
"from langchain_together import Together\n",
5167
"\n",
5268
"llm = Together(\n",
53-
" model=\"togethercomputer/RedPajama-INCITE-7B-Base\",\n",
54-
" temperature=0.7,\n",
55-
" max_tokens=128,\n",
56-
" top_k=1,\n",
69+
" model=\"codellama/CodeLlama-70b-Python-hf\",\n",
5770
" # together_api_key=\"...\"\n",
5871
")\n",
5972
"\n",
60-
"input_ = \"\"\"You are a teacher with a deep knowledge of machine learning and AI. \\\n",
61-
"You provide succinct and accurate answers. Answer the following question: \n",
62-
"\n",
63-
"What is a large language model?\"\"\"\n",
64-
"print(llm.invoke(input_))"
73+
"print(llm.invoke(\"def bubble_sort(): \"))"
6574
]
6675
}
6776
],

libs/partners/together/LICENSE

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
MIT License
22

3-
Copyright (c) 2023 LangChain, Inc.
3+
Copyright (c) 2024 LangChain, Inc.
44

55
Permission is hereby granted, free of charge, to any person obtaining a copy
66
of this software and associated documentation files (the "Software"), to deal

libs/partners/together/Makefile

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,6 @@ integration_test integration_tests: TEST_FILE=tests/integration_tests/
1111
test tests integration_test integration_tests:
1212
poetry run pytest $(TEST_FILE)
1313

14-
1514
######################
1615
# LINTING AND FORMATTING
1716
######################

libs/partners/together/README.md

Lines changed: 14 additions & 34 deletions
Original file line numberDiff line numberDiff line change
@@ -1,48 +1,28 @@
11
# langchain-together
22

3-
This package contains the LangChain integration for Together's generative models.
3+
This package contains the LangChain integrations for [Together AI](https://www.together.ai/) through their [APIs](https://docs.together.ai/).
44

5-
## Installation
5+
## Installation and Setup
66

7-
```sh
7+
- Install the LangChain partner package
8+
9+
```bash
810
pip install -U langchain-together
911
```
1012

11-
## Embeddings
12-
13-
You can use Together's embedding models through `TogetherEmbeddings` class.
14-
15-
```py
16-
from langchain_together import TogetherEmbeddings
13+
- Get your Together AI api key from the [Together Dashboard](https://api.together.ai/settings/api-keys) and set it as an environment variable (`TOGETHER_API_KEY`)
1714

18-
embeddings = TogetherEmbeddings(
19-
model='togethercomputer/m2-bert-80M-8k-retrieval'
20-
)
21-
embeddings.embed_query("What is a large language model?")
22-
```
23-
24-
## LLMs
15+
## Chat Completions
2516

26-
You can use Together's generative AI models as Langchain LLMs:
17+
This package contains the `ChatTogether` class, which is the recommended way to interface with Together AI chat models.
2718

28-
```py
29-
from langchain_together import Together
30-
from langchain_core.prompts import PromptTemplate
19+
ADD USAGE EXAMPLE HERE.
20+
Can we add this in the langchain docs?
3121

32-
llm = Together(
33-
model="togethercomputer/RedPajama-INCITE-7B-Base",
34-
temperature=0.7,
35-
max_tokens=64,
36-
top_k=1,
37-
# together_api_key="..."
38-
)
22+
NEED to add image endpoint + completions endpoint as well
3923

40-
template = """Question: {question}
41-
Answer: """
42-
prompt = PromptTemplate.from_template(template)
24+
## Embeddings
4325

44-
chain = prompt | llm
26+
See a [usage example](https://python.langchain.com/docs/integrations/text_embedding/together/)
4527

46-
question = "Who was the president in the year Justin Beiber was born?"
47-
print(chain.invoke({"question": question}))
48-
```
28+
Use `togethercomputer/m2-bert-80M-8k-retrieval` as the default model for embeddings.
Lines changed: 2 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,5 @@
1+
from langchain_together.chat_models import ChatTogether
12
from langchain_together.embeddings import TogetherEmbeddings
23
from langchain_together.llms import Together
3-
from langchain_together.version import __version__
44

5-
__all__ = [
6-
"__version__",
7-
"Together",
8-
"TogetherEmbeddings",
9-
]
5+
__all__ = ["ChatTogether", "Together", "TogetherEmbeddings"]
Lines changed: 103 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,103 @@
1+
"""Wrapper around Together AI's Chat Completions API."""
2+
3+
import os
4+
from typing import (
5+
Any,
6+
Dict,
7+
List,
8+
Optional,
9+
)
10+
11+
import openai
12+
from langchain_core.pydantic_v1 import Field, SecretStr, root_validator
13+
from langchain_core.utils import (
14+
convert_to_secret_str,
15+
get_from_dict_or_env,
16+
)
17+
from langchain_openai.chat_models.base import BaseChatOpenAI
18+
19+
20+
class ChatTogether(BaseChatOpenAI):
21+
"""ChatTogether chat model.
22+
23+
To use, you should have the environment variable `TOGETHER_API_KEY`
24+
set with your API key or pass it as a named parameter to the constructor.
25+
26+
Example:
27+
.. code-block:: python
28+
29+
from langchain_together import ChatTogether
30+
31+
32+
model = ChatTogether()
33+
"""
34+
35+
@property
36+
def lc_secrets(self) -> Dict[str, str]:
37+
return {"together_api_key": "TOGETHER_API_KEY"}
38+
39+
@classmethod
40+
def get_lc_namespace(cls) -> List[str]:
41+
return ["langchain", "chat_models", "together"]
42+
43+
@property
44+
def lc_attributes(self) -> Dict[str, Any]:
45+
attributes: Dict[str, Any] = {}
46+
47+
if self.together_api_base:
48+
attributes["together_api_base"] = self.together_api_base
49+
50+
return attributes
51+
52+
@property
53+
def _llm_type(self) -> str:
54+
"""Return type of chat model."""
55+
return "together-chat"
56+
57+
model_name: str = Field(default="meta-llama/Llama-3-8b-chat-hf", alias="model")
58+
"""Model name to use."""
59+
together_api_key: Optional[SecretStr] = Field(default=None, alias="api_key")
60+
"""Automatically inferred from env are `TOGETHER_API_KEY` if not provided."""
61+
together_api_base: Optional[str] = Field(
62+
default="https://api.together.ai/v1/chat/completions", alias="base_url"
63+
)
64+
65+
@root_validator()
66+
def validate_environment(cls, values: Dict) -> Dict:
67+
"""Validate that api key and python package exists in environment."""
68+
if values["n"] < 1:
69+
raise ValueError("n must be at least 1.")
70+
if values["n"] > 1 and values["streaming"]:
71+
raise ValueError("n must be 1 when streaming.")
72+
73+
values["together_api_key"] = convert_to_secret_str(
74+
get_from_dict_or_env(values, "together_api_key", "TOGETHER_API_KEY")
75+
)
76+
values["together_api_base"] = values["together_api_base"] or os.getenv(
77+
"TOGETHER_API_BASE"
78+
)
79+
80+
client_params = {
81+
"api_key": (
82+
values["together_api_key"].get_secret_value()
83+
if values["together_api_key"]
84+
else None
85+
),
86+
"base_url": values["together_api_base"],
87+
"timeout": values["request_timeout"],
88+
"max_retries": values["max_retries"],
89+
"default_headers": values["default_headers"],
90+
"default_query": values["default_query"],
91+
}
92+
93+
if not values.get("client"):
94+
sync_specific = {"http_client": values["http_client"]}
95+
values["client"] = openai.OpenAI(
96+
**client_params, **sync_specific
97+
).chat.completions
98+
if not values.get("async_client"):
99+
async_specific = {"http_client": values["http_async_client"]}
100+
values["async_client"] = openai.AsyncOpenAI(
101+
**client_params, **async_specific
102+
).chat.completions
103+
return values

0 commit comments

Comments
 (0)