✅ unit tests for chat templates

This commit is contained in:
Nate Sesti 2023-11-18 10:58:52 -08:00
parent c1c289fc19
commit f733627fdb
16 changed files with 236 additions and 141 deletions

View file

@ -29,7 +29,7 @@ class ChatMessage(ContinueBaseModel):
return values.get("content", "")
return summary
def to_dict(self, with_functions: bool) -> Dict[str, str]:
def to_dict(self, with_functions: bool = False) -> Dict[str, str]:
d = self.dict()
del d["summary"]
if d["function_call"] is not None:

View file

@ -624,8 +624,7 @@ Please output the code to be inserted at the cursor in order to fulfill the user
temperature=sdk.config.completion_options.temperature,
max_tokens=min(max_tokens, model_to_use.context_length // 2),
):
if "content" in chunk:
yield chunk["content"]
yield chunk.content
generator = gen()

View file

@ -1,7 +1,7 @@
from typing import Any, Dict
from ....models.main import ContinueBaseModel
from chromadb.types import Metadata
from ....models.main import ContinueBaseModel
class ChunkWithoutID(ContinueBaseModel):
content: str

View file

@ -122,7 +122,7 @@ class ChromaCodebaseIndex(CodebaseIndex):
name = re.sub("[^a-z0-9._-]", "a", name)
# Replace consecutive dots with a single dot
name = re.sub("\.\.+", ".", name)
name = re.sub("\\.\\.+", ".", name)
return name

View file

@ -1,8 +1,9 @@
from typing import Any, Coroutine, Optional
from typing import Any, Callable, Coroutine, Optional
from anthropic import AI_PROMPT, HUMAN_PROMPT, AsyncAnthropic
from .base import LLM, CompletionOptions
from .prompts.chat import anthropic_template_messages
class AnthropicLLM(LLM):
@ -29,6 +30,8 @@ class AnthropicLLM(LLM):
model: str = "claude-2"
template_messages: Callable = anthropic_template_messages
class Config:
arbitrary_types_allowed = True

View file

@ -41,15 +41,16 @@ class GGML(LLM):
)
api_type: Optional[Literal["azure", "openai"]] = Field(
None, description="OpenAI API type."
default=None, description="OpenAI API type."
)
api_version: Optional[str] = Field(
None, description="OpenAI API version. For use with Azure OpenAI Service."
default=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."
default=None, description="OpenAI engine. For use with Azure OpenAI Service."
)
class Config:
@ -131,7 +132,11 @@ class GGML(LLM):
async with self.create_client_session() as client_session:
async with client_session.post(
self.get_full_server_url(endpoint="chat/completions"),
json={"messages": messages, "stream": True, **args},
json={
"messages": [msg.to_dict() for msg in messages],
"stream": True,
**args,
},
headers=self.get_headers(),
proxy=self.request_options.proxy,
) as resp:

View file

@ -1,27 +1,29 @@
from textwrap import dedent
from typing import Dict, List
from typing import List
from anthropic import AI_PROMPT, HUMAN_PROMPT
from ....core.main import ChatMessage
def anthropic_template_messages(messages: List[Dict[str, str]]) -> str:
def anthropic_template_messages(messages: List[ChatMessage]) -> str:
prompt = ""
# Anthropic prompt must start with a Human turn
if (
len(messages) > 0
and messages[0]["role"] != "user"
and messages[0]["role"] != "system"
and messages[0].role != "user"
and messages[0].role != "system"
):
prompt += f"{HUMAN_PROMPT} Hello."
for msg in messages:
prompt += f"{HUMAN_PROMPT if (msg['role'] == 'user' or msg['role'] == 'system') else AI_PROMPT} {msg['content']} "
prompt += f"{HUMAN_PROMPT if (msg.role == 'user' or msg.role == 'system') else AI_PROMPT} {msg.content} "
prompt += AI_PROMPT
return prompt
def zephyr_template_messages(msgs: List[Dict[str, str]]) -> str:
def zephyr_template_messages(msgs: List[ChatMessage]) -> str:
""" "
<|system|>
</s>
@ -31,65 +33,65 @@ def zephyr_template_messages(msgs: List[Dict[str, str]]) -> str:
"""
prompt = ""
if msgs[0]["role"] == "system":
prompt += f"<|system|>{msgs[0]['content']}</s>\n"
if msgs[0].role == "system":
prompt += f"<|system|>{msgs[0].content}</s>\n"
msgs.pop(0)
else:
prompt += "<|system|> </s>\n"
for msg in msgs:
prompt += "<|user|>\n" if msg["role"] == "user" else "<|assistant|>\n"
prompt += f"{msg['content']}</s>\n"
prompt += "<|user|>\n" if msg.role == "user" else "<|assistant|>\n"
prompt += f"{msg.content}</s>\n"
prompt += "<|assistant|>\n"
return prompt
def chatml_template_messages(messages: List[Dict[str, str]]) -> str:
def chatml_template_messages(messages: List[ChatMessage]) -> str:
prompt = ""
for msg in messages:
prompt += f"<|im_start|>{msg['role']}\n{msg['content']}<|im_end|>\n"
prompt += f"<|im_start|>{msg.role}\n{msg.content}<|im_end|>\n"
prompt += "<|im_start|>assistant\n"
return prompt
def template_alpaca_messages(msgs: List[Dict[str, str]]) -> str:
def template_alpaca_messages(msgs: List[ChatMessage]) -> str:
prompt = ""
if msgs[0]["role"] == "system":
prompt += f"{msgs[0]['content']}\n\n"
if msgs[0].role == "system":
prompt += f"{msgs[0].content}\n\n"
msgs.pop(0)
for msg in msgs:
prompt += "### Instruction:\n" if msg["role"] == "user" else "### Response:\n"
prompt += f"{msg['content']}\n\n"
prompt += "### Instruction:\n" if msg.role == "user" else "### Response:\n"
prompt += f"{msg.content}\n\n"
prompt += "### Response:\n"
return prompt
def phind_template_messages(msgs: List[Dict[str, str]]) -> str:
def phind_template_messages(msgs: List[ChatMessage]) -> str:
prompt = ""
if msgs[0]["role"] == "system":
prompt += f"### System Prompt\n{msgs[0]['content']}\n\n"
if msgs[0].role == "system":
prompt += f"### System Prompt\n{msgs[0].content}\n\n"
msgs.pop(0)
for msg in msgs:
prompt += "### User Message\n" if msg["role"] == "user" else "### Assistant\n"
prompt += f"{msg['content']}\n"
prompt += "### User Message\n" if msg.role == "user" else "### Assistant\n"
prompt += f"{msg.content}\n"
prompt += "### Assistant\n"
return prompt
def raw_input_template(msgs: List[Dict[str, str]]) -> str:
return msgs[-1]["content"]
def raw_input_template(msgs: List[ChatMessage]) -> str:
return msgs[-1].content
SQL_CODER_DEFAULT_SCHEMA = """\
@ -135,9 +137,9 @@ CREATE TABLE product_suppliers (
def _sqlcoder_template_messages(
msgs: List[Dict[str, str]], schema: str = SQL_CODER_DEFAULT_SCHEMA
msgs: List[ChatMessage], schema: str = SQL_CODER_DEFAULT_SCHEMA
) -> str:
question = msgs[-1]["content"]
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:
@ -167,19 +169,19 @@ def sqlcoder_template_messages(schema: str = SQL_CODER_DEFAULT_SCHEMA):
return fn
def llama2_template_messages(msgs: List[Dict[str, str]]) -> str:
def llama2_template_messages(msgs: List[ChatMessage]) -> str:
if len(msgs) == 0:
return ""
if msgs[0]["role"] == "assistant":
if msgs[0].role == "assistant":
# These models aren't trained to handle assistant message coming first,
# and typically these are just introduction messages from Continue
msgs.pop(0)
prompt = ""
has_system = msgs[0]["role"] == "system"
has_system = msgs[0].role == "system"
if has_system and msgs[0]["content"].strip() == "":
if has_system and msgs[0].content.strip() == "":
has_system = False
msgs = msgs[1:]
@ -187,39 +189,39 @@ def llama2_template_messages(msgs: List[Dict[str, str]]) -> str:
system_message = dedent(
f"""\
<<SYS>>
{msgs[0]["content"]}
{msgs[0].content}
<</SYS>>
"""
)
if len(msgs) > 1:
prompt += f"[INST] {system_message}{msgs[1]['content']} [/INST]"
prompt += f"[INST] {system_message}{msgs[1].content} [/INST]"
else:
prompt += f"[INST] {system_message} [/INST]"
return prompt
for i in range(2 if has_system else 0, len(msgs)):
if msgs[i]["role"] == "user":
prompt += f"[INST] {msgs[i]['content']} [/INST]"
if msgs[i].role == "user":
prompt += f"[INST] {msgs[i].content} [/INST]"
else:
prompt += msgs[i]["content"] + " "
prompt += msgs[i].content + " "
return prompt
def code_llama_template_messages(msgs: List[Dict[str, str]]) -> str:
return f"[INST] {msgs[-1]['content']}\n[/INST]"
def code_llama_template_messages(msgs: List[ChatMessage]) -> str:
return f"[INST] {msgs[-1].content}\n[/INST]"
def extra_space_template_messages(msgs: List[Dict[str, str]]) -> str:
return f" {msgs[-1]['content']}"
def extra_space_template_messages(msgs: List[ChatMessage]) -> str:
return f" {msgs[-1].content}"
def code_llama_python_template_messages(msgs: List[Dict[str, str]]) -> str:
def code_llama_python_template_messages(msgs: List[ChatMessage]) -> str:
return dedent(
f"""\
[INST]
You are an expert Python programmer and personal assistant, here is your task: {msgs[-1]['content']}
You are an expert Python programmer and personal assistant, here is your task: {msgs[-1].content}
Your answer should start with a [PYTHON] tag and end with a [/PYTHON] tag.
[/INST]"""
)

View file

@ -53,7 +53,7 @@ class ProxyServer(LLM):
async with self.create_client_session() as session:
async with session.post(
f"{SERVER_URL}/stream_chat",
json={"messages": messages, **args},
json={"messages": [msg.to_dict() for msg in messages], **args},
headers=self.get_headers(),
proxy=self.request_options.proxy,
) as resp:

View file

@ -210,8 +210,8 @@ def flatten_messages(msgs: List[ChatMessage]) -> List[ChatMessage]:
"""If there are multiple adjacent messages with same "role", combine them"""
flattened = []
for msg in msgs:
if len(flattened) > 0 and flattened[-1]["role"] == msg.role:
flattened[-1]["content"] += "\n\n" + (msg.content or "")
if len(flattened) > 0 and flattened[-1].role == msg.role:
flattened[-1].content += "\n\n" + (msg.content or "")
else:
flattened.append(msg)

View file

@ -55,7 +55,7 @@ class BaseCompletionOptions(ContinueBaseModel):
default=None, description="The stop tokens of the completion."
)
max_tokens: int = Field(
default=None,
default=1023,
description="The maximum number of tokens to generate.",
)

View file

@ -57,8 +57,8 @@ class HighlightedCodeContextProvider(ContextProvider):
content = await self.ide.readFile(visible_files[0])
rif = RangeInFileWithContents.from_entire_file(visible_files[0], content)
item = self._rif_to_context_item(rif, 0, True)
item.description.name = self._rif_to_name(rif, show_line_nums=False)
item = self.rif_to_context_item(rif, 0, True)
item.description.name = self.rif_to_name(rif, show_line_nums=False)
self.last_added_fallback = True
return HighlightedRangeContextItem(rif=rif, item=item)
@ -119,14 +119,14 @@ class HighlightedCodeContextProvider(ContextProvider):
for hr in self.highlighted_ranges:
basename = os.path.basename(hr.rif.filepath)
if len(name_status[basename]) > 1:
hr.item.description.name = self._rif_to_name(
hr.item.description.name = self.rif_to_name(
hr.rif,
display_filename=os.path.join(
os.path.basename(os.path.dirname(hr.rif.filepath)), basename
),
)
else:
hr.item.description.name = self._rif_to_name(
hr.item.description.name = self.rif_to_name(
hr.rif, display_filename=basename
)
@ -142,8 +142,8 @@ class HighlightedCodeContextProvider(ContextProvider):
self.should_get_fallback_context_item = True
self.last_added_fallback = False
def _rif_to_name(
self,
@staticmethod
def rif_to_name(
rif: RangeInFileWithContents,
display_filename: Optional[str] = None,
show_line_nums: bool = True,
@ -155,14 +155,15 @@ class HighlightedCodeContextProvider(ContextProvider):
)
return f"{display_filename or os.path.basename(rif.filepath)}{line_nums}"
def _rif_to_context_item(
self, rif: RangeInFileWithContents, idx: int, editing: bool
@staticmethod
def rif_to_context_item(
rif: RangeInFileWithContents, idx: int, editing: bool
) -> ContextItem:
return ContextItem(
description=ContextItemDescription(
name=self._rif_to_name(rif),
name=HighlightedCodeContextProvider.rif_to_name(rif),
description=rif.filepath,
id=ContextItemId(provider_title=self.title, item_id=str(idx)),
id=ContextItemId(provider_title="code", item_id=str(idx)),
),
content=rif.contents,
editing=editing if editing is not None else False,
@ -203,7 +204,7 @@ class HighlightedCodeContextProvider(ContextProvider):
self.highlighted_ranges = [
HighlightedRangeContextItem(
rif=range_in_files[0],
item=self._rif_to_context_item(
item=self.rif_to_context_item(
range_in_files[0], 0, edit or False
),
)
@ -235,7 +236,7 @@ class HighlightedCodeContextProvider(ContextProvider):
new_ranges.append(
HighlightedRangeContextItem(
rif=new_hr,
item=self._rif_to_context_item(
item=self.rif_to_context_item(
new_hr, len(self.highlighted_ranges) + i, edit
),
)

View file

@ -1,3 +1,5 @@
from typing import List
from ...core.main import ContextItem, SessionUpdate
from .gui_protocol import AbstractGUIProtocolServer
@ -10,5 +12,8 @@ class CommandLineGUI(AbstractGUIProtocolServer):
async def send_indexing_progress(self, progress: float):
print(f"Indexing... {int(progress*100)}%")
context_items: List[ContextItem] = []
async def add_context_item(self, item: ContextItem):
...
self.context_items.append(item)
print(f"Added context item {item.description}")

View file

@ -0,0 +1,87 @@
import pytest
from continuedev.core.main import ChatMessage
from continuedev.libs.llm.prompts.chat import (
anthropic_template_messages,
chatml_template_messages,
code_llama_template_messages,
llama2_template_messages,
phind_template_messages,
template_alpaca_messages,
zephyr_template_messages,
)
@pytest.mark.parametrize(
"template,expected",
[
(
template_alpaca_messages,
"""Always be kind
### Instruction:
Hello!
### Response:
""",
),
(
zephyr_template_messages,
"""<|system|>Always be kind</s>
<|user|>
Hello!</s>
<|assistant|>
""",
),
(
chatml_template_messages,
"""<|im_start|>system
Always be kind<|im_end|>
<|im_start|>user
Hello!<|im_end|>
<|im_start|>assistant
""",
),
(
phind_template_messages,
"""### System Prompt
Always be kind
### User Message
Hello!
### Assistant
""",
),
(
anthropic_template_messages,
"""
Human: Always be kind
Human: Hello!
Assistant:""",
),
(
llama2_template_messages,
"""[INST] <<SYS>>
Always be kind
<</SYS>>
Hello! [/INST]""",
),
(
code_llama_template_messages,
"""[INST] Hello!
[/INST]""",
),
],
)
def test_template_messages(template, expected):
templated = template(
[
ChatMessage(role="system", content="Always be kind"),
ChatMessage(role="user", content="Hello!"),
]
)
print(templated)
assert templated == expected

View file

@ -16,14 +16,11 @@ from util.prompts import tokyo_test_pair
load_dotenv()
SPEND_MONEY = True
SPEND_MONEY = False
def start_model(model):
def write_log(msg: str):
pass
asyncio.run(model.start(write_log=write_log, unique_id="test_unique_id"))
def start_model(model: LLM):
asyncio.run(model.start(unique_id="test_unique_id"))
def async_test(func):
@ -39,14 +36,14 @@ class TestBaseLLM:
context_length = 4096
system_message = "test_system_message"
def setup_class(cls):
cls.llm = LLM(
model=cls.model,
context_length=cls.context_length,
system_message=cls.system_message,
def setup_class(self):
self.llm = LLM(
model=self.model,
context_length=self.context_length,
system_message=self.system_message,
)
start_model(cls.llm)
start_model(self.llm)
def test_llm_is_instance(self):
assert isinstance(self.llm, LLM)
@ -84,11 +81,9 @@ class TestBaseLLM:
],
temperature=0.0,
):
assert isinstance(chunk, dict)
if "content" in chunk:
completion += chunk["content"]
if "role" in chunk:
role = chunk["role"]
assert isinstance(chunk, ChatMessage)
completion += chunk.content
role = chunk.role
assert role == "assistant"
assert completion.strip().lower() == tokyo_test_pair[1]
@ -110,16 +105,16 @@ class TestBaseLLM:
class TestOpenAI(TestBaseLLM):
def setup_class(cls):
super().setup_class(cls)
cls.llm = OpenAI(
model=cls.model,
context_length=cls.context_length,
system_message=cls.system_message,
def setup_class(self):
super().setup_class(self) # type: ignore
self.llm = OpenAI(
model=self.model,
context_length=self.context_length,
system_message=self.system_message,
api_key=os.environ["OPENAI_API_KEY"],
# api_base=f"http://localhost:{port}",
)
start_model(cls.llm)
start_model(self.llm)
# cls.server = start_openai(port=port)
# def teardown_class(cls):
@ -136,33 +131,33 @@ class TestOpenAI(TestBaseLLM):
class TestGGML(TestBaseLLM):
def setup_class(cls):
super().setup_class(cls)
cls.llm = GGML(
def setup_class(self):
super().setup_class(self) # type: ignore
self.llm = GGML(
model="gpt-3.5-turbo",
context_length=cls.context_length,
system_message=cls.system_message,
context_length=self.context_length,
system_message=self.system_message,
api_base="https://api.openai.com",
api_key=os.environ["OPENAI_API_KEY"],
)
start_model(cls.llm)
start_model(self.llm)
@pytest.mark.skipif(True, reason="Together is not working")
class TestTogetherLLM(TestBaseLLM):
def setup_class(cls):
super().setup_class(cls)
cls.llm = TogetherLLM(
def setup_class(self):
super().setup_class(self) # type: ignore
self.llm = TogetherLLM(
api_key=os.environ["TOGETHER_API_KEY"],
)
start_model(cls.llm)
start_model(self.llm)
class TestAnthropicLLM(TestBaseLLM):
def setup_class(cls):
super().setup_class(cls)
cls.llm = AnthropicLLM(api_key=os.environ["ANTHROPIC_API_KEY"])
start_model(cls.llm)
def setup_class(self):
super().setup_class(self) # type: ignore
self.llm = AnthropicLLM(api_key=os.environ["ANTHROPIC_API_KEY"])
start_model(self.llm)
def test_llm_collect_args(self):
options = CompletionOptions(model=self.model)

View file

@ -1,9 +1,11 @@
import pytest
from continuedev.core.config import ContinueConfig
from continuedev.core.steps import UserInputStep
from continuedev.headless import start_headless_session
from continuedev.headless import get_headless_autopilot
from continuedev.models.filesystem import Range, RangeInFileWithContents
from continuedev.plugins.steps.chat import SimpleChatStep
from continuedev.plugins.context_providers.highlighted_code import (
HighlightedCodeContextProvider,
)
from continuedev.plugins.steps.main import EditHighlightedCodeStep
from continuedev.plugins.steps.on_traceback import DefaultOnTracebackStep
from util.prompts import dotenv_test_pair, tokyo_test_pair
@ -14,55 +16,44 @@ TEST_CONFIG = ContinueConfig()
@pytest.mark.asyncio
async def test_step():
pytest.skip("TODO: too slow")
session = await start_headless_session(config=TEST_CONFIG)
autopilot = await get_headless_autopilot(config=TEST_CONFIG)
await session.autopilot.run_from_step(UserInputStep(user_input=tokyo_test_pair[0]))
await autopilot.run(UserInputStep(user_input=tokyo_test_pair[0]))
full_state = await session.autopilot.get_full_state()
state = autopilot.session_state
assert isinstance(full_state.history.timeline[-1].step, SimpleChatStep)
assert not full_state.history.timeline[-1].step.hide
assert (
full_state.history.timeline[-1].step.description.strip().lower()
== tokyo_test_pair[1]
)
await session.autopilot.cleanup()
assert state.history[-1].step_type == "SimpleChatStep"
assert not state.history[-1].hide
assert state.history[-1].description.strip().lower() == tokyo_test_pair[1]
@pytest.mark.asyncio
async def test_traceback_step():
pytest.skip("TODO: too slow")
session = await start_headless_session(config=TEST_CONFIG)
autopilot = await get_headless_autopilot(config=TEST_CONFIG)
await session.autopilot.run_from_step(
DefaultOnTracebackStep(output=dotenv_test_pair[0])
)
await autopilot.run(DefaultOnTracebackStep(output=dotenv_test_pair[0]))
full_state = await session.autopilot.get_full_state()
assert dotenv_test_pair[1] in full_state.history.timeline[-1].step.description
await session.autopilot.cleanup()
state = autopilot.session_state
assert dotenv_test_pair[1] in state.history[-1].description
@pytest.mark.asyncio
async def test_edit_step():
pytest.skip("TODO: too slow")
session = await start_headless_session(config=TEST_CONFIG)
autopilot = await get_headless_autopilot(config=TEST_CONFIG)
sdk = autopilot.sdk
range_in_file = RangeInFileWithContents(
filepath=__file__, range=Range.from_shorthand(0, 0, 0, 0), contents=""
)
await session.autopilot.handle_highlighted_code(range_in_files=[range_in_file])
await session.autopilot.run_from_step(
EditHighlightedCodeStep(user_input="Don't edit this code")
await sdk.add_context_item(
HighlightedCodeContextProvider.rif_to_context_item(range_in_file, 0, True)
)
full_state = await session.autopilot.get_full_state()
assert isinstance(full_state.history.timeline[-1].step.description, str)
await autopilot.run(EditHighlightedCodeStep(user_input="Don't edit this code"))
await session.autopilot.cleanup()
state = autopilot.session_state
assert (
isinstance(state.history[-1].description, str)
and len(state.history[-1].description) > 0
)

View file

@ -1,9 +1,16 @@
import os
import re
from continuedev.libs.util.errors import format_exc
class TestUtils:
def test_get_random_string(self):
current_file_path = os.path.abspath(__file__)
try:
raise Exception("test")
except Exception as e:
assert format_exc(e) == ""
assert re.match(
rf'Traceback \(most recent call last\):\n\n File "{re.escape(current_file_path)}", line \d+, in test_get_random_string\n raise Exception\("test"\)\n\nException: test\n',
format_exc(e),
)