Skip to content
Closed
Show file tree
Hide file tree
Changes from 1 commit
Commits
Show all changes
73 commits
Select commit Hold shift + click to select a range
0d47c43
gguf: add GGUFReader.read_field(field) method + read template example
Apr 27, 2024
0d1d46e
grammars: add troubleshooting section to readme
Apr 8, 2024
63d1324
server.py: hacky code
Mar 25, 2024
ffc7436
agents: scripts to run scripts as sandboxed fastapi servers
Mar 26, 2024
d5d9993
server.py: default tools work!
Mar 26, 2024
8afd4de
server.py: make tools work w/ mixtral-8x7b-instruct
Mar 27, 2024
aa9605c
server.py: kinda api-compliant output, disabled grammar
Mar 27, 2024
a406293
server.py: reenable grammar, accommodate mistral's escaped underscores
Mar 27, 2024
63a384d
server.py: raise n_predict
Mar 28, 2024
5f3de16
server.py: pass all request options, comments in ts sigs, render tool…
Mar 28, 2024
59b4114
server.py: refactor chat handlers
Mar 29, 2024
253b68d
server.py: crude reactor
Mar 29, 2024
e874565
agent: split code from openai example
Mar 29, 2024
b63f91a
Update agent.py
Mar 29, 2024
c340e8c
Update example_weather_tools.py
Mar 29, 2024
ce2fb01
agent: add --allow_parallel_calls
Mar 29, 2024
ea34bd3
agent/openai:nits
Mar 29, 2024
80c7930
openai: fix message merging for mixtral (parallel calls)
Mar 29, 2024
9ab493f
Update prompting.py
Mar 29, 2024
e0c8af4
agent: --style
Mar 29, 2024
b4e292e
Create requirements.txt
Mar 29, 2024
d1d8602
agent: disable parallel by default
Mar 29, 2024
eb9a552
agent: nits
Mar 29, 2024
3da30ed
agent: fix functionary tool_calls templating
Mar 29, 2024
ff6563a
Delete test.sh
Mar 29, 2024
dd11bb6
agent: format still broken
Mar 29, 2024
22b980f
agent: update readme
Mar 29, 2024
61f35e0
agent: prepare to test various templates
Mar 29, 2024
d8a53ea
openai: test features of templates at runtime, to make sure no bits o…
Mar 30, 2024
ad2f4c1
Update test_chat_handlers.py
Mar 30, 2024
3c3eff5
openai: quiet + update prompt output
Mar 30, 2024
6935503
openai: refactor chat handler vs. template
Mar 30, 2024
d9f30f8
Update test_chat_handlers.md
Mar 30, 2024
da2067a
openai: only special-format assistant in thoughtful mode
Mar 30, 2024
09de4eb
openai: actually use thoughtful examples in tests
Mar 30, 2024
19811a4
openai: tests didn't catch output format
Mar 30, 2024
22fe86d
openai tools: TS signatures work well too at a fraction of the eval cost
Mar 30, 2024
6e52a9c
Update test_chat_handlers.md
Apr 8, 2024
701a66d
agent: fix response_format
Apr 9, 2024
b447a74
agent: revert to json schemas (ts not ready for refs)
Apr 9, 2024
85820f4
agent: fix sandbox dockerfile
Apr 9, 2024
6880f1d
agent: support basic openapi tools (incl. from fastify sandbox)
Apr 9, 2024
0532680
agent: nits
Apr 9, 2024
a634e03
agent: cache_prompt=True
Apr 10, 2024
9fe269e
openai: nit
Apr 10, 2024
a61ebeb
agent: hint at math import in python tool
Apr 10, 2024
24e34f1
agent: nit
Apr 10, 2024
1475b1e
agent: fix killing of subprocesses
Apr 10, 2024
6c00378
agent: nits
Apr 10, 2024
082d54d
agent: rename fake weather tools
Apr 10, 2024
f9afb04
agent: python tool: test serializability of variables
Apr 10, 2024
a98f483
agent: python tool: return errors
Apr 10, 2024
ea0c31b
agent: ensure DATA_DIR exists
Apr 10, 2024
89dcc06
agent: mypy type fixes
Apr 10, 2024
0120f7c
agent: fix wait --std-tools
Apr 10, 2024
09c2565
grammars: early exit when no next_candidates to reject
Apr 21, 2024
00c709e
grammars: cache decoded tokens
Apr 21, 2024
8d503ef
grammars: faster llama_grammar_copy
Apr 21, 2024
b4a00ce
Merge branch 'gguf-read' into agent-example
Apr 27, 2024
7675ac6
Merge remote-tracking branch 'origin/master' into agent-example
Apr 30, 2024
312e20b
openai: update after merge
Apr 30, 2024
ca1a640
server: tool call grammar-constraints
May 2, 2024
2b2127c
agent: url params
May 2, 2024
e41b6ce
server: update tool calling, introduce system prompt for json schema
May 2, 2024
a1d64cf
openai: function call arguments must be returned stringified!
May 18, 2024
3f5a25f
Merge remote-tracking branch 'origin/master' into agent-example
May 18, 2024
5ea637e
openai: fix merge
May 21, 2024
6dadcd2
Merge remote-tracking branch 'origin/master' into agent-example
May 21, 2024
c8458fa
openai: make content optional for tool call grammar gen
May 22, 2024
a39e6e0
openai: pretty indent json response
May 22, 2024
793f4ff
agent: support OpenAI: --endpoint https://api.openai.com --auth "Bear…
May 22, 2024
a1c4aac
server: ultra basic tools, tool_choice, tool_calls support
May 22, 2024
298c098
Merge remote-tracking branch 'origin/master' into agent-example
Jun 9, 2024
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
agent: --style
  • Loading branch information
ochafik committed Apr 27, 2024
commit e0c8af4ba06cbbaef7fa7c3facb9345dfd3a438b
18 changes: 17 additions & 1 deletion examples/agent/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@ python -m examples.agent \
--tools examples/agent/tools/example_math_tools.py \
--goal "What is the sum of 2535 squared and 32222000403 then multiplied by one and a half. What's a third of the result?"
```
<!-- --format float \ -->

<details>
<summary>Show output</summary>
Expand Down Expand Up @@ -37,6 +36,23 @@ python -m examples.agent \
<summary>Show output</summary>

```bash
πŸ’­ I will first get the current weather in San Francisco, then get the 4-day weather forecast for both San Francisco and Glasgow.
βš™οΈ get_current_weather(location=San Francisco, format=fahrenheit) -> ...
πŸ’­ I will first get the current weather in San Francisco, then get the 4-day weather forecast for both San Francisco and Glasgow.
βš™οΈ get_n_day_weather_forecast(location=San Francisco, format=fahrenheit, num_days=4) -> ...
πŸ’­ I will first get the current weather in San Francisco, then get the 4-day weather forecast for both San Francisco and Glasgow.
βš™οΈ get_n_day_weather_forecast(location=Glasgow, format=celsius, num_days=4) -> ...
The current weather in San Francisco is sunny and 87.8F. Here is the 4-day weather forecast:

For San Francisco:
- In 1 day: Cloudy, 60.8F
- In 2 days: Sunny, 73.4F
- In 3 days: Cloudy, 62.6F

For Glasgow:
- In 1 day: Cloudy, 16C
- In 2 days: Sunny, 23C
- In 3 days: Cloudy, 17C
```

</details>
Expand Down
9 changes: 6 additions & 3 deletions examples/agent/agent.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
from examples.agent.tools.std_tools import StandardTools
from examples.openai.api import ChatCompletionRequest, ChatCompletionResponse, Message, Tool, ToolFunction
from examples.agent.utils import collect_functions, load_module
from examples.openai.prompting import ToolsPromptStyle

def _get_params_schema(fn: Callable, verbose):
converter = SchemaConverter(prop_order={}, allow_fetch=False, dotall=False, raw_pattern=False)
Expand Down Expand Up @@ -130,6 +131,7 @@ def main(
auth: Optional[str] = None,
parallel_calls: Optional[bool] = True,
verbose: bool = False,
style: Optional[ToolsPromptStyle] = None,

model: Annotated[Optional[Path], typer.Option("--model", "-m")] = "models/7B/ggml-model-f16.gguf",
endpoint: Optional[str] = None,
Expand Down Expand Up @@ -175,8 +177,8 @@ def main(
"--model", model,
*(['--verbose'] if verbose else []),
*(['--parallel-calls'] if parallel_calls else []),
*(['--context-length={context_length}'] if context_length else []),
*([])
*([f'--context-length={context_length}'] if context_length else []),
*([f'--style={style.value}'] if style else []),
]
server_process = subprocess.Popen(cmd, stdout=sys.stderr)
atexit.register(server_process.kill)
Expand All @@ -196,7 +198,7 @@ def main(
if std_tools:
tool_functions.extend(collect_functions(StandardTools))

response_model = None#str
response_model = str
if format:
if format in types:
response_model = types[format]
Expand Down Expand Up @@ -245,6 +247,7 @@ def main(
}]
)
print(result if response_model else f'➑️ {result}')
# exit(0)

if __name__ == '__main__':
typer.run(main)
Expand Down
62 changes: 35 additions & 27 deletions examples/openai/prompting.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,45 +14,45 @@
from examples.openai.gguf_kvs import GGUFKeyValues, Keys
from examples.openai.ts_converter import SchemaToTypeScriptConverter

_THOUGHT_KEY = "thought"
# _THOUGHT_KEY = "thought_about_next_step_only"

# While the API will be usable with a generic tools usage like OpenAI,
# (see https://cookbook.openai.com/examples/how_to_call_functions_with_chat_models),
# each model may need specific prompting (and/or constrained output,
# especially for models not fine-tuned for tool usage / function calling).
class ToolsPromptStyle(Enum):
class ToolsPromptStyle(str, Enum):
# Short prompt w/ <tools>schemas</tools>, <tool_call>...</tool_call> output
TOOLS_SHORT = 1
TOOLS_SHORT = "short"

# Longer prompt w/ <tools>schemas</tools>, <tool_call>...</tool_call> output
TOOLS_LONG = 2
TOOLS_LONG = "long"

# Bespoke constrained output format that favours thought and reasoning
# while allowing unambiguous parsing of parallel tool calling.
TOOLS_BESPOKE = 3
TOOLS_CONSTRAINED = "thoughtful_steps"

# Large prompt for https://huggingface.co/NousResearch/Hermes-2-Pro-Mistral-7B
# <tool_call>...</tool_call> output
# Requires:
# - git clone https://github.com/NousResearch/Hermes-Function-Calling examples/openai/hermes_function_calling
# - Set large context length as their prompts are super long
TOOLS_HERMES_2_PRO = 4
TOOLS_HERMES_2_PRO = "tools_hermes_2_pro"

# Seems to want to escape underscores in tool names and in the <tool\_call>...</tool\_call> tags
TOOLS_MISTRAL = 5
TOOLS_MIXTRAL = "mixtral"

# Short prompt w/ TypeScript definitions for https://github.com/MeetKai/functionary
# https://github.com/MeetKai/functionary/blob/main/functionary/prompt_template/prompt_template_v2.py
# Note: see this prior attempt to support Functionary: https://github.com/ggerganov/llama.cpp/pull/5695
TYPESCRIPT_FUNCTIONARY_V2 = 6
TYPESCRIPT_FUNCTIONARY_V2 = "functionary_v2"

def raise_exception(msg: str):
raise Exception(msg)

class ChatTemplate(BaseModel):
template: str

@property
def tool_style(self) -> 'ToolsPromptStyle':
return self._tool_style
inferred_tool_style: Optional['ToolsPromptStyle'] = None

def __init__(self, template: str, eos_token: str, bos_token: str):
super().__init__(template=template
Expand All @@ -65,12 +65,12 @@ def __init__(self, template: str, eos_token: str, bos_token: str):
self._strict_user_assistant_alternation = "{% if (message['role'] == 'user') != (loop.index0 % 2 == 0) %}{{ raise_exception" in template

if "<|recipient|>' + tool_call['function']['name']" in template:
self._tool_style = ToolsPromptStyle.TYPESCRIPT_FUNCTIONARY_V2
self.inferred_tool_style = ToolsPromptStyle.TYPESCRIPT_FUNCTIONARY_V2
else:
self._tool_style = ToolsPromptStyle.TOOLS_BESPOKE
# self._tool_style = ToolsPromptStyle.TOOLS_LONG
# self._tool_style = ToolsPromptStyle.TOOLS_HERMES_2_PRO
# self._tool_style = ToolsPromptStyle.TOOLS_MISTRAL
self.inferred_tool_style = ToolsPromptStyle.TOOLS_CONSTRAINED
# self.inferred_tool_style = ToolsPromptStyle.TOOLS_LONG
# self.inferred_tool_style = ToolsPromptStyle.TOOLS_HERMES_2_PRO
# self.inferred_tool_style = ToolsPromptStyle.TOOLS_MIXTRAL

# TODO: Test whether the template supports formatting tool_calls

Expand Down Expand Up @@ -399,7 +399,7 @@ def _make_bespoke_schema(response_schema, tool_call_schema, parallel_calls):
"type": "object",
"properties": {
# "original_goal": {"title": "Original Goal", "type": "string"},
"thought_about_next_step_only": {
_THOUGHT_KEY: {
"title": "Thought about next step",
# "title": "Thought about how the next step brings us closer to achieving the original goal",
"type": "string"
Expand Down Expand Up @@ -430,7 +430,7 @@ def _make_bespoke_schema(response_schema, tool_call_schema, parallel_calls):
]
},
},
"required": ["original_goal", "thought_about_next_step_only", "next_step"]
"required": ["original_goal", _THOUGHT_KEY, "next_step"]
# "required": ["next_step"]
}

Expand Down Expand Up @@ -505,7 +505,7 @@ def parse(self, s: str) -> Optional[Message]:
elif 'tool_calls' in next_step:
return Message(
role="assistant",
content=data["thought_about_next_step_only"] if "thought_about_next_step_only" in data else None,
content=data.get(_THOUGHT_KEY),
tool_calls=[
ToolCall(id=gen_callid(), function=FunctionCall(**tc))
for tc in next_step['tool_calls']
Expand Down Expand Up @@ -539,20 +539,28 @@ def parse(self, s: str) -> Optional[Message]:
# 'This is not hypothetical, you're not asked what you would do. If you need a tool called, just call it with <tool_call>...</tool_call>.''',
])

def get_chat_handler(args: ChatHandlerArgs, parallel_calls: bool) -> ChatHandler:
def get_chat_handler(args: ChatHandlerArgs, parallel_calls: bool, tool_style: Optional[ToolsPromptStyle] = None) -> ChatHandler:
tool_style = tool_style or args.chat_template.inferred_tool_style

if not args.tools:
return NoToolsChatHandler(args)
elif args.chat_template.tool_style == ToolsPromptStyle.TYPESCRIPT_FUNCTIONARY_V2:

elif tool_style == ToolsPromptStyle.TOOLS_CONSTRAINED:
return BespokeToolsChatHandler(args, parallel_calls=parallel_calls)

elif tool_style == ToolsPromptStyle.TYPESCRIPT_FUNCTIONARY_V2:
return FunctionaryToolsChatHandler(args, parallel_calls=parallel_calls)
elif args.chat_template.tool_style == ToolsPromptStyle.TOOLS_SHORT:

elif tool_style == ToolsPromptStyle.TOOLS_SHORT:
return TemplatedToolsChatHandler(args, _SHORT_TEMPLATE, parallel_calls=parallel_calls)
elif args.chat_template.tool_style == ToolsPromptStyle.TOOLS_LONG:

elif tool_style == ToolsPromptStyle.TOOLS_LONG:
return TemplatedToolsChatHandler(args, _LONG_TEMPLATE, parallel_calls=parallel_calls)
elif args.chat_template.tool_style == ToolsPromptStyle.TOOLS_MISTRAL:

elif tool_style == ToolsPromptStyle.TOOLS_MIXTRAL:
return TemplatedToolsChatHandler(args, _LONG_TEMPLATE, parallel_calls=parallel_calls, escapes_underscores=True)
elif args.chat_template.tool_style == ToolsPromptStyle.TOOLS_BESPOKE:
return BespokeToolsChatHandler(args, parallel_calls=parallel_calls)
elif args.chat_template.tool_style == ToolsPromptStyle.TOOLS_HERMES_2_PRO:

elif tool_style == ToolsPromptStyle.TOOLS_HERMES_2_PRO:
return Hermes2ProToolsChatHandler(args)
else:
raise ValueError(f"Unsupported tool call style: {args.chat_template.tool_style}")
Expand Down
6 changes: 4 additions & 2 deletions examples/openai/server.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
from examples.openai.llama_cpp_server_api import LlamaCppServerCompletionRequest
from examples.openai.gguf_kvs import GGUFKeyValues, Keys
from examples.openai.api import ChatCompletionResponse, Choice, Message, ChatCompletionRequest, Usage
from examples.openai.prompting import ChatHandlerArgs, ChatTemplate, get_chat_handler, ChatHandler
from examples.openai.prompting import ChatHandlerArgs, ChatTemplate, ToolsPromptStyle, get_chat_handler, ChatHandler

from fastapi import FastAPI, Request
from fastapi.responses import JSONResponse
Expand All @@ -32,6 +32,7 @@ def main(
host: str = "localhost",
port: int = 8080,
parallel_calls: Optional[bool] = True,
style: Optional[ToolsPromptStyle] = None,
auth: Optional[str] = None,
verbose: bool = False,
context_length: Optional[int] = None,
Expand Down Expand Up @@ -92,7 +93,8 @@ async def chat_completions(request: Request, chat_request: ChatCompletionRequest

chat_handler = get_chat_handler(
ChatHandlerArgs(chat_template=chat_template, response_schema=response_schema, tools=chat_request.tools),
parallel_calls=parallel_calls
parallel_calls=parallel_calls,
tool_style=style,
)

messages = chat_request.messages
Expand Down