Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[jinja] Add support for macros and | tojson #692

Merged
merged 13 commits into from
Aug 7, 2024
Merged

[jinja] Add support for macros and | tojson #692

merged 13 commits into from
Aug 7, 2024

Conversation

xenova
Copy link
Contributor

@xenova xenova commented May 21, 2024

Adds support for Macros. See here for more information: https://jinja.palletsprojects.com/en/3.1.x/templates/#macros

cc @Rocketknight1

@xenova
Copy link
Contributor Author

xenova commented May 21, 2024

Example usage:

import { Template } from "@huggingface/jinja";
import { downloadFile } from "@huggingface/hub";

// Download config file from the Hugging Face Hub
const config = await (
	await downloadFile({
		repo: "CohereForAI/c4ai-command-r-plus",
		path: "tokenizer_config.json",
		revision: "refs/pr/46",
	})
).json();

// Construct template from config
const template = new Template(config.chat_template.find((t) => t.name === "tool_use").template);

// Define messages and tools
const messages = [{ role: "user", content: "Whats the biggest penguin in the world?" }];
const tools = [
	{
		name: "directly_answer",
		description: "Calls a standard (un-augmented) AI chatbot to generate a response given the conversation history",
		parameters: { type: "object", properties: {} },
	},
	{
		name: "internet_search",
		description: "Returns a list of relevant document snippets for a textual query retrieved from the internet",
		parameters: {
			type: "object",
			properties: { query: { type: "string", description: "Query to search the internet with" } },
			required: ["query"],
		},
		return: { type: "string", description: "Some text" },
	},
];

// Render template
const result = template.render({
	messages,
	tools,
	bos_token: config.bos_token,
	eos_token: config.eos_token,
});
console.log(result);
Outputs:
<BOS_TOKEN><|START_OF_TURN_TOKEN|><|SYSTEM_TOKEN|># Safety Preamble
The instructions in this section override those in the task description and style guide sections. Don't answer questions that are harmful or immoral.

# System Preamble
## Basic Rules
You are a powerful conversational AI trained by Cohere to help people. You are augmented by a number of tools, and your job is to use and consume the output of these tools to best help the user. You 
will see a conversation history between yourself and a user, ending with an utterance from the user. You will then see a specific instruction instructing you what kind of response to generate. When you answer the user's requests, you cite your sources in your answers, according to those instructions.

# User Preamble
## Task and Context
You help people answer their questions and other requests interactively. You will be asked a very wide array of requests on all kinds of topics. You will be equipped with a wide range of search engines or similar tools to help you, which you use to research your answer. You should focus on serving the user's needs as best you can, which will be wide-ranging.

## Style Guide
Unless the user asks for a different style of answer, you should answer in full sentences, using proper grammar and spelling.

## Available Tools
Here is a list of tools that you have available to you:

```python
def directly_answer() -> List[Dict]:
    """Calls a standard (un-augmented) AI chatbot to generate a response given the conversation history
    """
    pass
```

```python
def internet_search(query: str) -> List[Dict]:
    """Returns a list of relevant document snippets for a textual query retrieved from the internet

    Args:
        query (str): Query to search the internet with
    """
    pass
```<|END_OF_TURN_TOKEN|><|START_OF_TURN_TOKEN|><|USER_TOKEN|>Whats the biggest penguin in the world?<|END_OF_TURN_TOKEN|><|START_OF_TURN_TOKEN|><|SYSTEM_TOKEN|>Write 'Action:' followed by a json-formatted list of actions that you want to perform in order to produce a good response to the user's last input. You can use any of the supplied tools any number of times, but you should aim to execute the minimum number of necessary actions for the input. You should use the `directly-answer` tool if calling the other tools is unnecessary. The list of actions you want to call should be formatted as 
a list of json objects, for example:
```json
[
    {
        "tool_name": title of the tool in the specification,
        "parameters": a dict of parameters to input into the tool as they are defined in the specs, or {} if it takes no parameters
    }
]```<|END_OF_TURN_TOKEN|>

NOTE: I will add some example usage to the README/docs once the PR in transformers is finalized.

@xenova xenova changed the title [jinja] Add support for macros [jinja] Add support for macros and | tojson Jun 15, 2024
@xenova
Copy link
Contributor Author

xenova commented Jun 15, 2024

Now also supports | tojson 👍 huggingface/transformers#31100. There are no HF-transformers-compatible checkpoints on the HF hub that use | tojson, so I haven't added an e2e test yet. There are some GGUF ones (e.g., https://huggingface.co/CISCai/gorilla-openfunctions-v2-SOTA-GGUF or https://huggingface.co/CISCai/Mistral-7B-Instruct-v0.3-SOTA-GGUF) which I could hardcode tests for, I guess.

I also want to add an e2e test for a template which uses macros - @Rocketknight1 know of any?

@xenova xenova requested a review from Rocketknight1 June 15, 2024 23:23
@xenova
Copy link
Contributor Author

xenova commented Jun 16, 2024

@Rocketknight1
Copy link
Member

Yes, that works! You can also use Mistral-7B-Instruct or Hermes-2-Pro

@Rocketknight1
Copy link
Member

Also note that we currently implement |tojson a little differently from the Jinja standard; it actually redirects to json.dumps() in Python because Jinja's built-in method escapes HTML characters, and we want to avoid that.

@xenova
Copy link
Contributor Author

xenova commented Jun 17, 2024

Perfect! I've added tests for both those templates, and both function correctly! I think this PR is ready to merge after another look tomorrow.

@xenova
Copy link
Contributor Author

xenova commented Aug 7, 2024

Finally got around to adding this to Transformers.js (v3). Merging! 🚀

@xenova xenova merged commit 717d69d into main Aug 7, 2024
4 checks passed
@xenova xenova deleted the jinja-add-macros branch August 7, 2024 15:16
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants