♻️ update LLM subclasses arguments

This commit is contained in:
Nate Sesti 2023-11-13 21:07:25 -08:00
parent 16c0f1d8f0
commit 2acf5c2a3f
13 changed files with 88 additions and 202 deletions

View file

@ -122,6 +122,7 @@ class LLM(ContinueBaseModel):
api_key: Optional[str] = Field(
None, description="The API key for the LLM provider."
)
api_base: Optional[str] = Field(None, description="The base URL of the LLM API.")
class Config:
arbitrary_types_allowed = True
@ -136,48 +137,16 @@ class LLM(ContinueBaseModel):
"context_length": {
"description": "The maximum context length of the LLM in tokens, as counted by count_tokens."
},
"max_tokens": {"description": "The maximum number of tokens to generate."},
"unique_id": {"description": "The unique ID of the user."},
"model": {
"description": "The name of the model to be used (e.g. gpt-4, codellama)"
},
"timeout": {
"description": "Set the timeout for each request to the LLM. If you are running a local LLM that takes a while to respond, you might want to set this to avoid timeouts."
},
"prompt_templates": {
"description": 'A dictionary of prompt templates that can be used to customize the behavior of the LLM in certain situations. For example, set the "edit" key in order to change the prompt that is used for the /edit slash command. Each value in the dictionary is a string templated in mustache syntax, and filled in at runtime with the variables specific to the situation OR an instance of the PromptTemplate class if you want to control other parameters. See the documentation for more information.'
},
"template_messages": {
"description": "A function that takes a list of messages and returns a prompt. This ensures that models like llama2, which are trained on specific chat formats, will always receive input in that format."
},
"write_log": {
"description": "A function that is called upon every prompt and completion, by default to log to the file which can be viewed by clicking on the magnifying glass."
},
"api_key": {"description": "The API key for the LLM provider."},
"verify_ssl": {
"description": "Whether to verify SSL certificates for requests."
},
"ca_bundle_path": {
"description": "Path to a custom CA bundle to use when making the HTTP request"
},
"headers": {"description": "Headers to use when making the HTTP request"},
"proxy": {"description": "Proxy URL to use when making the HTTP request"},
"stop_tokens": {"description": "Tokens that will stop the completion."},
"temperature": {
"description": "The sampling temperature used for generation."
},
"top_p": {
"description": "The top_p sampling parameter used for generation."
},
"top_k": {
"description": "The top_k sampling parameter used for generation."
},
"presence_penalty": {
"description": "The presence penalty used for completions."
},
"frequency_penalty": {
"description": "The frequency penalty used for completions."
},
}
def dict(self, **kwargs):
@ -205,23 +174,25 @@ class LLM(ContinueBaseModel):
self._config_temperature = temperature
def create_client_session(self):
if self.verify_ssl is False:
if self.request_options.verify_ssl is False:
return aiohttp.ClientSession(
connector=aiohttp.TCPConnector(verify_ssl=False),
timeout=aiohttp.ClientTimeout(total=self.timeout),
headers=self.headers,
timeout=aiohttp.ClientTimeout(total=self.request_options.timeout),
headers=self.request_options.headers,
trust_env=True,
)
else:
ca_bundle_path = (
certifi.where() if self.ca_bundle_path is None else self.ca_bundle_path
certifi.where()
if self.request_options.ca_bundle_path is None
else self.request_options.ca_bundle_path
)
if os.path.exists(ca_bundle_path):
ssl_context = ssl.create_default_context(cafile=ca_bundle_path)
return aiohttp.ClientSession(
connector=aiohttp.TCPConnector(ssl_context=ssl_context),
timeout=aiohttp.ClientTimeout(total=self.timeout),
headers=self.headers,
timeout=aiohttp.ClientTimeout(total=self.request_options.timeout),
headers=self.request_options.headers,
trust_env=True,
)
else:
@ -230,8 +201,8 @@ class LLM(ContinueBaseModel):
ca_bundle_path,
)
return aiohttp.ClientSession(
timeout=aiohttp.ClientTimeout(total=self.timeout),
headers=self.headers,
timeout=aiohttp.ClientTimeout(total=self.request_options.timeout),
headers=self.request_options.headers,
trust_env=True,
)
@ -328,13 +299,15 @@ Settings:
"""Yield completion response, either streamed or not."""
options = CompletionOptions(
model=model or self.model,
temperature=temperature or self.temperature,
top_p=top_p or self.top_p,
top_k=top_k or self.top_k,
presence_penalty=presence_penalty or self.presence_penalty,
frequency_penalty=frequency_penalty or self.frequency_penalty,
stop=stop or self.stop_tokens,
max_tokens=max_tokens or self.max_tokens,
temperature=temperature or self.completion_options.temperature,
top_p=top_p or self.completion_options.top_p,
top_k=top_k or self.completion_options.top_k,
presence_penalty=presence_penalty
or self.completion_options.presence_penalty,
frequency_penalty=frequency_penalty
or self.completion_options.frequency_penalty,
stop=stop or self.completion_options.stop,
max_tokens=max_tokens or self.completion_options.max_tokens,
functions=functions,
)
@ -376,13 +349,15 @@ Settings:
"""Yield completion response, either streamed or not."""
options = CompletionOptions(
model=model or self.model,
temperature=temperature or self.temperature,
top_p=top_p or self.top_p,
top_k=top_k or self.top_k,
presence_penalty=presence_penalty or self.presence_penalty,
frequency_penalty=frequency_penalty or self.frequency_penalty,
stop=stop or self.stop_tokens,
max_tokens=max_tokens or self.max_tokens,
temperature=temperature or self.completion_options.temperature,
top_p=top_p or self.completion_options.top_p,
top_k=top_k or self.completion_options.top_k,
presence_penalty=presence_penalty
or self.completion_options.presence_penalty,
frequency_penalty=frequency_penalty
or self.completion_options.frequency_penalty,
stop=stop or self.completion_options.stop,
max_tokens=max_tokens or self.completion_options.max_tokens,
functions=functions,
)
@ -422,13 +397,15 @@ Settings:
"""Yield completion response, either streamed or not."""
options = CompletionOptions(
model=model or self.model,
temperature=temperature or self.temperature,
top_p=top_p or self.top_p,
top_k=top_k or self.top_k,
presence_penalty=presence_penalty or self.presence_penalty,
frequency_penalty=frequency_penalty or self.frequency_penalty,
stop=stop or self.stop_tokens,
max_tokens=max_tokens or self.max_tokens,
temperature=temperature or self.completion_options.temperature,
top_p=top_p or self.completion_options.top_p,
top_k=top_k or self.completion_options.top_k,
presence_penalty=presence_penalty
or self.completion_options.presence_penalty,
frequency_penalty=frequency_penalty
or self.completion_options.frequency_penalty,
stop=stop or self.completion_options.stop,
max_tokens=max_tokens or self.completion_options.max_tokens,
functions=functions,
)

View file

@ -31,7 +31,7 @@ class GGML(LLM):
```
"""
server_url: str = Field(
api_base: str = Field(
"http://localhost:8000",
description="URL of the OpenAI-compatible server where the model is being served",
)
@ -39,8 +39,6 @@ class GGML(LLM):
"ggml", description="The name of the model to use (optional for the GGML class)"
)
api_base: Optional[str] = Field(None, description="OpenAI API base URL.")
api_type: Optional[Literal["azure", "openai"]] = Field(
None, description="OpenAI API type."
)
@ -53,28 +51,6 @@ class GGML(LLM):
None, description="OpenAI engine. For use with Azure OpenAI Service."
)
api_base: Optional[str] = Field(None, description="OpenAI API base URL.")
api_type: Optional[Literal["azure", "openai"]] = Field(
None, description="OpenAI API type."
)
api_version: Optional[str] = Field(
None, description="OpenAI API version. For use with Azure OpenAI Service."
)
engine: Optional[str] = Field(
None, description="OpenAI engine. For use with Azure OpenAI Service."
)
template_messages: Optional[
Callable[[List[Dict[str, str]]], str]
] = llama2_template_messages
prompt_templates = {
"edit": codellama_edit_prompt,
}
class Config:
arbitrary_types_allowed = True
@ -101,20 +77,7 @@ class GGML(LLM):
return f"{self.api_base}/openai/deployments/{self.engine}/{endpoint}?api-version={self.api_version}"
else:
return f"{self.server_url}/v1/{endpoint}"
def get_full_server_url(self, endpoint: str):
endpoint = endpoint.lstrip("/").rstrip("/")
if self.api_type == "azure":
if self.engine is None or self.api_version is None or self.api_base is None:
raise Exception(
"For Azure OpenAI Service, you must specify engine, api_version, and api_base."
)
return f"{self.api_base}/openai/deployments/{self.engine}/{endpoint}?api-version={self.api_version}"
else:
return f"{self.server_url}/v1/{endpoint}"
return f"{self.api_base}/v1/{endpoint}"
async def _raw_stream_complete(self, prompt, options):
args = self.collect_args(options)

View file

@ -31,19 +31,11 @@ class HuggingFaceInferenceAPI(LLM):
"Hugging Face Inference API",
description="The name of the model to use (optional for the HuggingFaceInferenceAPI class)",
)
hf_token: str = Field(..., description="Your Hugging Face API token")
endpoint_url: str = Field(
api_key: str = Field(..., description="Your Hugging Face API token")
api_base: str = Field(
None, description="Your Hugging Face Inference API endpoint URL"
)
template_messages: Union[
Callable[[List[Dict[str, str]]], str], None
] = llama2_template_messages
prompt_templates = {
"edit": codellama_edit_prompt,
}
class Config:
arbitrary_types_allowed = True
@ -63,7 +55,7 @@ class HuggingFaceInferenceAPI(LLM):
async def _stream_complete(self, prompt, options):
args = self.collect_args(options)
client = InferenceClient(self.endpoint_url, token=self.hf_token)
client = InferenceClient(self.api_base, token=self.api_key)
stream = client.text_generation(prompt, stream=True, details=True, **args)

View file

@ -12,15 +12,7 @@ from .prompts.edit import codellama_edit_prompt
class HuggingFaceTGI(LLM):
model: str = "huggingface-tgi"
server_url: str = Field(
"http://localhost:8080", description="URL of your TGI server"
)
template_messages: Callable[[List[ChatMessage]], str] = llama2_template_messages
prompt_templates = {
"edit": codellama_edit_prompt,
}
api_base: str = Field("http://localhost:8080", description="URL of your TGI server")
class Config:
arbitrary_types_allowed = True
@ -42,7 +34,7 @@ class HuggingFaceTGI(LLM):
async with self.create_client_session() as client_session:
async with client_session.post(
f"{self.server_url}/generate_stream",
f"{self.api_base}/generate_stream",
json={"inputs": prompt, "parameters": args},
headers={"Content-Type": "application/json"},
proxy=self.proxy,

View file

@ -33,18 +33,13 @@ class LlamaCpp(LLM):
"""
model: str = "llamacpp"
server_url: str = Field("http://localhost:8080", description="URL of the server")
api_base: str = Field("http://localhost:8080", description="URL of the server")
llama_cpp_args: Dict[str, Any] = Field(
{"stop": ["[INST]"]},
description="A list of additional arguments to pass to llama.cpp. See [here](https://github.com/ggerganov/llama.cpp/tree/master/examples/server#api-endpoints) for the complete catalog of options.",
)
template_messages: Callable = llama2_template_messages
prompt_templates = {
"edit": codellama_edit_prompt,
}
class Config:
arbitrary_types_allowed = True
@ -71,10 +66,10 @@ class LlamaCpp(LLM):
async def server_generator():
async with self.create_client_session() as client_session:
async with client_session.post(
f"{self.server_url}/completion",
f"{self.api_base}/completion",
json={"prompt": prompt, "stream": True, **args},
headers=headers,
proxy=self.proxy,
proxy=self.request_options.proxy,
) as resp:
async for line in resp.content:
content = line.decode("utf-8")

View file

@ -1,14 +1,10 @@
import json
from typing import Any, Callable, Dict
import aiohttp
from pydantic import Field
from ...core.main import ContinueCustomException
from ..util.logging import logger
from .base import LLM, CompletionOptions
from .prompts.chat import llama2_template_messages
from .prompts.edit import codellama_edit_prompt
class Ollama(LLM):
@ -28,16 +24,10 @@ class Ollama(LLM):
"""
model: str = "llama2"
server_url: str = Field(
api_base: str = Field(
"http://localhost:11434", description="URL of the Ollama server"
)
template_messages: Callable = llama2_template_messages
prompt_templates = {
"edit": codellama_edit_prompt,
}
class Config:
arbitrary_types_allowed = True
@ -55,8 +45,8 @@ class Ollama(LLM):
try:
async with self.create_client_session() as session:
async with session.post(
f"{self.server_url}/api/generate",
proxy=self.proxy,
f"{self.api_base}/api/generate",
proxy=self.request_options.proxy,
json={
"prompt": "",
"model": self.model,
@ -69,8 +59,8 @@ class Ollama(LLM):
async def get_downloaded_models(self):
async with self.create_client_session() as session:
async with session.get(
f"{self.server_url}/api/tags",
proxy=self.proxy,
f"{self.api_base}/api/tags",
proxy=self.request_options.proxy,
) as resp:
js_data = await resp.json()
return list(map(lambda x: x["name"], js_data["models"]))
@ -78,14 +68,14 @@ class Ollama(LLM):
async def _stream_complete(self, prompt, options):
async with self.create_client_session() as session:
async with session.post(
f"{self.server_url}/api/generate",
f"{self.api_base}/api/generate",
json={
"template": prompt,
"model": self.model,
"system": self.system_message,
"options": self.collect_args(options),
},
proxy=self.proxy,
proxy=self.request_options.proxy,
) as resp:
if resp.status == 400:
txt = await resp.text()

View file

@ -18,7 +18,7 @@ CHAT_MODELS = {
"gpt-4",
"gpt-3.5-turbo-0613",
"gpt-4-32k",
"gpt-4-1106-preview"
"gpt-4-1106-preview",
}
NON_CHAT_MODELS = {
"gpt-3.5-turbo-instruct",
@ -71,8 +71,6 @@ class OpenAI(LLM):
description="OpenAI API key",
)
proxy: Optional[str] = Field(None, description="Proxy URL to use for requests.")
api_base: Optional[str] = Field(None, description="OpenAI API base URL.")
api_type: Optional[Literal["azure", "openai"]] = Field(
@ -83,15 +81,15 @@ class OpenAI(LLM):
None, description="OpenAI API version. For use with Azure OpenAI Service."
)
engine: Optional[str] = Field(
None, description="OpenAI engine. For use with Azure OpenAI Service."
)
use_legacy_completions_endpoint: bool = Field(
False,
description="Manually specify to use the legacy completions endpoint instead of chat completions.",
)
engine: Optional[str] = Field(
None, description="OpenAI engine. For use with Azure OpenAI Service."
)
@validator("context_length")
def context_length_for_model(cls, v, values):
return CONTEXT_LENGTH_FOR_MODEL.get(values["model"], 4096)
@ -110,13 +108,16 @@ class OpenAI(LLM):
if self.api_version is not None:
openai.api_version = self.api_version
if self.verify_ssl is not None and self.verify_ssl is False:
if (
self.request_options.verify_ssl is not None
and self.request_options.verify_ssl is False
):
openai.verify_ssl_certs = False
if self.proxy is not None:
openai.proxy = self.proxy
if self.request_options.proxy is not None:
openai.proxy = self.request_options.proxy
openai.ca_bundle_path = self.ca_bundle_path or certifi.where()
openai.ca_bundle_path = self.request_options.ca_bundle_path or certifi.where()
session = self.create_client_session()
openai.aiosession.set(session)
@ -142,13 +143,13 @@ class OpenAI(LLM):
async for chunk in await openai.ChatCompletion.acreate(
messages=[{"role": "user", "content": prompt}],
**args,
headers=self.headers,
headers=self.request_options.headers,
):
if len(chunk.choices) > 0 and "content" in chunk.choices[0].delta:
yield chunk.choices[0].delta.content
else:
async for chunk in await openai.Completion.acreate(
prompt=prompt, **args, headers=self.headers
prompt=prompt, **args, headers=self.request_options.headers
):
if len(chunk.choices) > 0:
yield chunk.choices[0].text
@ -164,7 +165,7 @@ class OpenAI(LLM):
messages=messages,
stream=True,
**args,
headers=self.headers,
headers=self.request_options.headers,
):
if not hasattr(chunk, "choices") or len(chunk.choices) == 0:
continue
@ -183,7 +184,7 @@ class OpenAI(LLM):
prompt=template_alpaca_messages(messages),
stream=True,
**args,
headers=self.headers,
headers=self.request_options.headers,
):
if len(chunk.choices) > 0:
yield {
@ -204,7 +205,7 @@ class OpenAI(LLM):
resp = await openai.ChatCompletion.acreate(
messages=[{"role": "user", "content": prompt}],
**args,
headers=self.headers,
headers=self.request_options.headers,
)
return resp.choices[0].message.content
except RateLimitError as e:
@ -217,7 +218,7 @@ class OpenAI(LLM):
return (
(
await openai.Completion.acreate(
prompt=prompt, **args, headers=self.headers
prompt=prompt, **args, headers=self.request_options.headers
)
)
.choices[0]

View file

@ -35,8 +35,6 @@ class OpenAIFreeTrial(LLM):
These classes support any models available through the OpenAI API, assuming your API key has access, including "gpt-4", "gpt-3.5-turbo", "gpt-3.5-turbo-16k", and "gpt-4-32k".
"""
api_key: Optional[str] = None
llm: Optional[LLM] = None
@validator("context_length", pre=True, always=True)
@ -52,15 +50,15 @@ class OpenAIFreeTrial(LLM):
if self.api_key is None or self.api_key.strip() == "":
self.llm = ProxyServer(
model=self.model,
verify_ssl=self.verify_ssl,
ca_bundle_path=self.ca_bundle_path,
verify_ssl=self.request_options.verify_ssl,
ca_bundle_path=self.request_options.ca_bundle_path,
)
else:
self.llm = OpenAI(
api_key=self.api_key,
model=self.model,
verify_ssl=self.verify_ssl,
ca_bundle_path=self.ca_bundle_path,
verify_ssl=self.request_options.verify_ssl,
ca_bundle_path=self.request_options.ca_bundle_path,
)
await self.llm.start(unique_id=unique_id)

View file

@ -3,7 +3,6 @@ import json
import traceback
from typing import List
import aiohttp
from pydantic import validator
from ..util.count_tokens import CONTEXT_LENGTH_FOR_MODEL
@ -41,7 +40,7 @@ class ProxyServer(LLM):
f"{SERVER_URL}/complete",
json={"messages": [{"role": "user", "content": prompt}], **args},
headers=self.get_headers(),
proxy=self.proxy,
proxy=self.request_options.proxy,
) as resp:
resp_text = await resp.text()
if resp.status != 200:
@ -56,7 +55,7 @@ class ProxyServer(LLM):
f"{SERVER_URL}/stream_chat",
json={"messages": messages, **args},
headers=self.get_headers(),
proxy=self.proxy,
proxy=self.request_options.proxy,
) as resp:
if resp.status != 200:
raise Exception(await resp.text())
@ -100,7 +99,7 @@ class ProxyServer(LLM):
f"{SERVER_URL}/stream_complete",
json={"messages": [{"role": "user", "content": prompt}], **args},
headers=self.get_headers(),
proxy=self.proxy,
proxy=self.request_options.proxy,
) as resp:
if resp.status != 200:
raise Exception(await resp.text())

View file

@ -36,10 +36,6 @@ class ReplicateLLM(LLM):
_client: replicate.Client = None
prompt_templates = {
"edit": codellama_edit_prompt,
}
async def start(self, *args, **kwargs):
await super().start(*args, **kwargs)
self._client = replicate.Client(api_token=self.api_key)

View file

@ -1,13 +1,10 @@
import json
from typing import Any, Callable, Dict, List, Union
from typing import Any, List
import websockets
from pydantic import Field
from ...core.main import ChatMessage
from .base import LLM
from .prompts.chat import llama2_template_messages
from .prompts.edit import simplest_edit_prompt
class TextGenWebUI(LLM):
@ -29,7 +26,7 @@ class TextGenWebUI(LLM):
"""
model: str = "text-gen-webui"
server_url: str = Field(
api_base: str = Field(
"http://localhost:5000", description="URL of your TextGenWebUI server"
)
streaming_url: str = Field(
@ -37,14 +34,6 @@ class TextGenWebUI(LLM):
description="URL of your TextGenWebUI streaming server (separate from main server URL)",
)
prompt_templates = {
"edit": simplest_edit_prompt,
}
template_messages: Union[
Callable[[List[Dict[str, str]]], str], None
] = llama2_template_messages
class Config:
arbitrary_types_allowed = True

View file

@ -32,30 +32,24 @@ class TogetherLLM(LLM):
api_key: str = Field(..., description="Together API key")
model: str = "togethercomputer/RedPajama-INCITE-7B-Instruct"
base_url: str = Field(
api_base: str = Field(
"https://api.together.xyz",
description="The base URL for your Together API instance",
)
template_messages: Callable = llama2_template_messages
prompt_templates = {
"edit": codellama_edit_prompt,
}
async def _stream_complete(self, prompt, options):
args = self.collect_args(options)
async with self.create_client_session() as session:
async with session.post(
f"{self.base_url}/inference",
f"{self.api_base}/inference",
json={
"prompt": prompt,
"stream_tokens": True,
**args,
},
headers={"Authorization": f"Bearer {self.api_key}"},
proxy=self.proxy,
proxy=self.request_options.proxy,
) as resp:
async for line in resp.content.iter_chunks():
if line[1]:
@ -92,10 +86,10 @@ class TogetherLLM(LLM):
async with self.create_client_session() as session:
async with session.post(
f"{self.base_url}/inference",
f"{self.api_base}/inference",
json={"prompt": prompt, **args},
headers={"Authorization": f"Bearer {self.api_key}"},
proxy=self.proxy,
proxy=self.request_options.proxy,
) as resp:
text = await resp.text()
j = json.loads(text)

View file

@ -142,7 +142,7 @@ class TestGGML(TestBaseLLM):
model="gpt-3.5-turbo",
context_length=cls.context_length,
system_message=cls.system_message,
server_url="https://api.openai.com",
api_base="https://api.openai.com",
api_key=os.environ["OPENAI_API_KEY"],
)
start_model(cls.llm)