From 8b697ff0ee7ae24299ae332751c737298812ebe5 Mon Sep 17 00:00:00 2001 From: Jean-Louis Queguiner Date: Tue, 17 Oct 2023 02:08:04 +0200 Subject: [PATCH] feat(llm): add together.xyz as an LLM provider (#11892) - **Description:** added together.xyz as an LLM provider, - **Issues:** fix some linting issues - twitter handle @jilijeanlouis --------- Co-authored-by: Bagatur --- docs/docs/integrations/llms/together.ipynb | 79 +++++++ libs/langchain/langchain/llms/__init__.py | 9 + libs/langchain/langchain/llms/together.py | 206 ++++++++++++++++++ .../integration_tests/llms/test_together.py | 40 ++++ 4 files changed, 334 insertions(+) create mode 100644 docs/docs/integrations/llms/together.ipynb create mode 100644 libs/langchain/langchain/llms/together.py create mode 100644 libs/langchain/tests/integration_tests/llms/test_together.py diff --git a/docs/docs/integrations/llms/together.ipynb b/docs/docs/integrations/llms/together.ipynb new file mode 100644 index 0000000000..d6e89e4c1b --- /dev/null +++ b/docs/docs/integrations/llms/together.ipynb @@ -0,0 +1,79 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "id": "2970dd75-8ebf-4b51-8282-9b454b8f356d", + "metadata": {}, + "source": [ + "# Together AI\n", + "\n", + "> 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", + "\n", + "To use, you'll need an API key which you can find here:\n", + "https://api.together.xyz/settings/api-keys. This can be passed in as init param\n", + "``together_api_key`` or set as environment variable ``TOGETHER_API_KEY``.\n", + "\n", + "Together API reference: https://docs.together.ai/reference/inference" + ] + }, + { + "cell_type": "code", + "execution_count": 10, + "id": "e7b7170d-d7c5-4890-9714-a37238343805", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "\n", + "\n", + "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", + "\n", + "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", + "\n", + "A: A large language model is a neural network that is trained on\n" + ] + } + ], + "source": [ + "from langchain.llms import Together\n", + "\n", + "llm = Together(\n", + " model=\"togethercomputer/RedPajama-INCITE-7B-Base\",\n", + " temperature=0.7,\n", + " max_tokens=128,\n", + " top_k=1,\n", + " # together_api_key=\"...\"\n", + ")\n", + "\n", + "input_ = \"\"\"You are a teacher with a deep knowledge of machine learning and AI. \\\n", + "You provide succinct and accurate answers. Answer the following question: \n", + "\n", + "What is a large language model?\"\"\"\n", + "print(llm(input_))" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "poetry-venv", + "language": "python", + "name": "poetry-venv" + }, + "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 +} diff --git a/libs/langchain/langchain/llms/__init__.py b/libs/langchain/langchain/llms/__init__.py index b4d74f470a..835b7323da 100644 --- a/libs/langchain/langchain/llms/__init__.py +++ b/libs/langchain/langchain/llms/__init__.py @@ -432,6 +432,12 @@ def _import_titan_takeoff() -> Any: return TitanTakeoff +def _import_together() -> Any: + from langchain.llms.together import Together + + return Together + + def _import_tongyi() -> Any: from langchain.llms.tongyi import Tongyi @@ -611,6 +617,8 @@ def __getattr__(name: str) -> Any: return _import_textgen() elif name == "TitanTakeoff": return _import_titan_takeoff() + elif name == "Together": + return _import_together() elif name == "Tongyi": return _import_tongyi() elif name == "VertexAI": @@ -773,6 +781,7 @@ def get_type_to_cls_dict() -> Dict[str, Callable[[], Type[BaseLLM]]]: "self_hosted": _import_self_hosted, "self_hosted_hugging_face": _import_self_hosted_hugging_face, "stochasticai": _import_stochasticai, + "together": _import_together, "tongyi": _import_tongyi, "titan_takeoff": _import_titan_takeoff, "vertexai": _import_vertex, diff --git a/libs/langchain/langchain/llms/together.py b/libs/langchain/langchain/llms/together.py new file mode 100644 index 0000000000..c5445c1ad0 --- /dev/null +++ b/libs/langchain/langchain/llms/together.py @@ -0,0 +1,206 @@ +"""Wrapper around Together AI's Completion API.""" +import logging +from typing import Any, Dict, List, Optional + +from aiohttp import ClientSession + +from langchain.callbacks.manager import ( + AsyncCallbackManagerForLLMRun, + CallbackManagerForLLMRun, +) +from langchain.llms.base import LLM +from langchain.pydantic_v1 import Extra, root_validator +from langchain.utilities.requests import Requests +from langchain.utils import get_from_dict_or_env + +logger = logging.getLogger(__name__) + + +class Together(LLM): + """Wrapper around Together AI models. + + To use, you'll need an API key which you can find here: + https://api.together.xyz/settings/api-keys. This can be passed in as init param + ``together_api_key`` or set as environment variable ``TOGETHER_API_KEY``. + + Together AI API reference: https://docs.together.ai/reference/inference + """ + + base_url: str = "https://api.together.xyz/inference" + """Base inference API URL.""" + together_api_key: str + """Together AI API key. Get it here: https://api.together.xyz/settings/api-keys""" + model: str + """Model name. Available models listed here: + https://docs.together.ai/docs/inference-models + """ + temperature: Optional[float] = None + """Model temperature.""" + top_p: Optional[float] = None + """Used to dynamically adjust the number of choices for each predicted token based + on the cumulative probabilities. A value of 1 will always yield the same + output. A temperature less than 1 favors more correctness and is appropriate + for question answering or summarization. A value greater than 1 introduces more + randomness in the output. + """ + top_k: Optional[int] = None + """Used to limit the number of choices for the next predicted word or token. It + specifies the maximum number of tokens to consider at each step, based on their + probability of occurrence. This technique helps to speed up the generation + process and can improve the quality of the generated text by focusing on the + most likely options. + """ + max_tokens: Optional[int] = None + """The maximum number of tokens to generate.""" + repetition_penalty: Optional[float] = None + """A number that controls the diversity of generated text by reducing the + likelihood of repeated sequences. Higher values decrease repetition. + """ + logprobs: Optional[int] = None + """An integer that specifies how many top token log probabilities are included in + the response for each token generation step. + """ + + class Config: + """Configuration for this pydantic object.""" + + extra = Extra.forbid + + @root_validator(pre=True) + def validate_environment(cls, values: Dict) -> Dict: + """Validate that api key exists in environment.""" + values["together_api_key"] = get_from_dict_or_env( + values, "together_api_key", "TOGETHER_API_KEY" + ) + return values + + @property + def _llm_type(self) -> str: + """Return type of model.""" + return "together" + + def _format_output(self, output: dict) -> str: + return output["output"]["choices"][0]["text"] + + @staticmethod + def get_user_agent() -> str: + from langchain import __version__ + + return f"langchain/{__version__}" + + @property + def default_params(self) -> Dict[str, Any]: + return { + "model": self.model, + "temperature": self.temperature, + "top_p": self.top_p, + "top_k": self.top_k, + "max_tokens": self.max_tokens, + "repetition_penalty": self.repetition_penalty, + } + + def _call( + self, + prompt: str, + stop: Optional[List[str]] = None, + run_manager: Optional[CallbackManagerForLLMRun] = None, + **kwargs: Any, + ) -> str: + """Call out to Together's text generation endpoint. + + Args: + prompt: The prompt to pass into the model. + + Returns: + The string generated by the model.. + """ + + headers = { + "Authorization": f"Bearer {self.together_api_key}", + "Content-Type": "application/json", + } + stop_to_use = stop[0] if stop and len(stop) == 1 else stop + payload: Dict[str, Any] = { + **self.default_params, + "prompt": prompt, + "stop": stop_to_use, + **kwargs, + } + + # filter None values to not pass them to the http payload + payload = {k: v for k, v in payload.items() if v is not None} + request = Requests(headers=headers) + response = request.post(url=self.base_url, data=payload) + + if response.status_code >= 500: + raise Exception(f"Together Server: Error {response.status_code}") + elif response.status_code >= 400: + raise ValueError(f"Together received an invalid payload: {response.text}") + elif response.status_code != 200: + raise Exception( + f"Together returned an unexpected response with status " + f"{response.status_code}: {response.text}" + ) + + data = response.json() + if data.get("status") != "finished": + err_msg = data.get("error", "Undefined Error") + raise Exception(err_msg) + + output = self._format_output(data) + + return output + + async def _acall( + self, + prompt: str, + stop: Optional[List[str]] = None, + run_manager: Optional[AsyncCallbackManagerForLLMRun] = None, + **kwargs: Any, + ) -> str: + """Call Together model to get predictions based on the prompt. + + Args: + prompt: The prompt to pass into the model. + + Returns: + The string generated by the model. + """ + headers = { + "Authorization": f"Bearer {self.together_api_key}", + "Content-Type": "application/json", + } + stop_to_use = stop[0] if stop and len(stop) == 1 else stop + payload: Dict[str, Any] = { + **self.default_params, + "prompt": prompt, + "stop": stop_to_use, + **kwargs, + } + + # filter None values to not pass them to the http payload + payload = {k: v for k, v in payload.items() if v is not None} + async with ClientSession() as session: + async with session.post( + self.base_url, json=payload, headers=headers + ) as response: + if response.status >= 500: + raise Exception(f"Together Server: Error {response.status}") + elif response.status >= 400: + raise ValueError( + f"Together received an invalid payload: {response.text}" + ) + elif response.status != 200: + raise Exception( + f"Together returned an unexpected response with status " + f"{response.status}: {response.text}" + ) + + response_json = await response.json() + + if response_json.get("status") != "finished": + err_msg = response_json.get("error", "Undefined Error") + raise Exception(err_msg) + + output = self._format_output(response_json) + return output diff --git a/libs/langchain/tests/integration_tests/llms/test_together.py b/libs/langchain/tests/integration_tests/llms/test_together.py new file mode 100644 index 0000000000..ca88c6c861 --- /dev/null +++ b/libs/langchain/tests/integration_tests/llms/test_together.py @@ -0,0 +1,40 @@ +"""Test Together API wrapper. + +In order to run this test, you need to have an Together api key. +You can get it by registering for free at https://api.together.xyz/. +A test key can be found at https://api.together.xyz/settings/api-keys + +You'll then need to set TOGETHER_API_KEY environment variable to your api key. +""" +import pytest as pytest + +from langchain.llms import Together + + +def test_together_call() -> None: + """Test simple call to together.""" + llm = Together( + model="togethercomputer/RedPajama-INCITE-7B-Base", + temperature=0.2, + max_tokens=250, + ) + output = llm("Say foo:") + + assert llm._llm_type == "together" + assert isinstance(output, str) + + +@pytest.mark.asyncio +async def test_together_acall() -> None: + """Test simple call to together.""" + llm = Together( + model="togethercomputer/RedPajama-INCITE-7B-Base", + temperature=0.2, + max_tokens=250, + ) + output = await llm.agenerate(["Say foo:"], stop=["bar"]) + + assert llm._llm_type == "together" + output_text = output.generations[0][0].text + assert isinstance(output_text, str) + assert output_text.count("bar") <= 1