feat: ✨ more model options, ollama error handling

This commit is contained in:
Nate Sesti 2023-10-06 19:03:21 -07:00
parent 9b379ddc6f
commit e2a7d4a3c7
9 changed files with 346 additions and 43 deletions

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 483 KiB

View file

@ -159,6 +159,12 @@ export interface ModelPackage {
dimensions?: PackageDimension[];
}
enum ChatTemplates {
"alpaca" = "template_alpaca_messages",
"llama2" = "llama2_template_messages",
"sqlcoder" = "sqlcoder_template_messages",
}
const codeLlamaInstruct: ModelPackage = {
title: "CodeLlama Instruct",
description:
@ -168,7 +174,7 @@ const codeLlamaInstruct: ModelPackage = {
title: "CodeLlama-7b-Instruct",
model: "codellama:7b-instruct",
context_length: 2048,
template_messages: "llama2_template_messages",
template_messages: ChatTemplates.llama2,
},
icon: "meta.svg",
dimensions: [
@ -201,7 +207,7 @@ const llama2Chat: ModelPackage = {
title: "Llama2-7b-Chat",
model: "llama2:7b-chat",
context_length: 2048,
template_messages: "llama2_template_messages",
template_messages: ChatTemplates.llama2,
},
icon: "meta.svg",
dimensions: [
@ -226,6 +232,113 @@ const llama2Chat: ModelPackage = {
],
};
const wizardCoder: ModelPackage = {
title: "WizardCoder",
description:
"A CodeLlama-based code generation model from WizardLM, focused on Python",
refUrl: "",
params: {
title: "WizardCoder-7b-Python",
model: "wizardcoder:7b-python",
context_length: 2048,
template_messages: ChatTemplates.alpaca,
},
icon: "wizardlm.png",
dimensions: [
{
name: "Parameter Count",
description: "The number of parameters in the model",
options: {
"7b": {
model: "wizardcoder:7b-python",
title: "WizardCoder-7b-Python",
},
"13b": {
model: "wizardcoder:13b-python",
title: "WizardCoder-13b-Python",
},
"34b": {
model: "wizardcoder:34b-python",
title: "WizardCoder-34b-Python",
},
},
},
],
};
const phindCodeLlama: ModelPackage = {
title: "Phind CodeLlama (34b)",
description: "A finetune of CodeLlama by Phind",
params: {
title: "Phind CodeLlama",
model: "phind-codellama",
context_length: 2048,
template_messages: ChatTemplates.llama2,
},
};
const mistral: ModelPackage = {
title: "Mistral (7b)",
description:
"A 7b parameter base model created by Mistral AI, very competent for code generation and other tasks",
params: {
title: "Mistral",
model: "mistral",
context_length: 2048,
template_messages: ChatTemplates.llama2,
},
icon: "mistral.png",
};
const sqlCoder: ModelPackage = {
title: "SQLCoder",
description:
"A finetune of StarCoder by Defog.ai, focused specifically on SQL",
params: {
title: "SQLCoder",
model: "sqlcoder",
context_length: 2048,
template_messages: ChatTemplates.sqlcoder,
},
dimensions: [
{
name: "Parameter Count",
description: "The number of parameters in the model",
options: {
"7b": {
model: "sqlcoder:7b",
title: "SQLCoder-7b",
},
"13b": {
model: "sqlcoder:15b",
title: "SQLCoder-15b",
},
},
},
],
};
const codeup: ModelPackage = {
title: "CodeUp (13b)",
description: "An open-source coding model based on Llama2",
params: {
title: "CodeUp",
model: "codeup",
context_length: 2048,
template_messages: ChatTemplates.llama2,
},
};
const osModels = [
codeLlamaInstruct,
llama2Chat,
wizardCoder,
phindCodeLlama,
sqlCoder,
mistral,
codeup,
];
const gpt4: ModelPackage = {
title: "GPT-4",
description: "The latest model from OpenAI",
@ -249,6 +362,23 @@ const gpt35turbo: ModelPackage = {
},
};
const OLLAMA_TO_REPLICATE_MODEL_NAMES: { [key: string]: string } = {
"codellama:7b-instruct":
"meta/codellama-7b-instruct:6527b83e01e41412db37de5110a8670e3701ee95872697481a355e05ce12af0e",
"codellama:13b-instruct":
"meta/codellama-13b-instruct:1f01a52ff933873dff339d5fb5e1fd6f24f77456836f514fa05e91c1a42699c7",
"codellama:34b-instruct":
"meta/codellama-34b-instruct:8281a5c610f6e88237ff3ddaf3c33b56f60809e2bdd19fbec2fda742aa18167e",
"llama2:7b-chat":
"meta/llama-2-7b-chat:8e6975e5ed6174911a6ff3d60540dfd4844201974602551e10e9e87ab143d81e",
"llama2:13b-chat":
"meta/llama-2-13b-chat:f4e2de70d66816a838a89eeeb621910adffb0dd0baba3976c96980970978018d",
};
function replicateConvertModelName(model: string): string {
return OLLAMA_TO_REPLICATE_MODEL_NAMES[model] || model;
}
export const MODEL_INFO: { [key: string]: ModelInfo } = {
openai: {
title: "OpenAI",
@ -310,16 +440,7 @@ export const MODEL_INFO: { [key: string]: ModelInfo } = {
'To get started with Ollama, follow these steps:\n1. Download from [ollama.ai](https://ollama.ai/) and open the application\n2. Open a terminal and run `ollama pull <MODEL_NAME>`. Example model names are `codellama:7b-instruct` or `llama2:7b-text`. You can find the full list [here](https://ollama.ai/library).\n3. Make sure that the model name used in step 2 is the same as the one in config.py (e.g. `model="codellama:7b-instruct"`)\n4. Once the model has finished downloading, you can start asking questions through Continue.',
icon: "ollama.png",
tags: [ModelProviderTag["Local"], ModelProviderTag["Open-Source"]],
packages: [
{
...codeLlamaInstruct,
refUrl: "https://ollama.ai/library/codellama",
},
{
...llama2Chat,
refUrl: "https://ollama.ai/library/llama2",
},
],
packages: osModels,
collectInputFor: [...completionParamsInputs],
},
together: {
@ -351,9 +472,9 @@ export const MODEL_INFO: { [key: string]: ModelInfo } = {
"dimensions[0].options": (options: any) =>
_.mapValues(options, (option) => {
return _.assign({}, option, {
model: option.model
.replace("llama2", "llama-2")
.replace(":", "-"),
model:
"togethercomputer/" +
option.model.replace("llama2", "llama-2").replace(":", "-"),
});
}),
}),
@ -361,13 +482,35 @@ export const MODEL_INFO: { [key: string]: ModelInfo } = {
"dimensions[0].options": (options: any) =>
_.mapValues(options, (option) => {
return _.assign({}, option, {
model: option.model
.replace("codellama", "CodeLlama")
.replace(":", "-")
.replace("instruct", "Instruct"),
model:
"togethercomputer/" +
option.model
.replace("codellama", "CodeLlama")
.replace(":", "-")
.replace("instruct", "Instruct"),
});
}),
}),
updatedObj(wizardCoder, {
"params.model": "WizardLM/WizardCoder-15B-V1.0",
"params.title": "WizardCoder-15b",
"dimensions[0].options": {
"15b": {
model: "WizardLM/WizardCoder-15B-V1.0",
title: "WizardCoder-15b",
},
"34b (Python)": {
model: "WizardLM/WizardCoder-Python-34B-V1.0",
title: "WizardCoder-34b-Python",
},
},
}),
updatedObj(phindCodeLlama, {
"params.model": "Phind/Phind-CodeLlama-34B-Python-v1",
}),
updatedObj(mistral, {
"params.model": "mistralai/Mistral-7B-Instruct-v0.1",
}),
].map((p) => {
p.params.context_length = 4096;
return p;
@ -385,7 +528,7 @@ export const MODEL_INFO: { [key: string]: ModelInfo } = {
params: {
server_url: "http://localhost:1234",
},
packages: [codeLlamaInstruct, llama2Chat],
packages: osModels,
collectInputFor: [...completionParamsInputs],
},
replicate: {
@ -411,17 +554,55 @@ export const MODEL_INFO: { [key: string]: ModelInfo } = {
ModelProviderTag["Requires API Key"],
ModelProviderTag["Open-Source"],
],
packages: [codeLlamaInstruct, llama2Chat].map((p) => {
return {
...p,
params: {
...p.params,
model:
"meta/" +
p.params.model.replace(":", "-").replace("llama2", "llama-2"),
},
};
}),
packages: [
...[codeLlamaInstruct, llama2Chat]
.map((p: ModelPackage) => {
if (p.title === "Llama2 Chat") {
return updatedObj(p, {
"dimensions[0].options.34b": undefined,
"dimensions[0].options.70b": {
model:
"meta/llama-2-70b-chat:02e509c789964a7ea8736978a43525956ef40397be9033abf9fd2badfe68c9e3",
title: "Llama2-70b-Chat",
},
});
}
return p;
})
.map((p) => {
return updatedObj(p, {
"params.model": (model: string) => {
return replicateConvertModelName(model);
},
"dimensions[0].options": (options: any) => {
const newOptions: any = {};
for (const key in options) {
newOptions[key] = {
...options[key],
model: replicateConvertModelName(options[key]?.model),
};
}
return newOptions;
},
});
}),
updatedObj(wizardCoder, {
title: "WizardCoder (15b)",
"params.model":
"andreasjansson/wizardcoder-python-34b-v1-gguf:67eed332a5389263b8ede41be3ee7dc119fa984e2bde287814c4abed19a45e54",
dimensions: undefined,
}),
updatedObj(sqlCoder, {
dimensions: undefined,
title: "SQLCoder (15b)",
"params.model":
"gregwdata/defog-sqlcoder-q8:0a9abc0d143072fd5d8920ad90b8fbaafaf16b10ffdad24bd897b5bffacfce0b",
}),
updatedObj(mistral, {
"params.model":
"a16z-infra/mistral-7b-instruct-v0.1:83b6a56e7c828e667f21fd596c338fd4f0039b46bcfa18d973e8e70e455fda70",
}),
],
},
llamacpp: {
title: "llama.cpp",
@ -441,7 +622,7 @@ export const MODEL_INFO: { [key: string]: ModelInfo } = {
After it's up and running, you can start using Continue.`,
icon: "llamacpp.png",
tags: [ModelProviderTag.Local, ModelProviderTag["Open-Source"]],
packages: [codeLlamaInstruct, llama2Chat],
packages: osModels,
collectInputFor: [...completionParamsInputs],
},
palm: {
@ -483,7 +664,7 @@ After it's up and running, you can start using Continue.`,
"HuggingFace Text Generation Inference is an advanced, highly-performant option for serving open-source models to multiple people. To get started, follow the [Quick Tour](https://huggingface.co/docs/text-generation-inference/quicktour) on their website to set up the Docker container. Make sure to enter the server URL below that corresponds to the host and port you set up for the Docker container.",
icon: "hf.png",
tags: [ModelProviderTag.Local, ModelProviderTag["Open-Source"]],
packages: [codeLlamaInstruct, llama2Chat],
packages: osModels,
collectInputFor: [
...completionParamsInputs,
{ ...serverUrlInput, defaultValue: "http://localhost:8080" },
@ -512,7 +693,7 @@ After it's up and running, you can start using Continue.`,
],
icon: "openai.svg",
tags: [ModelProviderTag.Local, ModelProviderTag["Open-Source"]],
packages: [codeLlamaInstruct, llama2Chat],
packages: osModels,
},
freetrial: {
title: "GPT-4 limited free trial",

View file

@ -445,8 +445,9 @@ class Autopilot(ContinueBaseModel):
caught_error = True
is_continue_custom_exception = issubclass(
e.__class__, ContinueCustomException
is_continue_custom_exception = (
issubclass(e.__class__, ContinueCustomException)
or e.__class__.__name__ == ContinueCustomException.__name__
)
error_string = (

View file

@ -179,7 +179,8 @@ class LLM(ContinueBaseModel):
def dict(self, **kwargs):
original_dict = super().dict(**kwargs)
original_dict.pop("write_log")
original_dict.pop("template_messages")
if self.template_messages is not None:
original_dict["template_messages"] = self.template_messages.__name__
original_dict.pop("unique_id")
original_dict["class_name"] = self.__class__.__name__
return original_dict

View file

@ -4,6 +4,7 @@ from typing import Callable
import aiohttp
from pydantic import Field
from ...core.main import ContinueCustomException
from ..util.logging import logger
from .base import LLM
from .prompts.chat import llama2_template_messages
@ -61,6 +62,14 @@ class Ollama(LLM):
async def stop(self):
await self._client_session.close()
async def get_downloaded_models(self):
async with self._client_session.get(
f"{self.server_url}/api/tags",
proxy=self.proxy,
) as resp:
js_data = await resp.json()
return list(map(lambda x: x["name"], js_data["models"]))
async def _stream_complete(self, prompt, options):
async with self._client_session.post(
f"{self.server_url}/api/generate",
@ -72,6 +81,20 @@ class Ollama(LLM):
},
proxy=self.proxy,
) as resp:
if resp.status == 400:
txt = await resp.text()
extra_msg = ""
if "no such file" in txt:
extra_msg = f"\n\nThis means that the model '{self.model}' is not downloaded.\n\nYou have the following models downloaded: {', '.join(await self.get_downloaded_models())}.\n\nTo download this model, run `ollama run {self.model}` in your terminal."
raise ContinueCustomException(
f"Ollama returned an error: {txt}{extra_msg}",
"Invalid request to Ollama",
)
elif resp.status != 200:
raise ContinueCustomException(
f"Ollama returned an error: {await resp.text()}",
"Invalid request to Ollama",
)
async for line in resp.content.iter_any():
if line:
json_chunk = line.decode("utf-8")

View file

@ -37,6 +37,85 @@ def template_alpaca_messages(msgs: List[Dict[str, str]]) -> str:
return prompt
def raw_input_template(msgs: List[Dict[str, str]]) -> str:
return msgs[-1]["content"]
SQL_CODER_DEFAULT_SCHEMA = """\
CREATE TABLE products (
product_id INTEGER PRIMARY KEY, -- Unique ID for each product
name VARCHAR(50), -- Name of the product
price DECIMAL(10,2), -- Price of each unit of the product
quantity INTEGER -- Current quantity in stock
);
CREATE TABLE customers (
customer_id INTEGER PRIMARY KEY, -- Unique ID for each customer
name VARCHAR(50), -- Name of the customer
address VARCHAR(100) -- Mailing address of the customer
);
CREATE TABLE salespeople (
salesperson_id INTEGER PRIMARY KEY, -- Unique ID for each salesperson
name VARCHAR(50), -- Name of the salesperson
region VARCHAR(50) -- Geographic sales region
);
CREATE TABLE sales (
sale_id INTEGER PRIMARY KEY, -- Unique ID for each sale
product_id INTEGER, -- ID of product sold
customer_id INTEGER, -- ID of customer who made purchase
salesperson_id INTEGER, -- ID of salesperson who made the sale
sale_date DATE, -- Date the sale occurred
quantity INTEGER -- Quantity of product sold
);
CREATE TABLE product_suppliers (
supplier_id INTEGER PRIMARY KEY, -- Unique ID for each supplier
product_id INTEGER, -- Product ID supplied
supply_price DECIMAL(10,2) -- Unit price charged by supplier
);
-- sales.product_id can be joined with products.product_id
-- sales.customer_id can be joined with customers.customer_id
-- sales.salesperson_id can be joined with salespeople.salesperson_id
-- product_suppliers.product_id can be joined with products.product_id
"""
def _sqlcoder_template_messages(
msgs: List[Dict[str, str]], schema: str = SQL_CODER_DEFAULT_SCHEMA
) -> str:
question = msgs[-1]["content"]
return f"""\
Your task is to convert a question into a SQL query, given a Postgres database schema.
Adhere to these rules:
- **Deliberately go through the question and database schema word by word** to appropriately answer the question
- **Use Table Aliases** to prevent ambiguity. For example, `SELECT table1.col1, table2.col1 FROM table1 JOIN table2 ON table1.id = table2.id`.
- When creating a ratio, always cast the numerator as float
### Input:
Generate a SQL query that answers the question `{question}`.
This query will run on a database whose schema is represented in this string:
{schema}
### Response:
Based on your instructions, here is the SQL query I have generated to answer the question `{question}`:
```sql
"""
def sqlcoder_template_messages(schema: str = SQL_CODER_DEFAULT_SCHEMA):
if schema == "<MY_DATABASE_SCHEMA>" or schema == "":
schema = SQL_CODER_DEFAULT_SCHEMA
def fn(msgs):
return _sqlcoder_template_messages(msgs, schema=schema)
fn.__name__ = "sqlcoder_template_messages"
return fn
def llama2_template_messages(msgs: List[Dict[str, str]]) -> str:
if len(msgs) == 0:
return ""

View file

@ -86,21 +86,28 @@ def escape_string(string: str) -> str:
return string.replace('"', '\\"').replace("'", "\\'")
def display_val(v: Any):
def display_val(v: Any, k: str = None):
if k == "template_messages":
return v
if isinstance(v, str):
return f'"{escape_string(v)}"'
return str(v)
def is_default(llm, k, v):
if k == "template_messages" and llm.__fields__[k].default is not None:
return llm.__fields__[k].default.__name__ == v
return v == llm.__fields__[k].default
def display_llm_class(llm, new: bool = False):
sep = ",\n\t\t\t"
args = sep.join(
[
f"{k}={display_val(v)}"
f"{k}={display_val(v, k)}"
for k, v in llm.dict().items()
if k not in filtered_attrs
and v is not None
and not v == llm.__fields__[k].default
if k not in filtered_attrs and v is not None and not is_default(llm, k, v)
]
)
return f"{llm.__class__.__name__}(\n\t\t\t{args}\n\t\t)"
@ -124,6 +131,10 @@ def create_string_node(string: str) -> redbaron.RedBaron:
return redbaron.RedBaron(f'"{string}"')[0]
def create_literal_node(literal: str) -> redbaron.RedBaron:
return redbaron.RedBaron(literal)[0]
def create_float_node(float: float) -> redbaron.RedBaron:
return redbaron.RedBaron(f"{float}")[0]

View file

@ -11,7 +11,11 @@ from uvicorn.main import Server
from ..core.main import ContextItem
from ..core.models import ALL_MODEL_ROLES, MODEL_CLASSES, MODEL_MODULE_NAMES
from ..core.steps import DisplayErrorStep
from ..libs.llm.prompts.chat import llama2_template_messages, template_alpaca_messages
from ..libs.llm.prompts.chat import (
llama2_template_messages,
sqlcoder_template_messages,
template_alpaca_messages,
)
from ..libs.util.create_async_task import create_async_task
from ..libs.util.edit_config import (
add_config_import,
@ -347,9 +351,12 @@ class GUIProtocolServer:
# Set and start the new default model
if "template_messages" in model:
sqtm = sqlcoder_template_messages("<MY_DATABASE_SCHEMA>")
sqtm.__name__ = 'sqlcoder_template_messages("<MY_DATABASE_SCHEMA>")'
model["template_messages"] = {
"llama2_template_messages": llama2_template_messages,
"template_alpaca_messages": template_alpaca_messages,
"sqlcoder_template_messages": sqtm,
}[model["template_messages"]]
new_model = MODEL_CLASSES[model_class](**model)
models.default = new_model