Elffuss BraidHub

kikocis/llama-stack public

Support for Llama3.2 models and Swift SDK (#98)

Changeset5322cb26ca8d827a5cd9271e77cbdcfe8a59d51b6ff06e7d25a7c33840163749
AuthorAshwin Bharambe <ashwin.bharambe@gmail.com> · 2024-09-25 10:29 -07:00
CommitterGitHub <noreply@github.com> · 2024-09-25 10:29 -07:00
Parents5861f14bbd80

Browse the files at this changeset

57 files changed

modified .gitignore +7 −2
@@ -5,6 +5,11 @@
55 dev_requirements.txt
66 build
77 .DS_Store
8-.idea
9-*.iml
108 llama_stack/configs/*
9+xcuserdata/
10+*.hmap
11+.DS_Store
12+.build/
13+Package.resolved
14+*.pte
15+*.ipynb_checkpoints*
modified docs/cli_reference.md +99 −132
@@ -37,50 +37,74 @@
3737 You should see a table like this:
3838
3939 <pre style="font-family: monospace;">
40-+---------------------------------------+---------------------------------------------+----------------+----------------------------+
41-| Model Descriptor | HuggingFace Repo | Context Length | Hardware Requirements |
42-+---------------------------------------+---------------------------------------------+----------------+----------------------------+
43-| Meta-Llama3.1-8B | meta-llama/Meta-Llama-3.1-8B | 128K | 1 GPU, each >= 20GB VRAM |
44-+---------------------------------------+---------------------------------------------+----------------+----------------------------+
45-| Meta-Llama3.1-70B | meta-llama/Meta-Llama-3.1-70B | 128K | 8 GPUs, each >= 20GB VRAM |
46-+---------------------------------------+---------------------------------------------+----------------+----------------------------+
47-| Meta-Llama3.1-405B:bf16-mp8 | | 128K | 8 GPUs, each >= 120GB VRAM |
48-+---------------------------------------+---------------------------------------------+----------------+----------------------------+
49-| Meta-Llama3.1-405B | meta-llama/Meta-Llama-3.1-405B-FP8 | 128K | 8 GPUs, each >= 70GB VRAM |
50-+---------------------------------------+---------------------------------------------+----------------+----------------------------+
51-| Meta-Llama3.1-405B:bf16-mp16 | meta-llama/Meta-Llama-3.1-405B | 128K | 16 GPUs, each >= 70GB VRAM |
52-+---------------------------------------+---------------------------------------------+----------------+----------------------------+
53-| Meta-Llama3.1-8B-Instruct | meta-llama/Meta-Llama-3.1-8B-Instruct | 128K | 1 GPU, each >= 20GB VRAM |
54-+---------------------------------------+---------------------------------------------+----------------+----------------------------+
55-| Meta-Llama3.1-70B-Instruct | meta-llama/Meta-Llama-3.1-70B-Instruct | 128K | 8 GPUs, each >= 20GB VRAM |
56-+---------------------------------------+---------------------------------------------+----------------+----------------------------+
57-| Meta-Llama3.1-405B-Instruct:bf16-mp8 | | 128K | 8 GPUs, each >= 120GB VRAM |
58-+---------------------------------------+---------------------------------------------+----------------+----------------------------+
59-| Meta-Llama3.1-405B-Instruct | meta-llama/Meta-Llama-3.1-405B-Instruct-FP8 | 128K | 8 GPUs, each >= 70GB VRAM |
60-+---------------------------------------+---------------------------------------------+----------------+----------------------------+
61-| Meta-Llama3.1-405B-Instruct:bf16-mp16 | meta-llama/Meta-Llama-3.1-405B-Instruct | 128K | 16 GPUs, each >= 70GB VRAM |
62-+---------------------------------------+---------------------------------------------+----------------+----------------------------+
63-| Llama-Guard-3-8B | meta-llama/Llama-Guard-3-8B | 128K | 1 GPU, each >= 20GB VRAM |
64-+---------------------------------------+---------------------------------------------+----------------+----------------------------+
65-| Llama-Guard-3-8B:int8-mp1 | meta-llama/Llama-Guard-3-8B-INT8 | 128K | 1 GPU, each >= 10GB VRAM |
66-+---------------------------------------+---------------------------------------------+----------------+----------------------------+
67-| Prompt-Guard-86M | meta-llama/Prompt-Guard-86M | 128K | 1 GPU, each >= 1GB VRAM |
68-+---------------------------------------+---------------------------------------------+----------------+----------------------------+
40++----------------------------------+------------------------------------------+----------------+
41+| Model Descriptor | HuggingFace Repo | Context Length |
42++----------------------------------+------------------------------------------+----------------+
43+| Llama3.1-8B | meta-llama/Llama-3.1-8B | 128K |
44++----------------------------------+------------------------------------------+----------------+
45+| Llama3.1-70B | meta-llama/Llama-3.1-70B | 128K |
46++----------------------------------+------------------------------------------+----------------+
47+| Llama3.1-405B:bf16-mp8 | meta-llama/Llama-3.1-405B | 128K |
48++----------------------------------+------------------------------------------+----------------+
49+| Llama3.1-405B | meta-llama/Llama-3.1-405B-FP8 | 128K |
50++----------------------------------+------------------------------------------+----------------+
51+| Llama3.1-405B:bf16-mp16 | meta-llama/Llama-3.1-405B | 128K |
52++----------------------------------+------------------------------------------+----------------+
53+| Llama3.1-8B-Instruct | meta-llama/Llama-3.1-8B-Instruct | 128K |
54++----------------------------------+------------------------------------------+----------------+
55+| Llama3.1-70B-Instruct | meta-llama/Llama-3.1-70B-Instruct | 128K |
56++----------------------------------+------------------------------------------+----------------+
57+| Llama3.1-405B-Instruct:bf16-mp8 | meta-llama/Llama-3.1-405B-Instruct | 128K |
58++----------------------------------+------------------------------------------+----------------+
59+| Llama3.1-405B-Instruct | meta-llama/Llama-3.1-405B-Instruct-FP8 | 128K |
60++----------------------------------+------------------------------------------+----------------+
61+| Llama3.1-405B-Instruct:bf16-mp16 | meta-llama/Llama-3.1-405B-Instruct | 128K |
62++----------------------------------+------------------------------------------+----------------+
63+| Llama3.2-1B | meta-llama/Llama-3.2-1B | 128K |
64++----------------------------------+------------------------------------------+----------------+
65+| Llama3.2-3B | meta-llama/Llama-3.2-3B | 128K |
66++----------------------------------+------------------------------------------+----------------+
67+| Llama3.2-11B-Vision | meta-llama/Llama-3.2-11B-Vision | 128K |
68++----------------------------------+------------------------------------------+----------------+
69+| Llama3.2-90B-Vision | meta-llama/Llama-3.2-90B-Vision | 128K |
70++----------------------------------+------------------------------------------+----------------+
71+| Llama3.2-1B-Instruct | meta-llama/Llama-3.2-1B-Instruct | 128K |
72++----------------------------------+------------------------------------------+----------------+
73+| Llama3.2-3B-Instruct | meta-llama/Llama-3.2-3B-Instruct | 128K |
74++----------------------------------+------------------------------------------+----------------+
75+| Llama3.2-11B-Vision-Instruct | meta-llama/Llama-3.2-11B-Vision-Instruct | 128K |
76++----------------------------------+------------------------------------------+----------------+
77+| Llama3.2-90B-Vision-Instruct | meta-llama/Llama-3.2-90B-Vision-Instruct | 128K |
78++----------------------------------+------------------------------------------+----------------+
79+| Llama-Guard-3-11B-Vision | meta-llama/Llama-Guard-3-11B-Vision | 128K |
80++----------------------------------+------------------------------------------+----------------+
81+| Llama-Guard-3-1B:int4-mp1 | meta-llama/Llama-Guard-3-1B-INT4 | 128K |
82++----------------------------------+------------------------------------------+----------------+
83+| Llama-Guard-3-1B | meta-llama/Llama-Guard-3-1B | 128K |
84++----------------------------------+------------------------------------------+----------------+
85+| Llama-Guard-3-8B | meta-llama/Llama-Guard-3-8B | 128K |
86++----------------------------------+------------------------------------------+----------------+
87+| Llama-Guard-3-8B:int8-mp1 | meta-llama/Llama-Guard-3-8B-INT8 | 128K |
88++----------------------------------+------------------------------------------+----------------+
89+| Prompt-Guard-86M | meta-llama/Prompt-Guard-86M | 128K |
90++----------------------------------+------------------------------------------+----------------+
91+| Llama-Guard-2-8B | meta-llama/Llama-Guard-2-8B | 4K |
92++----------------------------------+------------------------------------------+----------------+
6993 </pre>
7094
7195 To download models, you can use the llama download command.
7296
7397 #### Downloading from [Meta](https://llama.meta.com/llama-downloads/)
7498
75-Here is an example download command to get the 8B/70B Instruct model. You will need META_URL which can be obtained from [here](https://llama.meta.com/docs/getting_the_models/meta/)
99+Here is an example download command to get the 3B-Instruct/11B-Vision-Instruct model. You will need META_URL which can be obtained from [here](https://llama.meta.com/docs/getting_the_models/meta/)
76100
77101 Download the required checkpoints using the following commands:
78102 ```bash
79103 # download the 8B model, this can be run on a single GPU
80-llama download --source meta --model-id Meta-Llama3.1-8B-Instruct --meta-url META_URL
104+llama download --source meta --model-id Llama3.2-3B-Instruct --meta-url META_URL
81105
82106 # you can also get the 70B model, this will require 8 GPUs however
83-llama download --source meta --model-id Meta-Llama3.1-70B-Instruct --meta-url META_URL
107+llama download --source meta --model-id Llama3.2-11B-Vision-Instruct --meta-url META_URL
84108
85109 # llama-agents have safety enabled by default. For this, you will need
86110 # safety models -- Llama-Guard and Prompt-Guard
@@ -124,7 +148,7 @@
124148 ### 2.1 Subcommands
125149 1. `download`: Download the model from different sources. (meta, huggingface)
126150 2. `list`: Lists all the models available for download with hardware requirements to deploy the models.
127-3. `template`: <TODO: What is a template?>
151+3. `prompt-format`: Show llama model message formats.
128152 4. `describe`: Describes all the properties of the model.
129153
130154 ### 2.2 Sample Usage
@@ -135,7 +159,7 @@
135159 llama model --help
136160 ```
137161 <pre style="font-family: monospace;">
138-usage: llama model [-h] {download,list,template,describe} ...
162+usage: llama model [-h] {download,list,prompt-format,describe} ...
139163
140164 Work with llama models
141165
@@ -143,124 +167,67 @@
143167 -h, --help show this help message and exit
144168
145169 model_subcommands:
146- {download,list,template,describe}
170+ {download,list,prompt-format,describe}
147171 </pre>
148172
149173 You can use the describe command to know more about a model:
150174 ```
151-llama model describe -m Meta-Llama3.1-8B-Instruct
175+llama model describe -m Llama3.2-3B-Instruct
152176 ```
153177 ### 2.3 Describe
154178
155179 <pre style="font-family: monospace;">
156-+-----------------------------+---------------------------------------+
157-| Model | Meta- |
158-| | Llama3.1-8B-Instruct |
159-+-----------------------------+---------------------------------------+
160-| HuggingFace ID | meta-llama/Meta-Llama-3.1-8B-Instruct |
161-+-----------------------------+---------------------------------------+
162-| Description | Llama 3.1 8b instruct model |
163-+-----------------------------+---------------------------------------+
164-| Context Length | 128K tokens |
165-+-----------------------------+---------------------------------------+
166-| Weights format | bf16 |
167-+-----------------------------+---------------------------------------+
168-| Model params.json | { |
169-| | "dim": 4096, |
170-| | "n_layers": 32, |
171-| | "n_heads": 32, |
172-| | "n_kv_heads": 8, |
173-| | "vocab_size": 128256, |
174-| | "ffn_dim_multiplier": 1.3, |
175-| | "multiple_of": 1024, |
176-| | "norm_eps": 1e-05, |
177-| | "rope_theta": 500000.0, |
178-| | "use_scaled_rope": true |
179-| | } |
180-+-----------------------------+---------------------------------------+
181-| Recommended sampling params | { |
182-| | "strategy": "top_p", |
183-| | "temperature": 1.0, |
184-| | "top_p": 0.9, |
185-| | "top_k": 0 |
186-| | } |
187-+-----------------------------+---------------------------------------+
180++-----------------------------+----------------------------------+
181+| Model | Llama3.2-3B-Instruct |
182++-----------------------------+----------------------------------+
183+| HuggingFace ID | meta-llama/Llama-3.2-3B-Instruct |
184++-----------------------------+----------------------------------+
185+| Description | Llama 3.2 3b instruct model |
186++-----------------------------+----------------------------------+
187+| Context Length | 128K tokens |
188++-----------------------------+----------------------------------+
189+| Weights format | bf16 |
190++-----------------------------+----------------------------------+
191+| Model params.json | { |
192+| | "dim": 3072, |
193+| | "n_layers": 28, |
194+| | "n_heads": 24, |
195+| | "n_kv_heads": 8, |
196+| | "vocab_size": 128256, |
197+| | "ffn_dim_multiplier": 1.0, |
198+| | "multiple_of": 256, |
199+| | "norm_eps": 1e-05, |
200+| | "rope_theta": 500000.0, |
201+| | "use_scaled_rope": true |
202+| | } |
203++-----------------------------+----------------------------------+
204+| Recommended sampling params | { |
205+| | "strategy": "top_p", |
206+| | "temperature": 1.0, |
207+| | "top_p": 0.9, |
208+| | "top_k": 0 |
209+| | } |
210++-----------------------------+----------------------------------+
188211 </pre>
189-### 2.4 Template
190-You can even run `llama model template` see all of the templates and their tokens:
212+### 2.4 Prompt Format
213+You can even run `llama model prompt-format` see all of the templates and their tokens:
191214
192215 ```
193-llama model template
216+llama model prompt-format -m Llama3.2-3B-Instruct
194217 ```
218+<p align="center">
219+<img width="719" alt="image" src="https://github.com/user-attachments/assets/c5332026-8c0b-4edc-b438-ec60cd7ca554">
220+</p>
195221
196-<pre style="font-family: monospace;">
197-+-----------+---------------------------------+
198-| Role | Template Name |
199-+-----------+---------------------------------+
200-| user | user-default |
201-| assistant | assistant-builtin-tool-call |
202-| assistant | assistant-custom-tool-call |
203-| assistant | assistant-default |
204-| system | system-builtin-and-custom-tools |
205-| system | system-builtin-tools-only |
206-| system | system-custom-tools-only |
207-| system | system-default |
208-| tool | tool-success |
209-| tool | tool-failure |
210-+-----------+---------------------------------+
211-</pre>
212-
213-And fetch an example by passing it to `--name`:
214-```
215-llama model template --name tool-success
216-```
217-
218-<pre style="font-family: monospace;">
219-+----------+----------------------------------------------------------------+
220-| Name | tool-success |
221-+----------+----------------------------------------------------------------+
222-| Template | <|start_header_id|>ipython<|end_header_id|> |
223-| | |
224-| | completed |
225-| | [stdout]{"results":["something |
226-| | something"]}[/stdout]<|eot_id|> |
227-| | |
228-+----------+----------------------------------------------------------------+
229-| Notes | Note ipython header and [stdout] |
230-+----------+----------------------------------------------------------------+
231-</pre>
232-
233-Or:
234-```
235-llama model template --name system-builtin-tools-only
236-```
237-
238-<pre style="font-family: monospace;">
239-+----------+--------------------------------------------+
240-| Name | system-builtin-tools-only |
241-+----------+--------------------------------------------+
242-| Template | <|start_header_id|>system<|end_header_id|> |
243-| | |
244-| | Environment: ipython |
245-| | Tools: brave_search, wolfram_alpha |
246-| | |
247-| | Cutting Knowledge Date: December 2023 |
248-| | Today Date: 21 August 2024 |
249-| | <|eot_id|> |
250-| | |
251-+----------+--------------------------------------------+
252-| Notes | |
253-+----------+--------------------------------------------+
254-</pre>
255222
256-These commands can help understand the model interface and how prompts / messages are formatted for various scenarios.
223+You will be shown a Markdown formatted description of the model interface and how prompts / messages are formatted for various scenarios.
257224
258225 **NOTE**: Outputs in terminal are color printed to show special tokens.
259226
260227
261228 ## Step 3: Building, and Configuring Llama Stack Distributions
262229
263-- Please see our [Getting Started](getting_started.md) guide for details.
230+- Please see our [Getting Started](getting_started.md) guide for more details on how to build and start a Llama Stack distribution.
264231
265232 ### Step 3.1 Build
266233 In the following steps, imagine we'll be working with a `Meta-Llama3.1-8B-Instruct` model. We will name our build `8b-instruct` to help us remember the config. We will start build our distribution (in the form of a Conda environment, or Docker image). In this step, we will specify:
added docs/dog.jpg +0 −0

Binary content is not shown. View the file.

added docs/getting_started.ipynb +0 −0

Not shown: the file is larger than the hub shows, or this page holds as much as it shows. View the file.

modified docs/getting_started.md +99 −23
@@ -1,9 +1,70 @@
1+# llama-stack
2+
3+[![PyPI - Downloads](https://img.shields.io/pypi/dm/llama-stack)](https://pypi.org/project/llama-stack/)
4+[![Discord](https://img.shields.io/discord/1257833999603335178)](https://discord.gg/TZAAYNVtrU)
5+
6+This repository contains the specifications and implementations of the APIs which are part of the Llama Stack.
7+
8+The Llama Stack defines and standardizes the building blocks needed to bring generative AI applications to market. These blocks span the entire development lifecycle: from model training and fine-tuning, through product evaluation, to invoking AI agents in production. Beyond definition, we're developing open-source versions and partnering with cloud providers, ensuring developers can assemble AI solutions using consistent, interlocking pieces across platforms. The ultimate goal is to accelerate innovation in the AI space.
9+
10+The Stack APIs are rapidly improving, but still very much work in progress and we invite feedback as well as direct contributions.
11+
12+
13+## APIs
14+
15+The Llama Stack consists of the following set of APIs:
16+
17+- Inference
18+- Safety
19+- Memory
20+- Agentic System
21+- Evaluation
22+- Post Training
23+- Synthetic Data Generation
24+- Reward Scoring
25+
26+Each of the APIs themselves is a collection of REST endpoints.
27+
28+## API Providers
29+
30+A Provider is what makes the API real -- they provide the actual implementation backing the API.
31+
32+As an example, for Inference, we could have the implementation be backed by open source libraries like `[ torch | vLLM | TensorRT ]` as possible options.
33+
34+A provider can also be just a pointer to a remote REST service -- for example, cloud providers or dedicated inference providers could serve these APIs.
35+
36+
37+## Llama Stack Distribution
38+
39+A Distribution is where APIs and Providers are assembled together to provide a consistent whole to the end application developer. You can mix-and-match providers -- some could be backed by local code and some could be remote. As a hobbyist, you can serve a small model locally, but can choose a cloud provider for a large model. Regardless, the higher level APIs your app needs to work with don't need to change at all. You can even imagine moving across the server / mobile-device boundary as well always using the same uniform set of APIs for developing Generative AI applications.
40+
41+
42+## Installation
43+
44+You can install this repository as a [package](https://pypi.org/project/llama-stack/) with `pip install llama-stack`
45+
46+If you want to install from source:
47+
48+```bash
49+mkdir -p ~/local
50+cd ~/local
51+git clone git@github.com:meta-llama/llama-stack.git
52+
53+conda create -n stack python=3.10
54+conda activate stack
55+
56+cd llama-stack
57+$CONDA_PREFIX/bin/pip install -e .
58+```
59+
160 # Getting Started
261
362 The `llama` CLI tool helps you setup and use the Llama toolchain & agentic systems. It should be available on your path after installing the `llama-stack` package.
463
564 This guides allows you to quickly get started with building and running a Llama Stack server in < 5 minutes!
665
66+You may also checkout this [notebook](https://github.com/meta-llama/llama-stack/blob/main/docs/getting_started.ipynb) for trying out out demo scripts.
67+
768 ## Quick Cheatsheet
869 - Quick 3 line command to build and start a LlamaStack server using our Meta Reference implementation for all API endpoints with `conda` as build type.
970
@@ -12,7 +73,7 @@
1273 ```
1374 llama stack build
1475
15-> Enter an unique name for identifying your Llama Stack build distribution (e.g. my-local-stack): my-local-llama-stack
76+> Enter an unique name for identifying your Llama Stack build distribution (e.g. my-local-stack): my-local-stack
1677 > Enter the image type you want your distribution to be built with (docker or conda): conda
1778
1879 Llama Stack is composed of several APIs working together. Let's configure the providers (implementations) you want to use for these APIs.
@@ -24,47 +85,57 @@
2485
2586 > (Optional) Enter a short description for your Llama Stack distribution:
2687
27-Build spec configuration saved at ~/.conda/envs/llamastack-my-local-llama-stack/my-local-llama-stack-build.yaml
88+Build spec configuration saved at ~/.conda/envs/llamastack-my-local-stack/my-local-stack-build.yaml
89+You can now run `llama stack configure my-local-stack`
2890 ```
2991
3092 **`llama stack configure`**
3193 - Run `llama stack configure <name>` with the name you have previously defined in `build` step.
3294 ```
33-llama stack configure my-local-llama-stack
95+llama stack configure <name>
96+```
97+- You will be prompted to enter configurations for your Llama Stack
3498
35-Configuring APIs to serve...
36-Enter comma-separated list of APIs to serve:
99+```
100+$ llama stack configure my-local-stack
37101
102+Could not find my-local-stack. Trying conda build name instead...
38103 Configuring API `inference`...
39-
40-Configuring provider `meta-reference`...
41-Enter value for model (default: Meta-Llama3.1-8B-Instruct) (required):
104+=== Configuring provider `meta-reference` for API inference...
105+Enter value for model (default: Llama3.1-8B-Instruct) (required):
42106 Do you want to configure quantization? (y/n): n
43107 Enter value for torch_seed (optional):
44-Enter value for max_seq_len (required): 4096
108+Enter value for max_seq_len (default: 4096) (required):
45109 Enter value for max_batch_size (default: 1) (required):
46-Configuring API `safety`...
47110
48-Configuring provider `meta-reference`...
111+Configuring API `safety`...
112+=== Configuring provider `meta-reference` for API safety...
49113 Do you want to configure llama_guard_shield? (y/n): n
50114 Do you want to configure prompt_guard_shield? (y/n): n
115+
51116 Configuring API `agents`...
117+=== Configuring provider `meta-reference` for API agents...
118+Enter `type` for persistence_store (options: redis, sqlite, postgres) (default: sqlite):
119+
120+Configuring SqliteKVStoreConfig:
121+Enter value for namespace (optional):
122+Enter value for db_path (default: /home/xiyan/.llama/runtime/kvstore.db) (required):
52123
53-Configuring provider `meta-reference`...
54124 Configuring API `memory`...
125+=== Configuring provider `meta-reference` for API memory...
126+> Please enter the supported memory bank type your provider has for memory: vector
55127
56-Configuring provider `meta-reference`...
57128 Configuring API `telemetry`...
129+=== Configuring provider `meta-reference` for API telemetry...
58130
59-Configuring provider `meta-reference`...
60-> YAML configuration has been written to ~/.llama/builds/conda/my-local-llama-stack-run.yaml.
61-You can now run `llama stack run my-local-llama-stack --port PORT` or `llama stack run ~/.llama/builds/conda/my-local-llama-stack-run.yaml --port PORT
131+> YAML configuration has been written to ~/.llama/builds/conda/my-local-stack-run.yaml.
132+You can now run `llama stack run my-local-stack --port PORT`
62133 ```
63134
64135 **`llama stack run`**
65136 - Run `llama stack run <name>` with the name you have previously defined.
66137 ```
67-llama stack run my-local-llama-stack
138+llama stack run my-local-stack
68139
69140 ...
70141 > initializing model parallel with size 1
@@ -126,7 +197,7 @@
126197 Running the command above will allow you to fill in the configuration to build your Llama Stack distribution, you will see the following outputs.
127198
128199 ```
129-> Enter an unique name for identifying your Llama Stack build distribution (e.g. my-local-stack): my-local-llama-stack
200+> Enter an unique name for identifying your Llama Stack build distribution (e.g. my-local-stack): 8b-instruct
130201 > Enter the image type you want your distribution to be built with (docker or conda): conda
131202
132203 Llama Stack is composed of several APIs working together. Let's configure the providers (implementations) you want to use for these APIs.
@@ -138,9 +209,14 @@
138209
139210 > (Optional) Enter a short description for your Llama Stack distribution:
140211
141-Build spec configuration saved at ~/.conda/envs/llamastack-my-local-llama-stack/my-local-llama-stack-build.yaml
212+Build spec configuration saved at ~/.conda/envs/llamastack-my-local-llama-stack/8b-instruct-build.yaml
142213 ```
143214
215+**Ollama (optional)**
216+
217+If you plan to use Ollama for inference, you'll need to install the server [via these instructions](https://ollama.com/download).
218+
219+
144220 #### Building from templates
145221 - To build from alternative API providers, we provide distribution templates for users to get started building a distribution backed by different providers.
146222
@@ -236,7 +312,7 @@
236312 - Run `docker images` to check list of available images on your machine.
237313
238314 ```
239-$ llama stack configure ~/.llama/distributions/conda/8b-instruct-build.yaml
315+$ llama stack configure 8b-instruct
240316
241317 Configuring API: inference (meta-reference)
242318 Enter value for model (existing: Meta-Llama3.1-8B-Instruct) (required):
@@ -284,13 +360,13 @@
284360 Now, let's start the Llama Stack Distribution Server. You will need the YAML configuration file which was written out at the end by the `llama stack configure` step.
285361
286362 ```
287-llama stack run ~/.llama/builds/conda/8b-instruct-run.yaml
363+llama stack run 8b-instruct
288364 ```
289365
290366 You should see the Llama Stack server start and print the APIs that it is supporting
291367
292368 ```
293-$ llama stack run ~/.llama/builds/local/conda/8b-instruct.yaml
369+$ llama stack run 8b-instruct
294370
295371 > initializing model parallel with size 1
296372 > initializing ddp with size 1
@@ -357,4 +433,4 @@
357433 python -m llama_stack.apis.safety.client localhost 5000
358434 ```
359435
360-You can find more example scripts with client SDKs to talk with the Llama Stack server in our [llama-stack-apps](https://github.com/meta-llama/llama-stack-apps/tree/main/sdk_examples) repo.
436+You can find more example scripts with client SDKs to talk with the Llama Stack server in our [llama-stack-apps](https://github.com/meta-llama/llama-stack-apps) repo.
modified docs/resources/llama-stack-spec.html +233 −36
@@ -21,7 +21,7 @@
2121 "info": {
2222 "title": "[DRAFT] Llama Stack Specification",
2323 "version": "0.0.1",
24- "description": "This is the specification of the llama stack that provides\n a set of endpoints and their corresponding interfaces that are tailored to\n best leverage Llama Models. The specification is still in draft and subject to change.\n Generated at 2024-09-23 10:56:42.866760"
24+ "description": "This is the specification of the llama stack that provides\n a set of endpoints and their corresponding interfaces that are tailored to\n best leverage Llama Models. The specification is still in draft and subject to change.\n Generated at 2024-09-23 16:58:41.469308"
2525 },
2626 "servers": [
2727 {
@@ -2027,10 +2027,20 @@
20272027 {
20282028 "type": "string"
20292029 },
2030+ {
2031+ "$ref": "#/components/schemas/ImageMedia"
2032+ },
20302033 {
20312034 "type": "array",
20322035 "items": {
2033- "type": "string"
2036+ "oneOf": [
2037+ {
2038+ "type": "string"
2039+ },
2040+ {
2041+ "$ref": "#/components/schemas/ImageMedia"
2042+ }
2043+ ]
20342044 }
20352045 }
20362046 ]
@@ -2053,6 +2063,35 @@
20532063 "tool_calls"
20542064 ]
20552065 },
2066+ "ImageMedia": {
2067+ "type": "object",
2068+ "properties": {
2069+ "image": {
2070+ "oneOf": [
2071+ {
2072+ "type": "object",
2073+ "properties": {
2074+ "format": {
2075+ "type": "string"
2076+ },
2077+ "format_description": {
2078+ "type": "string"
2079+ }
2080+ },
2081+ "additionalProperties": false,
2082+ "title": "This class represents an image object. To create"
2083+ },
2084+ {
2085+ "$ref": "#/components/schemas/URL"
2086+ }
2087+ ]
2088+ }
2089+ },
2090+ "additionalProperties": false,
2091+ "required": [
2092+ "image"
2093+ ]
2094+ },
20562095 "SamplingParams": {
20572096 "type": "object",
20582097 "properties": {
@@ -2115,10 +2154,20 @@
21152154 {
21162155 "type": "string"
21172156 },
2157+ {
2158+ "$ref": "#/components/schemas/ImageMedia"
2159+ },
21182160 {
21192161 "type": "array",
21202162 "items": {
2121- "type": "string"
2163+ "oneOf": [
2164+ {
2165+ "type": "string"
2166+ },
2167+ {
2168+ "$ref": "#/components/schemas/ImageMedia"
2169+ }
2170+ ]
21222171 }
21232172 }
21242173 ]
@@ -2267,6 +2316,28 @@
22672316 "required": {
22682317 "type": "boolean",
22692318 "default": true
2319+ },
2320+ "default": {
2321+ "oneOf": [
2322+ {
2323+ "type": "null"
2324+ },
2325+ {
2326+ "type": "boolean"
2327+ },
2328+ {
2329+ "type": "number"
2330+ },
2331+ {
2332+ "type": "string"
2333+ },
2334+ {
2335+ "type": "array"
2336+ },
2337+ {
2338+ "type": "object"
2339+ }
2340+ ]
22702341 }
22712342 },
22722343 "additionalProperties": false,
@@ -2278,7 +2349,8 @@
22782349 "type": "string",
22792350 "enum": [
22802351 "json",
2281- "function_tag"
2352+ "function_tag",
2353+ "python_list"
22822354 ],
22832355 "title": "This Enum refers to the prompt format for calling custom / zero shot tools",
22842356 "description": "`json` --\n Refers to the json format for calling tools.\n The json format takes the form like\n {\n \"type\": \"function\",\n \"function\" : {\n \"name\": \"function_name\",\n \"description\": \"function_description\",\n \"parameters\": {...}\n }\n }\n\n`function_tag` --\n This is an example of how you could define\n your own user defined format for making tool calls.\n The function_tag format looks like this,\n <function=function_name>(parameters)</function>\n\nThe detailed prompts for each of these formats are added to llama cli"
@@ -2309,10 +2381,20 @@
23092381 {
23102382 "type": "string"
23112383 },
2384+ {
2385+ "$ref": "#/components/schemas/ImageMedia"
2386+ },
23122387 {
23132388 "type": "array",
23142389 "items": {
2315- "type": "string"
2390+ "oneOf": [
2391+ {
2392+ "type": "string"
2393+ },
2394+ {
2395+ "$ref": "#/components/schemas/ImageMedia"
2396+ }
2397+ ]
23162398 }
23172399 }
23182400 ]
@@ -2326,6 +2408,11 @@
23262408 "content"
23272409 ]
23282410 },
2411+ "URL": {
2412+ "type": "string",
2413+ "format": "uri",
2414+ "pattern": "^(https?://|file://|data:)"
2415+ },
23292416 "UserMessage": {
23302417 "type": "object",
23312418 "properties": {
@@ -2339,10 +2426,20 @@
23392426 {
23402427 "type": "string"
23412428 },
2429+ {
2430+ "$ref": "#/components/schemas/ImageMedia"
2431+ },
23422432 {
23432433 "type": "array",
23442434 "items": {
2345- "type": "string"
2435+ "oneOf": [
2436+ {
2437+ "type": "string"
2438+ },
2439+ {
2440+ "$ref": "#/components/schemas/ImageMedia"
2441+ }
2442+ ]
23462443 }
23472444 }
23482445 ]
@@ -2352,10 +2449,20 @@
23522449 {
23532450 "type": "string"
23542451 },
2452+ {
2453+ "$ref": "#/components/schemas/ImageMedia"
2454+ },
23552455 {
23562456 "type": "array",
23572457 "items": {
2358- "type": "string"
2458+ "oneOf": [
2459+ {
2460+ "type": "string"
2461+ },
2462+ {
2463+ "$ref": "#/components/schemas/ImageMedia"
2464+ }
2465+ ]
23592466 }
23602467 }
23612468 ]
@@ -2455,10 +2562,20 @@
24552562 {
24562563 "type": "string"
24572564 },
2565+ {
2566+ "$ref": "#/components/schemas/ImageMedia"
2567+ },
24582568 {
24592569 "type": "array",
24602570 "items": {
2461- "type": "string"
2571+ "oneOf": [
2572+ {
2573+ "type": "string"
2574+ },
2575+ {
2576+ "$ref": "#/components/schemas/ImageMedia"
2577+ }
2578+ ]
24622579 }
24632580 }
24642581 ]
@@ -2714,10 +2831,20 @@
27142831 {
27152832 "type": "string"
27162833 },
2834+ {
2835+ "$ref": "#/components/schemas/ImageMedia"
2836+ },
27172837 {
27182838 "type": "array",
27192839 "items": {
2720- "type": "string"
2840+ "oneOf": [
2841+ {
2842+ "type": "string"
2843+ },
2844+ {
2845+ "$ref": "#/components/schemas/ImageMedia"
2846+ }
2847+ ]
27212848 }
27222849 }
27232850 ]
@@ -3298,11 +3425,6 @@
32983425 "engine"
32993426 ]
33003427 },
3301- "URL": {
3302- "type": "string",
3303- "format": "uri",
3304- "pattern": "^(https?://|file://|data:)"
3305- },
33063428 "WolframAlphaToolDefinition": {
33073429 "type": "object",
33083430 "properties": {
@@ -3396,10 +3518,20 @@
33963518 {
33973519 "type": "string"
33983520 },
3521+ {
3522+ "$ref": "#/components/schemas/ImageMedia"
3523+ },
33993524 {
34003525 "type": "array",
34013526 "items": {
3402- "type": "string"
3527+ "oneOf": [
3528+ {
3529+ "type": "string"
3530+ },
3531+ {
3532+ "$ref": "#/components/schemas/ImageMedia"
3533+ }
3534+ ]
34033535 }
34043536 },
34053537 {
@@ -3731,10 +3863,20 @@
37313863 {
37323864 "type": "string"
37333865 },
3866+ {
3867+ "$ref": "#/components/schemas/ImageMedia"
3868+ },
37343869 {
37353870 "type": "array",
37363871 "items": {
3737- "type": "string"
3872+ "oneOf": [
3873+ {
3874+ "type": "string"
3875+ },
3876+ {
3877+ "$ref": "#/components/schemas/ImageMedia"
3878+ }
3879+ ]
37383880 }
37393881 }
37403882 ]
@@ -3888,10 +4030,20 @@
38884030 {
38894031 "type": "string"
38904032 },
4033+ {
4034+ "$ref": "#/components/schemas/ImageMedia"
4035+ },
38914036 {
38924037 "type": "array",
38934038 "items": {
3894- "type": "string"
4039+ "oneOf": [
4040+ {
4041+ "type": "string"
4042+ },
4043+ {
4044+ "$ref": "#/components/schemas/ImageMedia"
4045+ }
4046+ ]
38954047 }
38964048 }
38974049 ]
@@ -4316,10 +4468,20 @@
43164468 {
43174469 "type": "string"
43184470 },
4471+ {
4472+ "$ref": "#/components/schemas/ImageMedia"
4473+ },
43194474 {
43204475 "type": "array",
43214476 "items": {
4322- "type": "string"
4477+ "oneOf": [
4478+ {
4479+ "type": "string"
4480+ },
4481+ {
4482+ "$ref": "#/components/schemas/ImageMedia"
4483+ }
4484+ ]
43234485 }
43244486 }
43254487 ]
@@ -4515,10 +4677,20 @@
45154677 {
45164678 "type": "string"
45174679 },
4680+ {
4681+ "$ref": "#/components/schemas/ImageMedia"
4682+ },
45184683 {
45194684 "type": "array",
45204685 "items": {
4521- "type": "string"
4686+ "oneOf": [
4687+ {
4688+ "type": "string"
4689+ },
4690+ {
4691+ "$ref": "#/components/schemas/ImageMedia"
4692+ }
4693+ ]
45224694 }
45234695 },
45244696 {
@@ -5407,10 +5579,20 @@
54075579 {
54085580 "type": "string"
54095581 },
5582+ {
5583+ "$ref": "#/components/schemas/ImageMedia"
5584+ },
54105585 {
54115586 "type": "array",
54125587 "items": {
5413- "type": "string"
5588+ "oneOf": [
5589+ {
5590+ "type": "string"
5591+ },
5592+ {
5593+ "$ref": "#/components/schemas/ImageMedia"
5594+ }
5595+ ]
54145596 }
54155597 }
54165598 ]
@@ -5460,10 +5642,20 @@
54605642 {
54615643 "type": "string"
54625644 },
5645+ {
5646+ "$ref": "#/components/schemas/ImageMedia"
5647+ },
54635648 {
54645649 "type": "array",
54655650 "items": {
5466- "type": "string"
5651+ "oneOf": [
5652+ {
5653+ "type": "string"
5654+ },
5655+ {
5656+ "$ref": "#/components/schemas/ImageMedia"
5657+ }
5658+ ]
54675659 }
54685660 }
54695661 ]
@@ -6027,32 +6219,32 @@
60276219 }
60286220 ],
60296221 "tags": [
6030- {
6031- "name": "Inference"
6032- },
60336222 {
60346223 "name": "Shields"
60356224 },
60366225 {
6037- "name": "Models"
6226+ "name": "BatchInference"
60386227 },
60396228 {
6040- "name": "MemoryBanks"
6229+ "name": "RewardScoring"
60416230 },
60426231 {
60436232 "name": "SyntheticDataGeneration"
60446233 },
60456234 {
6046- "name": "RewardScoring"
6235+ "name": "Agents"
60476236 },
60486237 {
6049- "name": "PostTraining"
6238+ "name": "MemoryBanks"
60506239 },
60516240 {
60526241 "name": "Safety"
60536242 },
60546243 {
6055- "name": "Evaluations"
6244+ "name": "Models"
6245+ },
6246+ {
6247+ "name": "Inference"
60566248 },
60576249 {
60586250 "name": "Memory"
@@ -6061,13 +6253,13 @@
60616253 "name": "Telemetry"
60626254 },
60636255 {
6064- "name": "Agents"
6256+ "name": "PostTraining"
60656257 },
60666258 {
6067- "name": "BatchInference"
6259+ "name": "Datasets"
60686260 },
60696261 {
6070- "name": "Datasets"
6262+ "name": "Evaluations"
60716263 },
60726264 {
60736265 "name": "BuiltinTool",
@@ -6077,6 +6269,10 @@
60776269 "name": "CompletionMessage",
60786270 "description": "<SchemaDefinition schemaRef=\"#/components/schemas/CompletionMessage\" />"
60796271 },
6272+ {
6273+ "name": "ImageMedia",
6274+ "description": "<SchemaDefinition schemaRef=\"#/components/schemas/ImageMedia\" />"
6275+ },
60806276 {
60816277 "name": "SamplingParams",
60826278 "description": "<SchemaDefinition schemaRef=\"#/components/schemas/SamplingParams\" />"
@@ -6117,6 +6313,10 @@
61176313 "name": "ToolResponseMessage",
61186314 "description": "<SchemaDefinition schemaRef=\"#/components/schemas/ToolResponseMessage\" />"
61196315 },
6316+ {
6317+ "name": "URL",
6318+ "description": "<SchemaDefinition schemaRef=\"#/components/schemas/URL\" />"
6319+ },
61206320 {
61216321 "name": "UserMessage",
61226322 "description": "<SchemaDefinition schemaRef=\"#/components/schemas/UserMessage\" />"
@@ -6221,10 +6421,6 @@
62216421 "name": "SearchToolDefinition",
62226422 "description": "<SchemaDefinition schemaRef=\"#/components/schemas/SearchToolDefinition\" />"
62236423 },
6224- {
6225- "name": "URL",
6226- "description": "<SchemaDefinition schemaRef=\"#/components/schemas/URL\" />"
6227- },
62286424 {
62296425 "name": "WolframAlphaToolDefinition",
62306426 "description": "<SchemaDefinition schemaRef=\"#/components/schemas/WolframAlphaToolDefinition\" />"
@@ -6661,6 +6857,7 @@
66616857 "FunctionCallToolDefinition",
66626858 "GetAgentsSessionRequest",
66636859 "GetDocumentsRequest",
6860+ "ImageMedia",
66646861 "InferenceStep",
66656862 "InsertDocumentsRequest",
66666863 "LogEventRequest",
modified docs/resources/llama-stack-spec.yaml +96 −25
@@ -210,8 +210,11 @@
210210 content:
211211 oneOf:
212212 - type: string
213+ - $ref: '#/components/schemas/ImageMedia'
213214 - items:
214- type: string
215+ oneOf:
216+ - type: string
217+ - $ref: '#/components/schemas/ImageMedia'
215218 type: array
216219 - $ref: '#/components/schemas/URL'
217220 mime_type:
@@ -273,8 +276,11 @@
273276 items:
274277 oneOf:
275278 - type: string
279+ - $ref: '#/components/schemas/ImageMedia'
276280 - items:
277- type: string
281+ oneOf:
282+ - type: string
283+ - $ref: '#/components/schemas/ImageMedia'
278284 type: array
279285 type: array
280286 logprobs:
@@ -441,8 +447,11 @@
441447 content:
442448 oneOf:
443449 - type: string
450+ - $ref: '#/components/schemas/ImageMedia'
444451 - items:
445- type: string
452+ oneOf:
453+ - type: string
454+ - $ref: '#/components/schemas/ImageMedia'
446455 type: array
447456 role:
448457 const: assistant
@@ -466,8 +475,11 @@
466475 content:
467476 oneOf:
468477 - type: string
478+ - $ref: '#/components/schemas/ImageMedia'
469479 - items:
470- type: string
480+ oneOf:
481+ - type: string
482+ - $ref: '#/components/schemas/ImageMedia'
471483 type: array
472484 logprobs:
473485 additionalProperties: false
@@ -742,8 +754,11 @@
742754 items:
743755 oneOf:
744756 - type: string
757+ - $ref: '#/components/schemas/ImageMedia'
745758 - items:
746- type: string
759+ oneOf:
760+ - type: string
761+ - $ref: '#/components/schemas/ImageMedia'
747762 type: array
748763 type: array
749764 model:
@@ -893,6 +908,23 @@
893908 required:
894909 - document_ids
895910 type: object
911+ ImageMedia:
912+ additionalProperties: false
913+ properties:
914+ image:
915+ oneOf:
916+ - additionalProperties: false
917+ properties:
918+ format:
919+ type: string
920+ format_description:
921+ type: string
922+ title: This class represents an image object. To create
923+ type: object
924+ - $ref: '#/components/schemas/URL'
925+ required:
926+ - image
927+ type: object
896928 InferenceStep:
897929 additionalProperties: false
898930 properties:
@@ -1041,8 +1073,11 @@
10411073 content:
10421074 oneOf:
10431075 - type: string
1076+ - $ref: '#/components/schemas/ImageMedia'
10441077 - items:
1045- type: string
1078+ oneOf:
1079+ - type: string
1080+ - $ref: '#/components/schemas/ImageMedia'
10461081 type: array
10471082 - $ref: '#/components/schemas/URL'
10481083 document_id:
@@ -1108,8 +1143,11 @@
11081143 inserted_context:
11091144 oneOf:
11101145 - type: string
1146+ - $ref: '#/components/schemas/ImageMedia'
11111147 - items:
1112- type: string
1148+ oneOf:
1149+ - type: string
1150+ - $ref: '#/components/schemas/ImageMedia'
11131151 type: array
11141152 memory_bank_ids:
11151153 items:
@@ -1545,8 +1583,11 @@
15451583 query:
15461584 oneOf:
15471585 - type: string
1586+ - $ref: '#/components/schemas/ImageMedia'
15481587 - items:
1549- type: string
1588+ oneOf:
1589+ - type: string
1590+ - $ref: '#/components/schemas/ImageMedia'
15501591 type: array
15511592 required:
15521593 - bank_id
@@ -1562,8 +1603,11 @@
15621603 content:
15631604 oneOf:
15641605 - type: string
1606+ - $ref: '#/components/schemas/ImageMedia'
15651607 - items:
1566- type: string
1608+ oneOf:
1609+ - type: string
1610+ - $ref: '#/components/schemas/ImageMedia'
15671611 type: array
15681612 document_id:
15691613 type: string
@@ -2067,8 +2111,11 @@
20672111 content:
20682112 oneOf:
20692113 - type: string
2114+ - $ref: '#/components/schemas/ImageMedia'
20702115 - items:
2071- type: string
2116+ oneOf:
2117+ - type: string
2118+ - $ref: '#/components/schemas/ImageMedia'
20722119 type: array
20732120 role:
20742121 const: system
@@ -2203,6 +2250,14 @@
22032250 ToolParamDefinition:
22042251 additionalProperties: false
22052252 properties:
2253+ default:
2254+ oneOf:
2255+ - type: 'null'
2256+ - type: boolean
2257+ - type: number
2258+ - type: string
2259+ - type: array
2260+ - type: object
22062261 description:
22072262 type: string
22082263 param_type:
@@ -2225,6 +2280,7 @@
22252280 enum:
22262281 - json
22272282 - function_tag
2283+ - python_list
22282284 title: This Enum refers to the prompt format for calling custom / zero shot
22292285 tools
22302286 type: string
@@ -2236,8 +2292,11 @@
22362292 content:
22372293 oneOf:
22382294 - type: string
2295+ - $ref: '#/components/schemas/ImageMedia'
22392296 - items:
2240- type: string
2297+ oneOf:
2298+ - type: string
2299+ - $ref: '#/components/schemas/ImageMedia'
22412300 type: array
22422301 tool_name:
22432302 oneOf:
@@ -2256,8 +2315,11 @@
22562315 content:
22572316 oneOf:
22582317 - type: string
2318+ - $ref: '#/components/schemas/ImageMedia'
22592319 - items:
2260- type: string
2320+ oneOf:
2321+ - type: string
2322+ - $ref: '#/components/schemas/ImageMedia'
22612323 type: array
22622324 role:
22632325 const: ipython
@@ -2451,14 +2513,20 @@
24512513 content:
24522514 oneOf:
24532515 - type: string
2516+ - $ref: '#/components/schemas/ImageMedia'
24542517 - items:
2455- type: string
2518+ oneOf:
2519+ - type: string
2520+ - $ref: '#/components/schemas/ImageMedia'
24562521 type: array
24572522 context:
24582523 oneOf:
24592524 - type: string
2525+ - $ref: '#/components/schemas/ImageMedia'
24602526 - items:
2461- type: string
2527+ oneOf:
2528+ - type: string
2529+ - $ref: '#/components/schemas/ImageMedia'
24622530 type: array
24632531 role:
24642532 const: user
@@ -2501,7 +2569,7 @@
25012569 description: "This is the specification of the llama stack that provides\n \
25022570 \ a set of endpoints and their corresponding interfaces that are tailored\
25032571 \ to\n best leverage Llama Models. The specification is still in\
2504- \ draft and subject to change.\n Generated at 2024-09-23 10:56:42.866760"
2572+ \ draft and subject to change.\n Generated at 2024-09-23 16:58:41.469308"
25052573 title: '[DRAFT] Llama Stack Specification'
25062574 version: 0.0.1
25072575 jsonSchemaDialect: https://json-schema.org/draft/2020-12/schema
@@ -3739,25 +3807,27 @@
37393807 servers:
37403808 - url: http://any-hosted-llama-stack.com
37413809 tags:
3742-- name: Inference
37433810 - name: Shields
3744-- name: Models
3745-- name: MemoryBanks
3746-- name: SyntheticDataGeneration
3811+- name: BatchInference
37473812 - name: RewardScoring
3748-- name: PostTraining
3813+- name: SyntheticDataGeneration
3814+- name: Agents
3815+- name: MemoryBanks
37493816 - name: Safety
3750-- name: Evaluations
3817+- name: Models
3818+- name: Inference
37513819 - name: Memory
37523820 - name: Telemetry
3753-- name: Agents
3754-- name: BatchInference
3821+- name: PostTraining
37553822 - name: Datasets
3823+- name: Evaluations
37563824 - description: <SchemaDefinition schemaRef="#/components/schemas/BuiltinTool" />
37573825 name: BuiltinTool
37583826 - description: <SchemaDefinition schemaRef="#/components/schemas/CompletionMessage"
37593827 />
37603828 name: CompletionMessage
3829+- description: <SchemaDefinition schemaRef="#/components/schemas/ImageMedia" />
3830+ name: ImageMedia
37613831 - description: <SchemaDefinition schemaRef="#/components/schemas/SamplingParams" />
37623832 name: SamplingParams
37633833 - description: <SchemaDefinition schemaRef="#/components/schemas/SamplingStrategy"
@@ -3790,6 +3860,8 @@
37903860 - description: <SchemaDefinition schemaRef="#/components/schemas/ToolResponseMessage"
37913861 />
37923862 name: ToolResponseMessage
3863+- description: <SchemaDefinition schemaRef="#/components/schemas/URL" />
3864+ name: URL
37933865 - description: <SchemaDefinition schemaRef="#/components/schemas/UserMessage" />
37943866 name: UserMessage
37953867 - description: <SchemaDefinition schemaRef="#/components/schemas/BatchChatCompletionRequest"
@@ -3876,8 +3948,6 @@
38763948 - description: <SchemaDefinition schemaRef="#/components/schemas/SearchToolDefinition"
38773949 />
38783950 name: SearchToolDefinition
3879-- description: <SchemaDefinition schemaRef="#/components/schemas/URL" />
3880- name: URL
38813951 - description: <SchemaDefinition schemaRef="#/components/schemas/WolframAlphaToolDefinition"
38823952 />
38833953 name: WolframAlphaToolDefinition
@@ -4233,6 +4303,7 @@
42334303 - FunctionCallToolDefinition
42344304 - GetAgentsSessionRequest
42354305 - GetDocumentsRequest
4306+ - ImageMedia
42364307 - InferenceStep
42374308 - InsertDocumentsRequest
42384309 - LogEventRequest
modified llama_stack/apis/agents/client.py +74 −11
@@ -94,14 +94,16 @@
9494 print(f"Error with parsing or validation: {e}")
9595
9696
97-async def _run_agent(api, tool_definitions, user_prompts, attachments=None):
97+async def _run_agent(
98+ api, model, tool_definitions, tool_prompt_format, user_prompts, attachments=None
99+):
98100 agent_config = AgentConfig(
99- model="Meta-Llama3.1-8B-Instruct",
101+ model=model,
100102 instructions="You are a helpful assistant",
101- sampling_params=SamplingParams(temperature=1.0, top_p=0.9),
103+ sampling_params=SamplingParams(temperature=0.6, top_p=0.9),
102104 tools=tool_definitions,
103105 tool_choice=ToolChoice.auto,
104- tool_prompt_format=ToolPromptFormat.function_tag,
106+ tool_prompt_format=tool_prompt_format,
105107 enable_session_persistence=False,
106108 )
107109
@@ -130,7 +132,8 @@
130132 log.print()
131133
132134
133-async def run_main(host: str, port: int):
135+async def run_llama_3_1(host: str, port: int):
136+ model = "Llama3.1-8B-Instruct"
134137 api = AgentsClient(f"http://{host}:{port}")
135138
136139 tool_definitions = [
@@ -167,10 +170,11 @@
167170 "Write code to check if a number is prime. Use that to check if 7 is prime",
168171 "What is the boiling point of polyjuicepotion ?",
169172 ]
170- await _run_agent(api, tool_definitions, user_prompts)
173+ await _run_agent(api, model, tool_definitions, ToolPromptFormat.json, user_prompts)
171174
172175
173-async def run_rag(host: str, port: int):
176+async def run_llama_3_2_rag(host: str, port: int):
177+ model = "Llama3.2-3B-Instruct"
174178 api = AgentsClient(f"http://{host}:{port}")
175179
176180 urls = [
@@ -206,12 +210,71 @@
206210 "Tell me briefly about llama3 and torchtune",
207211 ]
208212
209- await _run_agent(api, tool_definitions, user_prompts, attachments)
213+ await _run_agent(
214+ api, model, tool_definitions, ToolPromptFormat.json, user_prompts, attachments
215+ )
216+
217+
218+async def run_llama_3_2(host: str, port: int):
219+ model = "Llama3.2-3B-Instruct"
220+ api = AgentsClient(f"http://{host}:{port}")
221+
222+ # zero shot tools for llama3.2 text models
223+ tool_definitions = [
224+ FunctionCallToolDefinition(
225+ function_name="get_boiling_point",
226+ description="Get the boiling point of a imaginary liquids (eg. polyjuice)",
227+ parameters={
228+ "liquid_name": ToolParamDefinition(
229+ param_type="str",
230+ description="The name of the liquid",
231+ required=True,
232+ ),
233+ "celcius": ToolParamDefinition(
234+ param_type="bool",
235+ description="Whether to return the boiling point in Celcius",
236+ required=False,
237+ ),
238+ },
239+ ),
240+ FunctionCallToolDefinition(
241+ function_name="make_web_search",
242+ description="Search the web / internet for more realtime information",
243+ parameters={
244+ "query": ToolParamDefinition(
245+ param_type="str",
246+ description="the query to search for",
247+ required=True,
248+ ),
249+ },
250+ ),
251+ ]
252+
253+ user_prompts = [
254+ "Who are you?",
255+ "what is the 100th prime number?",
256+ "Who was 44th President of USA?",
257+ # multiple tool calls in a single prompt
258+ "What is the boiling point of polyjuicepotion and pinkponklyjuice?",
259+ ]
260+ await _run_agent(
261+ api, model, tool_definitions, ToolPromptFormat.python_list, user_prompts
262+ )
263+
210264
265+def main(host: str, port: int, run_type: str):
266+ assert run_type in [
267+ "tools_llama_3_1",
268+ "tools_llama_3_2",
269+ "rag_llama_3_2",
270+ ], f"Invalid run type {run_type}, must be one of tools_llama_3_1, tools_llama_3_2, rag_llama_3_2"
211271
212-def main(host: str, port: int, rag: bool = False):
213- fn = run_rag if rag else run_main
214- asyncio.run(fn(host, port))
272+ fn = {
273+ "tools_llama_3_1": run_llama_3_1,
274+ "tools_llama_3_2": run_llama_3_2,
275+ "rag_llama_3_2": run_llama_3_2_rag,
276+ }
277+ asyncio.run(fn[run_type](host, port))
215278
216279
217280 if __name__ == "__main__":
modified llama_stack/apis/inference/client.py +33 −3
@@ -10,6 +10,10 @@
1010
1111 import fire
1212 import httpx
13+
14+from llama_models.llama3.api.datatypes import ImageMedia, URL
15+
16+from PIL import Image as PIL_Image
1317 from pydantic import BaseModel
1418
1519 from llama_models.llama3.api import * # noqa: F403
@@ -105,7 +109,30 @@
105109 )
106110 cprint(f"User>{message.content}", "green")
107111 iterator = client.chat_completion(
108- model="Meta-Llama3.1-8B-Instruct",
112+ model="Llama3.1-8B-Instruct",
113+ messages=[message],
114+ stream=stream,
115+ )
116+ async for log in EventLogger().log(iterator):
117+ log.print()
118+
119+
120+async def run_mm_main(host: str, port: int, stream: bool, path: str):
121+ client = InferenceClient(f"http://{host}:{port}")
122+
123+ with open(path, "rb") as f:
124+ img = PIL_Image.open(f).convert("RGB")
125+
126+ message = UserMessage(
127+ content=[
128+ ImageMedia(image=URL(uri=f"file://{path}")),
129+ # ImageMedia(image=img),
130+ "Describe this image in two sentences",
131+ ],
132+ )
133+ cprint(f"User>{message.content}", "green")
134+ iterator = client.chat_completion(
135+ model="Llama3.2-11B-Vision-Instruct",
109136 messages=[message],
110137 stream=stream,
111138 )
@@ -113,8 +140,11 @@
113140 log.print()
114141
115142
116-def main(host: str, port: int, stream: bool = True):
117- asyncio.run(run_main(host, port, stream))
143+def main(host: str, port: int, stream: bool = True, mm: bool = False, file: str = None):
144+ if mm:
145+ asyncio.run(run_mm_main(host, port, stream, file))
146+ else:
147+ asyncio.run(run_main(host, port, stream))
118148
119149
120150 if __name__ == "__main__":
modified llama_stack/apis/memory_banks/memory_banks.py +1 −1
@@ -7,11 +7,11 @@
77 from typing import List, Optional, Protocol
88
99 from llama_models.schema_utils import json_schema_type, webmethod
10+from pydantic import BaseModel, Field
1011
1112 from llama_stack.apis.memory import MemoryBankType
1213
1314 from llama_stack.distribution.datatypes import GenericProviderConfig
14-from pydantic import BaseModel, Field
1515
1616
1717 @json_schema_type
modified llama_stack/apis/safety/client.py +5 −0
@@ -51,6 +51,11 @@
5151 ),
5252 headers={
5353 "Content-Type": "application/json",
54+ "X-LlamaStack-ProviderData": json.dumps(
55+ {
56+ "together_api_key": "1882f9a484fc7c6ce3e4dc90272d5db52346c93838daab3d704803181f396b22"
57+ }
58+ ),
5459 },
5560 timeout=20,
5661 )
modified llama_stack/cli/download.py +2 −2
@@ -44,7 +44,7 @@
4444 parser.add_argument(
4545 "--source",
4646 choices=["meta", "huggingface"],
47- required=True,
47+ default="meta",
4848 )
4949 parser.add_argument(
5050 "--model-id",
@@ -116,7 +116,7 @@
116116 "You can find your token by visiting https://huggingface.co/settings/tokens"
117117 )
118118 except RepositoryNotFoundError:
119- parser.error(f"Repository '{args.repo_id}' not found on the Hugging Face Hub.")
119+ parser.error(f"Repository '{repo_id}' not found on the Hugging Face Hub.")
120120 except Exception as e:
121121 parser.error(e)
122122
modified llama_stack/cli/model/model.py +2 −2
@@ -9,7 +9,7 @@
99 from llama_stack.cli.model.describe import ModelDescribe
1010 from llama_stack.cli.model.download import ModelDownload
1111 from llama_stack.cli.model.list import ModelList
12-from llama_stack.cli.model.template import ModelTemplate
12+from llama_stack.cli.model.prompt_format import ModelPromptFormat
1313
1414 from llama_stack.cli.subcommand import Subcommand
1515
@@ -30,5 +30,5 @@
3030 # Add sub-commands
3131 ModelDownload.create(subparsers)
3232 ModelList.create(subparsers)
33- ModelTemplate.create(subparsers)
33+ ModelPromptFormat.create(subparsers)
3434 ModelDescribe.create(subparsers)
added llama_stack/cli/model/prompt_format.py +116 −0
@@ -0,0 +1,116 @@
1+# Copyright (c) Meta Platforms, Inc. and affiliates.
2+# All rights reserved.
3+#
4+# This source code is licensed under the terms described in the LICENSE file in
5+# the root directory of this source tree.
6+
7+import argparse
8+import subprocess
9+import textwrap
10+from io import StringIO
11+
12+from llama_models.datatypes import CoreModelId, is_multimodal, model_family, ModelFamily
13+
14+from llama_stack.cli.subcommand import Subcommand
15+
16+
17+class ModelPromptFormat(Subcommand):
18+ """Llama model cli for describe a model prompt format (message formats)"""
19+
20+ def __init__(self, subparsers: argparse._SubParsersAction):
21+ super().__init__()
22+ self.parser = subparsers.add_parser(
23+ "prompt-format",
24+ prog="llama model prompt-format",
25+ description="Show llama model message formats",
26+ epilog=textwrap.dedent(
27+ """
28+ Example:
29+ llama model prompt-format <options>
30+ """
31+ ),
32+ formatter_class=argparse.RawTextHelpFormatter,
33+ )
34+ self._add_arguments()
35+ self.parser.set_defaults(func=self._run_model_template_cmd)
36+
37+ def _add_arguments(self):
38+ self.parser.add_argument(
39+ "-m",
40+ "--model-name",
41+ type=str,
42+ default="llama3_1",
43+ help="Model Family (llama3_1, llama3_X, etc.)",
44+ )
45+
46+ def _run_model_template_cmd(self, args: argparse.Namespace) -> None:
47+ import pkg_resources
48+
49+ # Only Llama 3.1 and 3.2 are supported
50+ supported_model_ids = [
51+ m
52+ for m in CoreModelId
53+ if model_family(m) in {ModelFamily.llama3_1, ModelFamily.llama3_2}
54+ ]
55+ model_str = "\n".join([m.value for m in supported_model_ids])
56+ try:
57+ model_id = CoreModelId(args.model_name)
58+ except ValueError:
59+ raise argparse.ArgumentTypeError(
60+ f"{args.model_name} is not a valid Model. Choose one from --\n{model_str}"
61+ ) from None
62+
63+ if model_id not in supported_model_ids:
64+ raise argparse.ArgumentTypeError(
65+ f"{model_id} is not a valid Model. Choose one from --\n {model_str}"
66+ ) from None
67+
68+ llama_3_1_file = pkg_resources.resource_filename(
69+ "llama_models", "llama3_1/prompt_format.md"
70+ )
71+ llama_3_2_text_file = pkg_resources.resource_filename(
72+ "llama_models", "llama3_2/text_prompt_format.md"
73+ )
74+ llama_3_2_vision_file = pkg_resources.resource_filename(
75+ "llama_models", "llama3_2/vision_prompt_format.md"
76+ )
77+ if model_family(model_id) == ModelFamily.llama3_1:
78+ with open(llama_3_1_file, "r") as f:
79+ content = f.read()
80+ elif model_family(model_id) == ModelFamily.llama3_2:
81+ if is_multimodal(model_id):
82+ with open(llama_3_2_vision_file, "r") as f:
83+ content = f.read()
84+ else:
85+ with open(llama_3_2_text_file, "r") as f:
86+ content = f.read()
87+
88+ render_markdown_to_pager(content)
89+
90+
91+def render_markdown_to_pager(markdown_content: str):
92+ from rich.console import Console
93+ from rich.markdown import Markdown
94+ from rich.style import Style
95+ from rich.text import Text
96+
97+ class LeftAlignedHeaderMarkdown(Markdown):
98+ def parse_header(self, token):
99+ level = token.type.count("h")
100+ content = Text(token.content)
101+ header_style = Style(color="bright_blue", bold=True)
102+ header = Text(f"{'#' * level} ", style=header_style) + content
103+ self.add_text(header)
104+
105+ # Render the Markdown
106+ md = LeftAlignedHeaderMarkdown(markdown_content)
107+
108+ # Capture the rendered output
109+ output = StringIO()
110+ console = Console(file=output, force_terminal=True, width=100) # Set a fixed width
111+ console.print(md)
112+ rendered_content = output.getvalue()
113+
114+ # Pipe to pager
115+ pager = subprocess.Popen(["less", "-R"], stdin=subprocess.PIPE)
116+ pager.communicate(input=rendered_content.encode())
deleted llama_stack/cli/model/template.py +0 −113
@@ -1,113 +0,0 @@
1-# Copyright (c) Meta Platforms, Inc. and affiliates.
2-# All rights reserved.
3-#
4-# This source code is licensed under the terms described in the LICENSE file in
5-# the root directory of this source tree.
6-
7-import argparse
8-import textwrap
9-
10-from termcolor import colored
11-
12-from llama_stack.cli.subcommand import Subcommand
13-
14-
15-class ModelTemplate(Subcommand):
16- """Llama model cli for describe a model template (message formats)"""
17-
18- def __init__(self, subparsers: argparse._SubParsersAction):
19- super().__init__()
20- self.parser = subparsers.add_parser(
21- "template",
22- prog="llama model template",
23- description="Show llama model message formats",
24- epilog=textwrap.dedent(
25- """
26- Example:
27- llama model template <options>
28- """
29- ),
30- formatter_class=argparse.RawTextHelpFormatter,
31- )
32- self._add_arguments()
33- self.parser.set_defaults(func=self._run_model_template_cmd)
34-
35- def _prompt_type(self, value):
36- from llama_models.llama3.api.datatypes import ToolPromptFormat
37-
38- try:
39- return ToolPromptFormat(value.lower())
40- except ValueError:
41- raise argparse.ArgumentTypeError(
42- f"{value} is not a valid ToolPromptFormat. Choose from {', '.join(t.value for t in ToolPromptFormat)}"
43- ) from None
44-
45- def _add_arguments(self):
46- self.parser.add_argument(
47- "-m",
48- "--model-family",
49- type=str,
50- default="llama3_1",
51- help="Model Family (llama3_1, llama3_X, etc.)",
52- )
53- self.parser.add_argument(
54- "--name",
55- type=str,
56- help="Usecase template name (system_message, user_message, assistant_message, tool_message)...",
57- required=False,
58- )
59- self.parser.add_argument(
60- "--format",
61- type=str,
62- help="ToolPromptFormat (json or function_tag). This flag is used to print the template in a specific formats.",
63- required=False,
64- default="json",
65- )
66- self.parser.add_argument(
67- "--raw",
68- action="store_true",
69- help="If set to true, don't pretty-print into a table. Useful to copy-paste.",
70- )
71-
72- def _run_model_template_cmd(self, args: argparse.Namespace) -> None:
73- from llama_models.llama3.api.interface import (
74- list_jinja_templates,
75- render_jinja_template,
76- )
77-
78- from llama_stack.cli.table import print_table
79-
80- if args.name:
81- tool_prompt_format = self._prompt_type(args.format)
82- template, tokens_info = render_jinja_template(args.name, tool_prompt_format)
83- rendered = ""
84- for tok, is_special in tokens_info:
85- if is_special:
86- rendered += colored(tok, "yellow", attrs=["bold"])
87- else:
88- rendered += tok
89-
90- if not args.raw:
91- rendered = rendered.replace("\n", "↵\n")
92- print_table(
93- [
94- (
95- "Name",
96- colored(template.template_name, "white", attrs=["bold"]),
97- ),
98- ("Template", rendered),
99- ("Notes", template.notes),
100- ],
101- separate_rows=True,
102- )
103- else:
104- print("Template: ", template.template_name)
105- print("=" * 40)
106- print(rendered)
107- else:
108- templates = list_jinja_templates()
109- headers = ["Role", "Template Name"]
110- print_table(
111- [(t.role, t.template_name) for t in templates],
112- headers,
113- )
deleted llama_stack/distribution/control_plane/__init__.py +0 −5
@@ -1,5 +0,0 @@
1-# Copyright (c) Meta Platforms, Inc. and affiliates.
2-# All rights reserved.
3-#
4-# This source code is licensed under the terms described in the LICENSE file in
5-# the root directory of this source tree.
modified llama_stack/distribution/start_container.sh +23 −7
@@ -8,6 +8,7 @@
88
99 DOCKER_BINARY=${DOCKER_BINARY:-docker}
1010 DOCKER_OPTS=${DOCKER_OPTS:-}
11+LLAMA_CHECKPOINT_DIR=${LLAMA_CHECKPOINT_DIR:-}
1112
1213 set -euo pipefail
1314
@@ -37,10 +38,25 @@
3738 shift
3839
3940 set -x
40-$DOCKER_BINARY run $DOCKER_OPTS -it \
41- -p $port:$port \
42- -v "$yaml_config:/app/config.yaml" \
43- $docker_image \
44- python -m llama_stack.distribution.server.server \
45- --yaml_config /app/config.yaml \
46- --port $port "$@"
41+
42+if [ -n "$LLAMA_CHECKPOINT_DIR" ]; then
43+ $DOCKER_BINARY run $DOCKER_OPTS -it \
44+ -p $port:$port \
45+ -v "$yaml_config:/app/config.yaml" \
46+ -v "$LLAMA_CHECKPOINT_DIR:/root/.llama" \
47+ --gpus=all \
48+ $docker_image \
49+ python -m llama_stack.distribution.server.server \
50+ --yaml_config /app/config.yaml \
51+ --port $port "$@"
52+fi
53+
54+if [ -z "$LLAMA_CHECKPOINT_DIR" ]; then
55+ $DOCKER_BINARY run $DOCKER_OPTS -it \
56+ -p $port:$port \
57+ -v "$yaml_config:/app/config.yaml" \
58+ $docker_image \
59+ python -m llama_stack.distribution.server.server \
60+ --yaml_config /app/config.yaml \
61+ --port $port "$@"
62+fi
modified llama_stack/providers/adapters/inference/fireworks/fireworks.py +7 −5
@@ -15,14 +15,16 @@
1515 from llama_models.sku_list import resolve_model
1616
1717 from llama_stack.apis.inference import * # noqa: F403
18-from llama_stack.providers.utils.inference.prepare_messages import prepare_messages
18+from llama_stack.providers.utils.inference.augment_messages import (
19+ augment_messages_for_tools,
20+)
1921
2022 from .config import FireworksImplConfig
2123
2224 FIREWORKS_SUPPORTED_MODELS = {
23- "Meta-Llama3.1-8B-Instruct": "fireworks/llama-v3p1-8b-instruct",
24- "Meta-Llama3.1-70B-Instruct": "fireworks/llama-v3p1-70b-instruct",
25- "Meta-Llama3.1-405B-Instruct": "fireworks/llama-v3p1-405b-instruct",
25+ "Llama3.1-8B-Instruct": "fireworks/llama-v3p1-8b-instruct",
26+ "Llama3.1-70B-Instruct": "fireworks/llama-v3p1-70b-instruct",
27+ "Llama3.1-405B-Instruct": "fireworks/llama-v3p1-405b-instruct",
2628 }
2729
2830
@@ -106,7 +108,7 @@
106108 logprobs=logprobs,
107109 )
108110
109- messages = prepare_messages(request)
111+ messages = augment_messages_for_tools(request)
110112
111113 # accumulate sampling params and other options to pass to fireworks
112114 options = self.get_fireworks_chat_options(request)
modified llama_stack/providers/adapters/inference/ollama/ollama.py +7 −5
@@ -16,14 +16,16 @@
1616 from ollama import AsyncClient
1717
1818 from llama_stack.apis.inference import * # noqa: F403
19-from llama_stack.providers.utils.inference.prepare_messages import prepare_messages
19+from llama_stack.providers.utils.inference.augment_messages import (
20+ augment_messages_for_tools,
21+)
2022
2123 # TODO: Eventually this will move to the llama cli model list command
2224 # mapping of Model SKUs to ollama models
2325 OLLAMA_SUPPORTED_SKUS = {
24- # "Meta-Llama3.1-8B-Instruct": "llama3.1",
25- "Meta-Llama3.1-8B-Instruct": "llama3.1:8b-instruct-fp16",
26- "Meta-Llama3.1-70B-Instruct": "llama3.1:70b-instruct-fp16",
26+ # "Llama3.1-8B-Instruct": "llama3.1",
27+ "Llama3.1-8B-Instruct": "llama3.1:8b-instruct-fp16",
28+ "Llama3.1-70B-Instruct": "llama3.1:70b-instruct-fp16",
2729 }
2830
2931
@@ -115,7 +117,7 @@
115117 logprobs=logprobs,
116118 )
117119
118- messages = prepare_messages(request)
120+ messages = augment_messages_for_tools(request)
119121 # accumulate sampling params and other options to pass to ollama
120122 options = self.get_ollama_chat_options(request)
121123 ollama_model = self.resolve_ollama_model(request.model)
modified llama_stack/providers/adapters/inference/tgi/tgi.py +4 −2
@@ -14,7 +14,9 @@
1414 from llama_models.llama3.api.datatypes import StopReason
1515 from llama_models.llama3.api.tokenizer import Tokenizer
1616 from llama_stack.apis.inference import * # noqa: F403
17-from llama_stack.providers.utils.inference.prepare_messages import prepare_messages
17+from llama_stack.providers.utils.inference.augment_messages import (
18+ augment_messages_for_tools,
19+)
1820
1921 from .config import TGIImplConfig
2022
@@ -95,7 +97,7 @@
9597 logprobs=logprobs,
9698 )
9799
98- messages = prepare_messages(request)
100+ messages = augment_messages_for_tools(request)
99101 model_input = self.formatter.encode_dialog_prompt(messages)
100102 prompt = self.tokenizer.decode(model_input.tokens)
101103
modified llama_stack/providers/adapters/inference/together/together.py +7 −5
@@ -15,14 +15,16 @@
1515 from together import Together
1616
1717 from llama_stack.apis.inference import * # noqa: F403
18-from llama_stack.providers.utils.inference.prepare_messages import prepare_messages
18+from llama_stack.providers.utils.inference.augment_messages import (
19+ augment_messages_for_tools,
20+)
1921
2022 from .config import TogetherImplConfig
2123
2224 TOGETHER_SUPPORTED_MODELS = {
23- "Meta-Llama3.1-8B-Instruct": "meta-llama/Meta-Llama-3.1-8B-Instruct-Turbo",
24- "Meta-Llama3.1-70B-Instruct": "meta-llama/Meta-Llama-3.1-70B-Instruct-Turbo",
25- "Meta-Llama3.1-405B-Instruct": "meta-llama/Meta-Llama-3.1-405B-Instruct-Turbo",
25+ "Llama3.1-8B-Instruct": "meta-llama/Llama-3.1-8B-Instruct-Turbo",
26+ "Llama3.1-70B-Instruct": "meta-llama/Llama-3.1-70B-Instruct-Turbo",
27+ "Llama3.1-405B-Instruct": "meta-llama/Llama-3.1-405B-Instruct-Turbo",
2628 }
2729
2830
@@ -110,7 +112,7 @@
110112 # accumulate sampling params and other options to pass to together
111113 options = self.get_together_chat_options(request)
112114 together_model = self.resolve_together_model(request.model)
113- messages = prepare_messages(request)
115+ messages = augment_messages_for_tools(request)
114116
115117 if not request.stream:
116118 # TODO: might need to add back an async here
added llama_stack/providers/impls/ios/inference/LocalInference/LocalInference.xcodeproj/project.pbxproj +548 −0
@@ -0,0 +1,548 @@
1+// !$*UTF8*$!
2+{
3+ archiveVersion = 1;
4+ classes = {
5+ };
6+ objectVersion = 60;
7+ objects = {
8+
9+/* Begin PBXBuildFile section */
10+ 5C03561F2CA3AB9600E3BB46 /* LlamaStackClient in Frameworks */ = {isa = PBXBuildFile; productRef = 5C03561E2CA3AB9600E3BB46 /* LlamaStackClient */; };
11+ 5C5B6E212CA3D89F00AF6130 /* LlamaStackClient in Frameworks */ = {isa = PBXBuildFile; productRef = 5C5B6E202CA3D89F00AF6130 /* LlamaStackClient */; };
12+ 5CCBC60C2CA1F04A00E958D0 /* LocalInference.h in Headers */ = {isa = PBXBuildFile; fileRef = 5CCBC60B2CA1F04A00E958D0 /* LocalInference.h */; settings = {ATTRIBUTES = (Public, ); }; };
13+ 5CCBC6752CA1F45800E958D0 /* executorch_debug in Frameworks */ = {isa = PBXBuildFile; productRef = 5CCBC6742CA1F45800E958D0 /* executorch_debug */; };
14+ 5CCBC6862CA1F64A00E958D0 /* LLaMARunner.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 5CCBC6802CA1F63F00E958D0 /* LLaMARunner.framework */; platformFilter = ios; };
15+ 5CCBC6872CA1F64A00E958D0 /* LLaMARunner.framework in Embed Frameworks */ = {isa = PBXBuildFile; fileRef = 5CCBC6802CA1F63F00E958D0 /* LLaMARunner.framework */; platformFilter = ios; settings = {ATTRIBUTES = (CodeSignOnCopy, RemoveHeadersOnCopy, ); }; };
16+ 5CCBC68D2CA1F7A100E958D0 /* PromptTemplate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5CCBC6892CA1F7A000E958D0 /* PromptTemplate.swift */; };
17+ 5CCBC68E2CA1F7A100E958D0 /* LocalInference.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5CCBC68A2CA1F7A000E958D0 /* LocalInference.swift */; };
18+ 5CCBC68F2CA1F7A100E958D0 /* Parsing.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5CCBC68B2CA1F7A000E958D0 /* Parsing.swift */; };
19+ 5CCBC6902CA1F7A100E958D0 /* SystemPrompts.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5CCBC68C2CA1F7A100E958D0 /* SystemPrompts.swift */; };
20+ 5CCBC6932CA1F7D000E958D0 /* Stencil in Frameworks */ = {isa = PBXBuildFile; productRef = 5CCBC6922CA1F7D000E958D0 /* Stencil */; };
21+/* End PBXBuildFile section */
22+
23+/* Begin PBXContainerItemProxy section */
24+ 5CCBC67D2CA1F63F00E958D0 /* PBXContainerItemProxy */ = {
25+ isa = PBXContainerItemProxy;
26+ containerPortal = 5CCBC6762CA1F63F00E958D0 /* LLaMA.xcodeproj */;
27+ proxyType = 2;
28+ remoteGlobalIDString = 036CAF9D2BB1444500D6C2D5;
29+ remoteInfo = LLaMA;
30+ };
31+ 5CCBC67F2CA1F63F00E958D0 /* PBXContainerItemProxy */ = {
32+ isa = PBXContainerItemProxy;
33+ containerPortal = 5CCBC6762CA1F63F00E958D0 /* LLaMA.xcodeproj */;
34+ proxyType = 2;
35+ remoteGlobalIDString = 03729ED52BB1F8DE00152F2E;
36+ remoteInfo = LLaMARunner;
37+ };
38+ 5CCBC69E2CA2036B00E958D0 /* PBXContainerItemProxy */ = {
39+ isa = PBXContainerItemProxy;
40+ containerPortal = 5CCBC6762CA1F63F00E958D0 /* LLaMA.xcodeproj */;
41+ proxyType = 2;
42+ remoteGlobalIDString = 5CCBC6982CA2036A00E958D0;
43+ remoteInfo = LLaMAPerfBenchmark;
44+ };
45+ 5CCBC6A02CA2036B00E958D0 /* PBXContainerItemProxy */ = {
46+ isa = PBXContainerItemProxy;
47+ containerPortal = 5CCBC6762CA1F63F00E958D0 /* LLaMA.xcodeproj */;
48+ proxyType = 2;
49+ remoteGlobalIDString = 5CCBC6992CA2036A00E958D0;
50+ remoteInfo = LLaMAPerfBenchmarkTests;
51+ };
52+/* End PBXContainerItemProxy section */
53+
54+/* Begin PBXCopyFilesBuildPhase section */
55+ 5CCBC6882CA1F64A00E958D0 /* Embed Frameworks */ = {
56+ isa = PBXCopyFilesBuildPhase;
57+ buildActionMask = 2147483647;
58+ dstPath = "";
59+ dstSubfolderSpec = 10;
60+ files = (
61+ 5CCBC6872CA1F64A00E958D0 /* LLaMARunner.framework in Embed Frameworks */,
62+ );
63+ name = "Embed Frameworks";
64+ runOnlyForDeploymentPostprocessing = 0;
65+ };
66+/* End PBXCopyFilesBuildPhase section */
67+
68+/* Begin PBXFileReference section */
69+ 5CCBC6082CA1F04A00E958D0 /* LocalInference.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = LocalInference.framework; sourceTree = BUILT_PRODUCTS_DIR; };
70+ 5CCBC60B2CA1F04A00E958D0 /* LocalInference.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = LocalInference.h; sourceTree = "<group>"; };
71+ 5CCBC6762CA1F63F00E958D0 /* LLaMA.xcodeproj */ = {isa = PBXFileReference; lastKnownFileType = "wrapper.pb-project"; name = LLaMA.xcodeproj; path = "executorch/examples/demo-apps/apple_ios/LLaMA/LLaMA.xcodeproj"; sourceTree = "<group>"; };
72+ 5CCBC6892CA1F7A000E958D0 /* PromptTemplate.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PromptTemplate.swift; sourceTree = "<group>"; };
73+ 5CCBC68A2CA1F7A000E958D0 /* LocalInference.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = LocalInference.swift; sourceTree = "<group>"; };
74+ 5CCBC68B2CA1F7A000E958D0 /* Parsing.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Parsing.swift; sourceTree = "<group>"; };
75+ 5CCBC68C2CA1F7A100E958D0 /* SystemPrompts.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SystemPrompts.swift; sourceTree = "<group>"; };
76+/* End PBXFileReference section */
77+
78+/* Begin PBXFrameworksBuildPhase section */
79+ 5CCBC6052CA1F04A00E958D0 /* Frameworks */ = {
80+ isa = PBXFrameworksBuildPhase;
81+ buildActionMask = 2147483647;
82+ files = (
83+ 5C03561F2CA3AB9600E3BB46 /* LlamaStackClient in Frameworks */,
84+ 5C5B6E212CA3D89F00AF6130 /* LlamaStackClient in Frameworks */,
85+ 5CCBC6932CA1F7D000E958D0 /* Stencil in Frameworks */,
86+ 5CCBC6862CA1F64A00E958D0 /* LLaMARunner.framework in Frameworks */,
87+ 5CCBC6752CA1F45800E958D0 /* executorch_debug in Frameworks */,
88+ );
89+ runOnlyForDeploymentPostprocessing = 0;
90+ };
91+/* End PBXFrameworksBuildPhase section */
92+
93+/* Begin PBXGroup section */
94+ 5CCBC5FE2CA1F04A00E958D0 = {
95+ isa = PBXGroup;
96+ children = (
97+ 5CCBC6762CA1F63F00E958D0 /* LLaMA.xcodeproj */,
98+ 5CCBC60A2CA1F04A00E958D0 /* LocalInference */,
99+ 5CCBC6092CA1F04A00E958D0 /* Products */,
100+ 5CCBC6852CA1F64A00E958D0 /* Frameworks */,
101+ );
102+ sourceTree = "<group>";
103+ };
104+ 5CCBC6092CA1F04A00E958D0 /* Products */ = {
105+ isa = PBXGroup;
106+ children = (
107+ 5CCBC6082CA1F04A00E958D0 /* LocalInference.framework */,
108+ );
109+ name = Products;
110+ sourceTree = "<group>";
111+ };
112+ 5CCBC60A2CA1F04A00E958D0 /* LocalInference */ = {
113+ isa = PBXGroup;
114+ children = (
115+ 5CCBC68A2CA1F7A000E958D0 /* LocalInference.swift */,
116+ 5CCBC68B2CA1F7A000E958D0 /* Parsing.swift */,
117+ 5CCBC6892CA1F7A000E958D0 /* PromptTemplate.swift */,
118+ 5CCBC68C2CA1F7A100E958D0 /* SystemPrompts.swift */,
119+ 5CCBC60B2CA1F04A00E958D0 /* LocalInference.h */,
120+ );
121+ path = LocalInference;
122+ sourceTree = "<group>";
123+ };
124+ 5CCBC6772CA1F63F00E958D0 /* Products */ = {
125+ isa = PBXGroup;
126+ children = (
127+ 5CCBC67E2CA1F63F00E958D0 /* LLaMA.app */,
128+ 5CCBC6802CA1F63F00E958D0 /* LLaMARunner.framework */,
129+ 5CCBC69F2CA2036B00E958D0 /* LLaMAPerfBenchmark.app */,
130+ 5CCBC6A12CA2036B00E958D0 /* LLaMAPerfBenchmarkTests.xctest */,
131+ );
132+ name = Products;
133+ sourceTree = "<group>";
134+ };
135+ 5CCBC6852CA1F64A00E958D0 /* Frameworks */ = {
136+ isa = PBXGroup;
137+ children = (
138+ );
139+ name = Frameworks;
140+ sourceTree = "<group>";
141+ };
142+/* End PBXGroup section */
143+
144+/* Begin PBXHeadersBuildPhase section */
145+ 5CCBC6032CA1F04A00E958D0 /* Headers */ = {
146+ isa = PBXHeadersBuildPhase;
147+ buildActionMask = 2147483647;
148+ files = (
149+ 5CCBC60C2CA1F04A00E958D0 /* LocalInference.h in Headers */,
150+ );
151+ runOnlyForDeploymentPostprocessing = 0;
152+ };
153+/* End PBXHeadersBuildPhase section */
154+
155+/* Begin PBXNativeTarget section */
156+ 5CCBC6072CA1F04A00E958D0 /* LocalInference */ = {
157+ isa = PBXNativeTarget;
158+ buildConfigurationList = 5CCBC60F2CA1F04A00E958D0 /* Build configuration list for PBXNativeTarget "LocalInference" */;
159+ buildPhases = (
160+ 5CCBC6032CA1F04A00E958D0 /* Headers */,
161+ 5CCBC6042CA1F04A00E958D0 /* Sources */,
162+ 5CCBC6052CA1F04A00E958D0 /* Frameworks */,
163+ 5CCBC6062CA1F04A00E958D0 /* Resources */,
164+ 5CCBC6882CA1F64A00E958D0 /* Embed Frameworks */,
165+ );
166+ buildRules = (
167+ );
168+ dependencies = (
169+ );
170+ name = LocalInference;
171+ packageProductDependencies = (
172+ 5CCBC6742CA1F45800E958D0 /* executorch_debug */,
173+ 5CCBC6922CA1F7D000E958D0 /* Stencil */,
174+ 5C03561E2CA3AB9600E3BB46 /* LlamaStackClient */,
175+ 5C5B6E202CA3D89F00AF6130 /* LlamaStackClient */,
176+ );
177+ productName = LocalInferenceProvider;
178+ productReference = 5CCBC6082CA1F04A00E958D0 /* LocalInference.framework */;
179+ productType = "com.apple.product-type.framework";
180+ };
181+/* End PBXNativeTarget section */
182+
183+/* Begin PBXProject section */
184+ 5CCBC5FF2CA1F04A00E958D0 /* Project object */ = {
185+ isa = PBXProject;
186+ attributes = {
187+ BuildIndependentTargetsInParallel = 1;
188+ LastUpgradeCheck = 1540;
189+ TargetAttributes = {
190+ 5CCBC6072CA1F04A00E958D0 = {
191+ CreatedOnToolsVersion = 15.4;
192+ LastSwiftMigration = 1540;
193+ };
194+ };
195+ };
196+ buildConfigurationList = 5CCBC6022CA1F04A00E958D0 /* Build configuration list for PBXProject "LocalInference" */;
197+ compatibilityVersion = "Xcode 14.0";
198+ developmentRegion = en;
199+ hasScannedForEncodings = 0;
200+ knownRegions = (
201+ en,
202+ Base,
203+ );
204+ mainGroup = 5CCBC5FE2CA1F04A00E958D0;
205+ packageReferences = (
206+ 5CCBC6732CA1F45800E958D0 /* XCRemoteSwiftPackageReference "executorch" */,
207+ 5CCBC6912CA1F7D000E958D0 /* XCRemoteSwiftPackageReference "Stencil" */,
208+ 5C5B6E1F2CA3D89F00AF6130 /* XCLocalSwiftPackageReference "internal-llama-stack-client-swift" */,
209+ );
210+ productRefGroup = 5CCBC6092CA1F04A00E958D0 /* Products */;
211+ projectDirPath = "";
212+ projectReferences = (
213+ {
214+ ProductGroup = 5CCBC6772CA1F63F00E958D0 /* Products */;
215+ ProjectRef = 5CCBC6762CA1F63F00E958D0 /* LLaMA.xcodeproj */;
216+ },
217+ );
218+ projectRoot = "";
219+ targets = (
220+ 5CCBC6072CA1F04A00E958D0 /* LocalInference */,
221+ );
222+ };
223+/* End PBXProject section */
224+
225+/* Begin PBXReferenceProxy section */
226+ 5CCBC67E2CA1F63F00E958D0 /* LLaMA.app */ = {
227+ isa = PBXReferenceProxy;
228+ fileType = wrapper.application;
229+ path = LLaMA.app;
230+ remoteRef = 5CCBC67D2CA1F63F00E958D0 /* PBXContainerItemProxy */;
231+ sourceTree = BUILT_PRODUCTS_DIR;
232+ };
233+ 5CCBC6802CA1F63F00E958D0 /* LLaMARunner.framework */ = {
234+ isa = PBXReferenceProxy;
235+ fileType = wrapper.framework;
236+ path = LLaMARunner.framework;
237+ remoteRef = 5CCBC67F2CA1F63F00E958D0 /* PBXContainerItemProxy */;
238+ sourceTree = BUILT_PRODUCTS_DIR;
239+ };
240+ 5CCBC69F2CA2036B00E958D0 /* LLaMAPerfBenchmark.app */ = {
241+ isa = PBXReferenceProxy;
242+ fileType = wrapper.application;
243+ path = LLaMAPerfBenchmark.app;
244+ remoteRef = 5CCBC69E2CA2036B00E958D0 /* PBXContainerItemProxy */;
245+ sourceTree = BUILT_PRODUCTS_DIR;
246+ };
247+ 5CCBC6A12CA2036B00E958D0 /* LLaMAPerfBenchmarkTests.xctest */ = {
248+ isa = PBXReferenceProxy;
249+ fileType = wrapper.cfbundle;
250+ path = LLaMAPerfBenchmarkTests.xctest;
251+ remoteRef = 5CCBC6A02CA2036B00E958D0 /* PBXContainerItemProxy */;
252+ sourceTree = BUILT_PRODUCTS_DIR;
253+ };
254+/* End PBXReferenceProxy section */
255+
256+/* Begin PBXResourcesBuildPhase section */
257+ 5CCBC6062CA1F04A00E958D0 /* Resources */ = {
258+ isa = PBXResourcesBuildPhase;
259+ buildActionMask = 2147483647;
260+ files = (
261+ );
262+ runOnlyForDeploymentPostprocessing = 0;
263+ };
264+/* End PBXResourcesBuildPhase section */
265+
266+/* Begin PBXSourcesBuildPhase section */
267+ 5CCBC6042CA1F04A00E958D0 /* Sources */ = {
268+ isa = PBXSourcesBuildPhase;
269+ buildActionMask = 2147483647;
270+ files = (
271+ 5CCBC6902CA1F7A100E958D0 /* SystemPrompts.swift in Sources */,
272+ 5CCBC68D2CA1F7A100E958D0 /* PromptTemplate.swift in Sources */,
273+ 5CCBC68F2CA1F7A100E958D0 /* Parsing.swift in Sources */,
274+ 5CCBC68E2CA1F7A100E958D0 /* LocalInference.swift in Sources */,
275+ );
276+ runOnlyForDeploymentPostprocessing = 0;
277+ };
278+/* End PBXSourcesBuildPhase section */
279+
280+/* Begin XCBuildConfiguration section */
281+ 5CCBC60D2CA1F04A00E958D0 /* Debug */ = {
282+ isa = XCBuildConfiguration;
283+ buildSettings = {
284+ ALWAYS_SEARCH_USER_PATHS = NO;
285+ ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES;
286+ CLANG_ANALYZER_NONNULL = YES;
287+ CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE;
288+ CLANG_CXX_LANGUAGE_STANDARD = "gnu++20";
289+ CLANG_ENABLE_MODULES = YES;
290+ CLANG_ENABLE_OBJC_ARC = YES;
291+ CLANG_ENABLE_OBJC_WEAK = YES;
292+ CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES;
293+ CLANG_WARN_BOOL_CONVERSION = YES;
294+ CLANG_WARN_COMMA = YES;
295+ CLANG_WARN_CONSTANT_CONVERSION = YES;
296+ CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES;
297+ CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR;
298+ CLANG_WARN_DOCUMENTATION_COMMENTS = YES;
299+ CLANG_WARN_EMPTY_BODY = YES;
300+ CLANG_WARN_ENUM_CONVERSION = YES;
301+ CLANG_WARN_INFINITE_RECURSION = YES;
302+ CLANG_WARN_INT_CONVERSION = YES;
303+ CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES;
304+ CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES;
305+ CLANG_WARN_OBJC_LITERAL_CONVERSION = YES;
306+ CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR;
307+ CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = YES;
308+ CLANG_WARN_RANGE_LOOP_ANALYSIS = YES;
309+ CLANG_WARN_STRICT_PROTOTYPES = YES;
310+ CLANG_WARN_SUSPICIOUS_MOVE = YES;
311+ CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE;
312+ CLANG_WARN_UNREACHABLE_CODE = YES;
313+ CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;
314+ COPY_PHASE_STRIP = NO;
315+ CURRENT_PROJECT_VERSION = 1;
316+ DEBUG_INFORMATION_FORMAT = dwarf;
317+ ENABLE_STRICT_OBJC_MSGSEND = YES;
318+ ENABLE_TESTABILITY = YES;
319+ ENABLE_USER_SCRIPT_SANDBOXING = YES;
320+ GCC_C_LANGUAGE_STANDARD = gnu17;
321+ GCC_DYNAMIC_NO_PIC = NO;
322+ GCC_NO_COMMON_BLOCKS = YES;
323+ GCC_OPTIMIZATION_LEVEL = 0;
324+ GCC_PREPROCESSOR_DEFINITIONS = (
325+ "DEBUG=1",
326+ "$(inherited)",
327+ );
328+ GCC_WARN_64_TO_32_BIT_CONVERSION = YES;
329+ GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR;
330+ GCC_WARN_UNDECLARED_SELECTOR = YES;
331+ GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
332+ GCC_WARN_UNUSED_FUNCTION = YES;
333+ GCC_WARN_UNUSED_VARIABLE = YES;
334+ IPHONEOS_DEPLOYMENT_TARGET = 17.5;
335+ LOCALIZATION_PREFERS_STRING_CATALOGS = YES;
336+ MTL_ENABLE_DEBUG_INFO = INCLUDE_SOURCE;
337+ MTL_FAST_MATH = YES;
338+ ONLY_ACTIVE_ARCH = YES;
339+ SDKROOT = iphoneos;
340+ SWIFT_ACTIVE_COMPILATION_CONDITIONS = "DEBUG $(inherited)";
341+ SWIFT_OPTIMIZATION_LEVEL = "-Onone";
342+ VERSIONING_SYSTEM = "apple-generic";
343+ VERSION_INFO_PREFIX = "";
344+ };
345+ name = Debug;
346+ };
347+ 5CCBC60E2CA1F04A00E958D0 /* Release */ = {
348+ isa = XCBuildConfiguration;
349+ buildSettings = {
350+ ALWAYS_SEARCH_USER_PATHS = NO;
351+ ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES;
352+ CLANG_ANALYZER_NONNULL = YES;
353+ CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE;
354+ CLANG_CXX_LANGUAGE_STANDARD = "gnu++20";
355+ CLANG_ENABLE_MODULES = YES;
356+ CLANG_ENABLE_OBJC_ARC = YES;
357+ CLANG_ENABLE_OBJC_WEAK = YES;
358+ CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES;
359+ CLANG_WARN_BOOL_CONVERSION = YES;
360+ CLANG_WARN_COMMA = YES;
361+ CLANG_WARN_CONSTANT_CONVERSION = YES;
362+ CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES;
363+ CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR;
364+ CLANG_WARN_DOCUMENTATION_COMMENTS = YES;
365+ CLANG_WARN_EMPTY_BODY = YES;
366+ CLANG_WARN_ENUM_CONVERSION = YES;
367+ CLANG_WARN_INFINITE_RECURSION = YES;
368+ CLANG_WARN_INT_CONVERSION = YES;
369+ CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES;
370+ CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES;
371+ CLANG_WARN_OBJC_LITERAL_CONVERSION = YES;
372+ CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR;
373+ CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = YES;
374+ CLANG_WARN_RANGE_LOOP_ANALYSIS = YES;
375+ CLANG_WARN_STRICT_PROTOTYPES = YES;
376+ CLANG_WARN_SUSPICIOUS_MOVE = YES;
377+ CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE;
378+ CLANG_WARN_UNREACHABLE_CODE = YES;
379+ CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;
380+ COPY_PHASE_STRIP = NO;
381+ CURRENT_PROJECT_VERSION = 1;
382+ DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym";
383+ ENABLE_NS_ASSERTIONS = NO;
384+ ENABLE_STRICT_OBJC_MSGSEND = YES;
385+ ENABLE_USER_SCRIPT_SANDBOXING = YES;
386+ GCC_C_LANGUAGE_STANDARD = gnu17;
387+ GCC_NO_COMMON_BLOCKS = YES;
388+ GCC_WARN_64_TO_32_BIT_CONVERSION = YES;
389+ GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR;
390+ GCC_WARN_UNDECLARED_SELECTOR = YES;
391+ GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
392+ GCC_WARN_UNUSED_FUNCTION = YES;
393+ GCC_WARN_UNUSED_VARIABLE = YES;
394+ IPHONEOS_DEPLOYMENT_TARGET = 17.5;
395+ LOCALIZATION_PREFERS_STRING_CATALOGS = YES;
396+ MTL_ENABLE_DEBUG_INFO = NO;
397+ MTL_FAST_MATH = YES;
398+ SDKROOT = iphoneos;
399+ SWIFT_COMPILATION_MODE = wholemodule;
400+ VALIDATE_PRODUCT = YES;
401+ VERSIONING_SYSTEM = "apple-generic";
402+ VERSION_INFO_PREFIX = "";
403+ };
404+ name = Release;
405+ };
406+ 5CCBC6102CA1F04A00E958D0 /* Debug */ = {
407+ isa = XCBuildConfiguration;
408+ buildSettings = {
409+ BUILD_LIBRARY_FOR_DISTRIBUTION = YES;
410+ CLANG_ENABLE_MODULES = YES;
411+ CODE_SIGN_STYLE = Automatic;
412+ CURRENT_PROJECT_VERSION = 1;
413+ DEFINES_MODULE = YES;
414+ DYLIB_COMPATIBILITY_VERSION = 1;
415+ DYLIB_CURRENT_VERSION = 1;
416+ DYLIB_INSTALL_NAME_BASE = "@rpath";
417+ ENABLE_MODULE_VERIFIER = YES;
418+ GENERATE_INFOPLIST_FILE = YES;
419+ HEADER_SEARCH_PATHS = "";
420+ INFOPLIST_KEY_NSHumanReadableCopyright = "";
421+ INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks";
422+ LD_RUNPATH_SEARCH_PATHS = (
423+ "$(inherited)",
424+ "@executable_path/Frameworks",
425+ "@loader_path/Frameworks",
426+ );
427+ MARKETING_VERSION = 1.0;
428+ MODULE_VERIFIER_SUPPORTED_LANGUAGES = "objective-c objective-c++";
429+ MODULE_VERIFIER_SUPPORTED_LANGUAGE_STANDARDS = "gnu17 gnu++20";
430+ OTHER_LDFLAGS = "";
431+ PRODUCT_BUNDLE_IDENTIFIER = meta.llamatsack.LocalInferenceProvider;
432+ PRODUCT_NAME = "$(TARGET_NAME:c99extidentifier)";
433+ SKIP_INSTALL = YES;
434+ SWIFT_EMIT_LOC_STRINGS = YES;
435+ SWIFT_INSTALL_OBJC_HEADER = NO;
436+ SWIFT_OPTIMIZATION_LEVEL = "-Onone";
437+ SWIFT_VERSION = 5.0;
438+ TARGETED_DEVICE_FAMILY = "1,2";
439+ };
440+ name = Debug;
441+ };
442+ 5CCBC6112CA1F04A00E958D0 /* Release */ = {
443+ isa = XCBuildConfiguration;
444+ buildSettings = {
445+ BUILD_LIBRARY_FOR_DISTRIBUTION = YES;
446+ CLANG_ENABLE_MODULES = YES;
447+ CODE_SIGN_STYLE = Automatic;
448+ CURRENT_PROJECT_VERSION = 1;
449+ DEFINES_MODULE = YES;
450+ DYLIB_COMPATIBILITY_VERSION = 1;
451+ DYLIB_CURRENT_VERSION = 1;
452+ DYLIB_INSTALL_NAME_BASE = "@rpath";
453+ ENABLE_MODULE_VERIFIER = YES;
454+ GENERATE_INFOPLIST_FILE = YES;
455+ HEADER_SEARCH_PATHS = "";
456+ INFOPLIST_KEY_NSHumanReadableCopyright = "";
457+ INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks";
458+ LD_RUNPATH_SEARCH_PATHS = (
459+ "$(inherited)",
460+ "@executable_path/Frameworks",
461+ "@loader_path/Frameworks",
462+ );
463+ MARKETING_VERSION = 1.0;
464+ MODULE_VERIFIER_SUPPORTED_LANGUAGES = "objective-c objective-c++";
465+ MODULE_VERIFIER_SUPPORTED_LANGUAGE_STANDARDS = "gnu17 gnu++20";
466+ OTHER_LDFLAGS = "";
467+ PRODUCT_BUNDLE_IDENTIFIER = meta.llamatsack.LocalInferenceProvider;
468+ PRODUCT_NAME = "$(TARGET_NAME:c99extidentifier)";
469+ SKIP_INSTALL = YES;
470+ SWIFT_EMIT_LOC_STRINGS = YES;
471+ SWIFT_INSTALL_OBJC_HEADER = NO;
472+ SWIFT_VERSION = 5.0;
473+ TARGETED_DEVICE_FAMILY = "1,2";
474+ };
475+ name = Release;
476+ };
477+/* End XCBuildConfiguration section */
478+
479+/* Begin XCConfigurationList section */
480+ 5CCBC6022CA1F04A00E958D0 /* Build configuration list for PBXProject "LocalInference" */ = {
481+ isa = XCConfigurationList;
482+ buildConfigurations = (
483+ 5CCBC60D2CA1F04A00E958D0 /* Debug */,
484+ 5CCBC60E2CA1F04A00E958D0 /* Release */,
485+ );
486+ defaultConfigurationIsVisible = 0;
487+ defaultConfigurationName = Release;
488+ };
489+ 5CCBC60F2CA1F04A00E958D0 /* Build configuration list for PBXNativeTarget "LocalInference" */ = {
490+ isa = XCConfigurationList;
491+ buildConfigurations = (
492+ 5CCBC6102CA1F04A00E958D0 /* Debug */,
493+ 5CCBC6112CA1F04A00E958D0 /* Release */,
494+ );
495+ defaultConfigurationIsVisible = 0;
496+ defaultConfigurationName = Release;
497+ };
498+/* End XCConfigurationList section */
499+
500+/* Begin XCLocalSwiftPackageReference section */
501+ 5C5B6E1F2CA3D89F00AF6130 /* XCLocalSwiftPackageReference "internal-llama-stack-client-swift" */ = {
502+ isa = XCLocalSwiftPackageReference;
503+ relativePath = "internal-llama-stack-client-swift";
504+ };
505+/* End XCLocalSwiftPackageReference section */
506+
507+/* Begin XCRemoteSwiftPackageReference section */
508+ 5CCBC6732CA1F45800E958D0 /* XCRemoteSwiftPackageReference "executorch" */ = {
509+ isa = XCRemoteSwiftPackageReference;
510+ repositoryURL = "https://github.com/pytorch/executorch";
511+ requirement = {
512+ branch = latest;
513+ kind = branch;
514+ };
515+ };
516+ 5CCBC6912CA1F7D000E958D0 /* XCRemoteSwiftPackageReference "Stencil" */ = {
517+ isa = XCRemoteSwiftPackageReference;
518+ repositoryURL = "https://github.com/stencilproject/Stencil";
519+ requirement = {
520+ kind = upToNextMajorVersion;
521+ minimumVersion = 0.15.1;
522+ };
523+ };
524+/* End XCRemoteSwiftPackageReference section */
525+
526+/* Begin XCSwiftPackageProductDependency section */
527+ 5C03561E2CA3AB9600E3BB46 /* LlamaStackClient */ = {
528+ isa = XCSwiftPackageProductDependency;
529+ productName = LlamaStackClient;
530+ };
531+ 5C5B6E202CA3D89F00AF6130 /* LlamaStackClient */ = {
532+ isa = XCSwiftPackageProductDependency;
533+ productName = LlamaStackClient;
534+ };
535+ 5CCBC6742CA1F45800E958D0 /* executorch_debug */ = {
536+ isa = XCSwiftPackageProductDependency;
537+ package = 5CCBC6732CA1F45800E958D0 /* XCRemoteSwiftPackageReference "executorch" */;
538+ productName = executorch_debug;
539+ };
540+ 5CCBC6922CA1F7D000E958D0 /* Stencil */ = {
541+ isa = XCSwiftPackageProductDependency;
542+ package = 5CCBC6912CA1F7D000E958D0 /* XCRemoteSwiftPackageReference "Stencil" */;
543+ productName = Stencil;
544+ };
545+/* End XCSwiftPackageProductDependency section */
546+ };
547+ rootObject = 5CCBC5FF2CA1F04A00E958D0 /* Project object */;
548+}
added llama_stack/providers/impls/ios/inference/LocalInference/LocalInference.xcodeproj/project.xcworkspace/contents.xcworkspacedata +7 −0
@@ -0,0 +1,7 @@
1+<?xml version="1.0" encoding="UTF-8"?>
2+<Workspace
3+ version = "1.0">
4+ <FileRef
5+ location = "self:">
6+ </FileRef>
7+</Workspace>
added llama_stack/providers/impls/ios/inference/LocalInference/LocalInference.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist +8 −0
@@ -0,0 +1,8 @@
1+<?xml version="1.0" encoding="UTF-8"?>
2+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
3+<plist version="1.0">
4+<dict>
5+ <key>IDEDidComputeMac32BitWarning</key>
6+ <true/>
7+</dict>
8+</plist>
added llama_stack/providers/impls/ios/inference/LocalInference/LocalInference/LocalInference.h +16 −0
@@ -0,0 +1,16 @@
1+//
2+// LocalInference.h
3+// LocalInference
4+//
5+// Created by Dalton Flanagan on 9/23/24.
6+//
7+
8+#import <Foundation/Foundation.h>
9+
10+//! Project version number for LocalInference.
11+FOUNDATION_EXPORT double LocalInferenceVersionNumber;
12+
13+//! Project version string for LocalInference.
14+FOUNDATION_EXPORT const unsigned char LocalInferenceVersionString[];
15+
16+// In this header, you should import all the public headers of your framework using statements like #import <LocalInference/PublicHeader.h>
added llama_stack/providers/impls/ios/inference/LocalInference/LocalInference/LocalInference.swift +167 −0
@@ -0,0 +1,167 @@
1+import Foundation
2+
3+import LLaMARunner
4+import LlamaStackClient
5+
6+class RunnerHolder: ObservableObject {
7+ var runner: Runner?
8+}
9+
10+public class LocalInference: Inference {
11+ private var runnerHolder = RunnerHolder()
12+ private let runnerQueue: DispatchQueue
13+
14+ public init (queue: DispatchQueue) {
15+ runnerQueue = queue
16+ }
17+
18+ public func loadModel(modelPath: String, tokenizerPath: String, completion: @escaping (Result<Void, Error>) -> Void) {
19+ runnerHolder.runner = runnerHolder.runner ?? Runner(
20+ modelPath: modelPath,
21+ tokenizerPath: tokenizerPath
22+ )
23+
24+
25+ runnerQueue.async {
26+ let runner = self.runnerHolder.runner
27+ do {
28+ try runner!.load()
29+ completion(.success(()))
30+ } catch let loadError {
31+ print("error: " + loadError.localizedDescription)
32+ completion(.failure(loadError))
33+ }
34+ }
35+ }
36+
37+ public func chatCompletion(request: Components.Schemas.ChatCompletionRequest) -> AsyncStream<Components.Schemas.ChatCompletionResponseStreamChunk> {
38+ return AsyncStream { continuation in
39+ runnerQueue.async {
40+ do {
41+ var tokens: [String] = []
42+
43+ let prompt = try encodeDialogPrompt(messages: prepareMessages(request: request))
44+ var stopReason: Components.Schemas.StopReason? = nil
45+ var buffer = ""
46+ var ipython = false
47+ var echoDropped = false
48+
49+ try self.runnerHolder.runner?.generate(prompt, sequenceLength: 4096) { token in
50+ buffer += token
51+
52+ // HACK: Workaround until LlamaRunner exposes echo param
53+ if (!echoDropped) {
54+ if (buffer.hasPrefix(prompt)) {
55+ buffer = String(buffer.dropFirst(prompt.count))
56+ echoDropped = true
57+ }
58+ return
59+ }
60+
61+ tokens.append(token)
62+
63+ if !ipython && (buffer.starts(with: "<|python_tag|>") || buffer.starts(with: "[") ) {
64+ ipython = true
65+ continuation.yield(
66+ Components.Schemas.ChatCompletionResponseStreamChunk(
67+ event: Components.Schemas.ChatCompletionResponseEvent(
68+ delta: .ToolCallDelta(Components.Schemas.ToolCallDelta(
69+ content: .case1(""),
70+ parse_status: Components.Schemas.ToolCallParseStatus.started
71+ )
72+ ),
73+ event_type: .progress
74+ )
75+ )
76+ )
77+
78+ if (buffer.starts(with: "<|python_tag|>")) {
79+ buffer = String(buffer.dropFirst("<|python_tag|>".count))
80+ }
81+ }
82+
83+ // TODO: Non-streaming lobprobs
84+
85+ var text = ""
86+ if token == "<|eot_id|>" {
87+ stopReason = Components.Schemas.StopReason.end_of_turn
88+ } else if token == "<|eom_id|>" {
89+ stopReason = Components.Schemas.StopReason.end_of_message
90+ } else {
91+ text = token
92+ }
93+
94+ var delta: Components.Schemas.ChatCompletionResponseEvent.deltaPayload
95+ if ipython {
96+ delta = .ToolCallDelta(Components.Schemas.ToolCallDelta(
97+ content: .case1(text),
98+ parse_status: .in_progress
99+ ))
100+ } else {
101+ delta = .case1(text)
102+ }
103+
104+ if stopReason == nil {
105+ continuation.yield(
106+ Components.Schemas.ChatCompletionResponseStreamChunk(
107+ event: Components.Schemas.ChatCompletionResponseEvent(
108+ delta: delta,
109+ event_type: .progress
110+ )
111+ )
112+ )
113+ }
114+ }
115+
116+ if stopReason == nil {
117+ stopReason = Components.Schemas.StopReason.out_of_tokens
118+ }
119+
120+ let message = decodeAssistantMessage(tokens: tokens.joined(), stopReason: stopReason!)
121+ // TODO: non-streaming support
122+
123+ let didParseToolCalls = message.tool_calls.count > 0
124+ if ipython && !didParseToolCalls {
125+ continuation.yield(
126+ Components.Schemas.ChatCompletionResponseStreamChunk(
127+ event: Components.Schemas.ChatCompletionResponseEvent(
128+ delta: .ToolCallDelta(Components.Schemas.ToolCallDelta(content: .case1(""), parse_status: .failure)),
129+ event_type: .progress
130+ )
131+ // TODO: stopReason
132+ )
133+ )
134+ }
135+
136+ for toolCall in message.tool_calls {
137+ continuation.yield(
138+ Components.Schemas.ChatCompletionResponseStreamChunk(
139+ event: Components.Schemas.ChatCompletionResponseEvent(
140+ delta: .ToolCallDelta(Components.Schemas.ToolCallDelta(
141+ content: .ToolCall(toolCall),
142+ parse_status: .success
143+ )),
144+ event_type: .progress
145+ )
146+ // TODO: stopReason
147+ )
148+ )
149+ }
150+
151+ continuation.yield(
152+ Components.Schemas.ChatCompletionResponseStreamChunk(
153+ event: Components.Schemas.ChatCompletionResponseEvent(
154+ delta: .case1(""),
155+ event_type: .complete
156+ )
157+ // TODO: stopReason
158+ )
159+ )
160+ }
161+ catch (let error) {
162+ print("Inference error: " + error.localizedDescription)
163+ }
164+ }
165+ }
166+ }
167+}
added llama_stack/providers/impls/ios/inference/LocalInference/LocalInference/Parsing.swift +235 −0
@@ -0,0 +1,235 @@
1+import Foundation
2+
3+import LlamaStackClient
4+
5+func encodeHeader(role: String) -> String {
6+ return "<|start_header_id|>\(role)<|end_header_id|>\n\n"
7+}
8+
9+func encodeDialogPrompt(messages: [Components.Schemas.ChatCompletionRequest.messagesPayloadPayload]) -> String {
10+ var prompt = ""
11+
12+ prompt.append("<|begin_of_text|>")
13+ for message in messages {
14+ let msg = encodeMessage(message: message)
15+ prompt += msg
16+ }
17+
18+ prompt.append(encodeHeader(role: "assistant"))
19+
20+ return prompt
21+}
22+
23+func getRole(message: Components.Schemas.ChatCompletionRequest.messagesPayloadPayload) -> String {
24+ switch (message) {
25+ case .UserMessage(let m):
26+ return m.role.rawValue
27+ case .SystemMessage(let m):
28+ return m.role.rawValue
29+ case .ToolResponseMessage(let m):
30+ return m.role.rawValue
31+ case .CompletionMessage(let m):
32+ return m.role.rawValue
33+ }
34+}
35+
36+func encodeMessage(message: Components.Schemas.ChatCompletionRequest.messagesPayloadPayload) -> String {
37+ var prompt = encodeHeader(role: getRole(message: message))
38+
39+ switch (message) {
40+ case .CompletionMessage(let m):
41+ if (m.tool_calls.count > 0) {
42+ prompt += "<|python_tag|>"
43+ }
44+ default:
45+ break
46+ }
47+
48+ func _processContent(_ content: Any) -> String {
49+ func _process(_ c: Any) {
50+ if let str = c as? String {
51+ prompt += str
52+ }
53+ }
54+
55+ if let str = content as? String {
56+ _process(str)
57+ } else if let list = content as? [Any] {
58+ for c in list {
59+ _process(c)
60+ }
61+ }
62+
63+ return ""
64+ }
65+
66+ switch (message) {
67+ case .UserMessage(let m):
68+ prompt += _processContent(m.content)
69+ case .SystemMessage(let m):
70+ prompt += _processContent(m.content)
71+ case .ToolResponseMessage(let m):
72+ prompt += _processContent(m.content)
73+ case .CompletionMessage(let m):
74+ prompt += _processContent(m.content)
75+ }
76+
77+ var eom = false
78+
79+ switch (message) {
80+ case .UserMessage(let m):
81+ switch (m.content) {
82+ case .case1(let c):
83+ prompt += _processContent(c)
84+ case .case2(let c):
85+ prompt += _processContent(c)
86+ }
87+ case .CompletionMessage(let m):
88+ // TODO: Support encoding past tool call history
89+ // for t in m.tool_calls {
90+ // _processContent(t.)
91+ //}
92+ eom = m.stop_reason == Components.Schemas.StopReason.end_of_message
93+ case .SystemMessage(_):
94+ break
95+ case .ToolResponseMessage(_):
96+ break
97+ }
98+
99+ if (eom) {
100+ prompt += "<|eom_id|>"
101+ } else {
102+ prompt += "<|eot_id|>"
103+ }
104+
105+ return prompt
106+}
107+
108+func prepareMessages(request: Components.Schemas.ChatCompletionRequest) throws -> [Components.Schemas.ChatCompletionRequest.messagesPayloadPayload] {
109+ var existingMessages = request.messages
110+ var existingSystemMessage: Components.Schemas.ChatCompletionRequest.messagesPayloadPayload?
111+ // TODO: Existing system message
112+
113+ var messages: [Components.Schemas.ChatCompletionRequest.messagesPayloadPayload] = []
114+
115+ let defaultGen = SystemDefaultGenerator()
116+ let defaultTemplate = defaultGen.gen()
117+
118+ var sysContent = ""
119+
120+ // TODO: Built-in tools
121+
122+ sysContent += try defaultTemplate.render()
123+
124+ messages.append(.SystemMessage(Components.Schemas.SystemMessage(
125+ content: .case1(sysContent),
126+ role: .system))
127+ )
128+
129+ if request.tools?.isEmpty == false {
130+ // TODO: Separate built-ins and custom tools (right now everything treated as custom)
131+ let toolGen = FunctionTagCustomToolGenerator()
132+ let toolTemplate = try toolGen.gen(customTools: request.tools!)
133+ let tools = try toolTemplate.render()
134+ messages.append(.UserMessage(Components.Schemas.UserMessage(
135+ content: .case1(tools),
136+ role: .user)
137+ ))
138+ }
139+
140+ messages.append(contentsOf: existingMessages)
141+
142+ return messages
143+}
144+
145+struct FunctionCall {
146+ let name: String
147+ let params: [String: Any]
148+}
149+
150+public func maybeExtractCustomToolCalls(input: String) -> [Components.Schemas.ToolCall] {
151+ guard input.hasPrefix("[") && input.hasSuffix("]") else {
152+ return []
153+ }
154+
155+ do {
156+ let trimmed = input.trimmingCharacters(in: CharacterSet(charactersIn: "[]"))
157+ let calls = trimmed.components(separatedBy: "),").map { $0.hasSuffix(")") ? $0 : $0 + ")" }
158+
159+ var result: [Components.Schemas.ToolCall] = []
160+
161+ for call in calls {
162+ guard let nameEndIndex = call.firstIndex(of: "("),
163+ let paramsStartIndex = call.firstIndex(of: "{"),
164+ let paramsEndIndex = call.lastIndex(of: "}") else {
165+ return []
166+ }
167+
168+ let name = String(call[..<nameEndIndex]).trimmingCharacters(in: .whitespacesAndNewlines)
169+ let paramsString = String(call[paramsStartIndex...paramsEndIndex])
170+
171+ guard let data = paramsString.data(using: .utf8),
172+ let params = try? JSONSerialization.jsonObject(with: data, options: []) as? [String: Any] else {
173+ return []
174+ }
175+
176+ var props: [String : Components.Schemas.ToolCall.argumentsPayload.additionalPropertiesPayload] = [:]
177+ for (param_name, param) in params {
178+ switch (param) {
179+ case let value as String:
180+ props[param_name] = .case1(value)
181+ case let value as Int:
182+ props[param_name] = .case2(value)
183+ case let value as Double:
184+ props[param_name] = .case3(value)
185+ case let value as Bool:
186+ props[param_name] = .case4(value)
187+ default:
188+ return []
189+ }
190+ }
191+
192+ result.append(
193+ Components.Schemas.ToolCall(
194+ arguments: .init(additionalProperties: props),
195+ call_id: UUID().uuidString,
196+ tool_name: .case2(name) // custom_tool
197+ )
198+ )
199+ }
200+
201+ return result.isEmpty ? [] : result
202+ } catch {
203+ return []
204+ }
205+}
206+
207+func decodeAssistantMessage(tokens: String, stopReason: Components.Schemas.StopReason) -> Components.Schemas.CompletionMessage {
208+ var content = tokens
209+
210+ let roles = ["user", "system", "assistant"]
211+ for role in roles {
212+ let headerStr = encodeHeader(role: role)
213+ if content.hasPrefix(headerStr) {
214+ content = String(content.dropFirst(encodeHeader(role: role).count))
215+ }
216+ }
217+
218+ if content.hasPrefix("<|python_tag|>") {
219+ content = String(content.dropFirst("<|python_tag|>".count))
220+ }
221+
222+
223+ if content.hasSuffix("<|eot_id|>") {
224+ content = String(content.dropLast("<|eot_id|>".count))
225+ } else {
226+ content = String(content.dropLast("<|eom_id|>".count))
227+ }
228+
229+ return Components.Schemas.CompletionMessage(
230+ content: .case1(content),
231+ role: .assistant,
232+ stop_reason: stopReason,
233+ tool_calls: maybeExtractCustomToolCalls(input: content)
234+ )
235+}
added llama_stack/providers/impls/ios/inference/LocalInference/LocalInference/PromptTemplate.swift +12 −0
@@ -0,0 +1,12 @@
1+import Foundation
2+import Stencil
3+
4+public struct PromptTemplate {
5+ let template: String
6+ let data: [String: Any]
7+
8+ public func render() throws -> String {
9+ let template = Template(templateString: self.template)
10+ return try template.render(self.data)
11+ }
12+}
added llama_stack/providers/impls/ios/inference/LocalInference/LocalInference/SystemPrompts.swift +91 −0
@@ -0,0 +1,91 @@
1+import Foundation
2+
3+import LlamaStackClient
4+
5+func convertToNativeSwiftType(_ value: Any) -> Any {
6+ switch value {
7+ case let number as NSNumber:
8+ if CFGetTypeID(number) == CFBooleanGetTypeID() {
9+ return number.boolValue
10+ }
11+ if floor(number.doubleValue) == number.doubleValue {
12+ return number.intValue
13+ }
14+ return number.doubleValue
15+ case let string as String:
16+ return string
17+ case let array as [Any]:
18+ return array.map(convertToNativeSwiftType)
19+ case let dict as [String: Any]:
20+ return dict.mapValues(convertToNativeSwiftType)
21+ case is NSNull:
22+ return NSNull()
23+ default:
24+ return value
25+ }
26+}
27+
28+public class SystemDefaultGenerator {
29+ public init() {}
30+
31+ public func gen() -> PromptTemplate {
32+ let templateStr = """
33+ Cutting Knowledge Date: December 2023
34+ Today Date: {{ today }}
35+ """
36+
37+ let dateFormatter = DateFormatter()
38+ dateFormatter.dateFormat = "dd MMMM yyyy"
39+
40+ return PromptTemplate(
41+ template: templateStr,
42+ data: ["today": dateFormatter.string(from: Date())]
43+ )
44+ }
45+}
46+
47+
48+public class FunctionTagCustomToolGenerator {
49+ public init() {}
50+
51+ public func gen(customTools: [Components.Schemas.ToolDefinition]) throws -> PromptTemplate {
52+ // TODO: required params
53+ // TODO: {{#unless @last}},{{/unless}}
54+
55+ let templateStr = """
56+ You are an expert in composing functions. You are given a question and a set of possible functions.
57+ Based on the question, you will need to make one or more function/tool calls to achieve the purpose.
58+ If none of the function can be used, point it out. If the given question lacks the parameters required by the function,
59+ also point it out. You should only return the function call in tools call sections.
60+
61+ If you decide to invoke any of the function(s), you MUST put it in the format of [func_name1(params_name1=params_value1, params_name2=params_value2...), func_name2(params)]
62+ You SHOULD NOT include any other text in the response.
63+
64+ Here is a list of functions in JSON format that you can invoke.
65+
66+ [
67+ {% for t in custom_tools %}
68+ {
69+ "name": "{{t.tool_name}}",
70+ "description": "{{t.description}}",
71+ "parameters": {
72+ "type": "dict",
73+ "properties": { {{t.parameters}} }
74+ }
75+
76+ {{/let}}
77+ {% endfor -%}
78+ ]
79+ """
80+
81+ let encoder = JSONEncoder()
82+ return PromptTemplate(
83+ template: templateStr,
84+ data: ["custom_tools": try customTools.map {
85+ let data = try encoder.encode($0)
86+ let obj = try JSONSerialization.jsonObject(with: data)
87+ return convertToNativeSwiftType(obj)
88+ }]
89+ )
90+ }
91+}
added llama_stack/providers/impls/ios/inference/LocalInference/LocalInferenceImpl.xcodeproj/project.pbxproj +541 −0
@@ -0,0 +1,541 @@
1+// !$*UTF8*$!
2+{
3+ archiveVersion = 1;
4+ classes = {
5+ };
6+ objectVersion = 60;
7+ objects = {
8+
9+/* Begin PBXBuildFile section */
10+ 5CADC71A2CA471CC007662D2 /* LlamaStackClient in Frameworks */ = {isa = PBXBuildFile; productRef = 5CADC7192CA471CC007662D2 /* LlamaStackClient */; };
11+ 5CCBC60C2CA1F04A00E958D0 /* LocalInference.h in Headers */ = {isa = PBXBuildFile; fileRef = 5CCBC60B2CA1F04A00E958D0 /* LocalInference.h */; settings = {ATTRIBUTES = (Public, ); }; };
12+ 5CCBC6752CA1F45800E958D0 /* executorch_debug in Frameworks */ = {isa = PBXBuildFile; productRef = 5CCBC6742CA1F45800E958D0 /* executorch_debug */; };
13+ 5CCBC6862CA1F64A00E958D0 /* LLaMARunner.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 5CCBC6802CA1F63F00E958D0 /* LLaMARunner.framework */; platformFilter = ios; };
14+ 5CCBC6872CA1F64A00E958D0 /* LLaMARunner.framework in Embed Frameworks */ = {isa = PBXBuildFile; fileRef = 5CCBC6802CA1F63F00E958D0 /* LLaMARunner.framework */; platformFilter = ios; settings = {ATTRIBUTES = (CodeSignOnCopy, RemoveHeadersOnCopy, ); }; };
15+ 5CCBC68D2CA1F7A100E958D0 /* PromptTemplate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5CCBC6892CA1F7A000E958D0 /* PromptTemplate.swift */; };
16+ 5CCBC68E2CA1F7A100E958D0 /* LocalInference.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5CCBC68A2CA1F7A000E958D0 /* LocalInference.swift */; };
17+ 5CCBC68F2CA1F7A100E958D0 /* Parsing.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5CCBC68B2CA1F7A000E958D0 /* Parsing.swift */; };
18+ 5CCBC6902CA1F7A100E958D0 /* SystemPrompts.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5CCBC68C2CA1F7A100E958D0 /* SystemPrompts.swift */; };
19+ 5CCBC6932CA1F7D000E958D0 /* Stencil in Frameworks */ = {isa = PBXBuildFile; productRef = 5CCBC6922CA1F7D000E958D0 /* Stencil */; };
20+/* End PBXBuildFile section */
21+
22+/* Begin PBXContainerItemProxy section */
23+ 5CCBC67D2CA1F63F00E958D0 /* PBXContainerItemProxy */ = {
24+ isa = PBXContainerItemProxy;
25+ containerPortal = 5CCBC6762CA1F63F00E958D0 /* LLaMA.xcodeproj */;
26+ proxyType = 2;
27+ remoteGlobalIDString = 036CAF9D2BB1444500D6C2D5;
28+ remoteInfo = LLaMA;
29+ };
30+ 5CCBC67F2CA1F63F00E958D0 /* PBXContainerItemProxy */ = {
31+ isa = PBXContainerItemProxy;
32+ containerPortal = 5CCBC6762CA1F63F00E958D0 /* LLaMA.xcodeproj */;
33+ proxyType = 2;
34+ remoteGlobalIDString = 03729ED52BB1F8DE00152F2E;
35+ remoteInfo = LLaMARunner;
36+ };
37+ 5CCBC69E2CA2036B00E958D0 /* PBXContainerItemProxy */ = {
38+ isa = PBXContainerItemProxy;
39+ containerPortal = 5CCBC6762CA1F63F00E958D0 /* LLaMA.xcodeproj */;
40+ proxyType = 2;
41+ remoteGlobalIDString = 5CCBC6982CA2036A00E958D0;
42+ remoteInfo = LLaMAPerfBenchmark;
43+ };
44+ 5CCBC6A02CA2036B00E958D0 /* PBXContainerItemProxy */ = {
45+ isa = PBXContainerItemProxy;
46+ containerPortal = 5CCBC6762CA1F63F00E958D0 /* LLaMA.xcodeproj */;
47+ proxyType = 2;
48+ remoteGlobalIDString = 5CCBC6992CA2036A00E958D0;
49+ remoteInfo = LLaMAPerfBenchmarkTests;
50+ };
51+/* End PBXContainerItemProxy section */
52+
53+/* Begin PBXCopyFilesBuildPhase section */
54+ 5CCBC6882CA1F64A00E958D0 /* Embed Frameworks */ = {
55+ isa = PBXCopyFilesBuildPhase;
56+ buildActionMask = 2147483647;
57+ dstPath = "";
58+ dstSubfolderSpec = 10;
59+ files = (
60+ 5CCBC6872CA1F64A00E958D0 /* LLaMARunner.framework in Embed Frameworks */,
61+ );
62+ name = "Embed Frameworks";
63+ runOnlyForDeploymentPostprocessing = 0;
64+ };
65+/* End PBXCopyFilesBuildPhase section */
66+
67+/* Begin PBXFileReference section */
68+ 5CCBC6082CA1F04A00E958D0 /* LocalInferenceImpl.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = LocalInferenceImpl.framework; sourceTree = BUILT_PRODUCTS_DIR; };
69+ 5CCBC60B2CA1F04A00E958D0 /* LocalInference.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = LocalInference.h; sourceTree = "<group>"; };
70+ 5CCBC6762CA1F63F00E958D0 /* LLaMA.xcodeproj */ = {isa = PBXFileReference; lastKnownFileType = "wrapper.pb-project"; name = LLaMA.xcodeproj; path = "executorch/examples/demo-apps/apple_ios/LLaMA/LLaMA.xcodeproj"; sourceTree = "<group>"; };
71+ 5CCBC6892CA1F7A000E958D0 /* PromptTemplate.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PromptTemplate.swift; sourceTree = "<group>"; };
72+ 5CCBC68A2CA1F7A000E958D0 /* LocalInference.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = LocalInference.swift; sourceTree = "<group>"; };
73+ 5CCBC68B2CA1F7A000E958D0 /* Parsing.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Parsing.swift; sourceTree = "<group>"; };
74+ 5CCBC68C2CA1F7A100E958D0 /* SystemPrompts.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SystemPrompts.swift; sourceTree = "<group>"; };
75+/* End PBXFileReference section */
76+
77+/* Begin PBXFrameworksBuildPhase section */
78+ 5CCBC6052CA1F04A00E958D0 /* Frameworks */ = {
79+ isa = PBXFrameworksBuildPhase;
80+ buildActionMask = 2147483647;
81+ files = (
82+ 5CADC71A2CA471CC007662D2 /* LlamaStackClient in Frameworks */,
83+ 5CCBC6932CA1F7D000E958D0 /* Stencil in Frameworks */,
84+ 5CCBC6862CA1F64A00E958D0 /* LLaMARunner.framework in Frameworks */,
85+ 5CCBC6752CA1F45800E958D0 /* executorch_debug in Frameworks */,
86+ );
87+ runOnlyForDeploymentPostprocessing = 0;
88+ };
89+/* End PBXFrameworksBuildPhase section */
90+
91+/* Begin PBXGroup section */
92+ 5CCBC5FE2CA1F04A00E958D0 = {
93+ isa = PBXGroup;
94+ children = (
95+ 5CCBC6762CA1F63F00E958D0 /* LLaMA.xcodeproj */,
96+ 5CCBC60A2CA1F04A00E958D0 /* LocalInferenceImpl */,
97+ 5CCBC6092CA1F04A00E958D0 /* Products */,
98+ 5CCBC6852CA1F64A00E958D0 /* Frameworks */,
99+ );
100+ sourceTree = "<group>";
101+ };
102+ 5CCBC6092CA1F04A00E958D0 /* Products */ = {
103+ isa = PBXGroup;
104+ children = (
105+ 5CCBC6082CA1F04A00E958D0 /* LocalInferenceImpl.framework */,
106+ );
107+ name = Products;
108+ sourceTree = "<group>";
109+ };
110+ 5CCBC60A2CA1F04A00E958D0 /* LocalInferenceImpl */ = {
111+ isa = PBXGroup;
112+ children = (
113+ 5CCBC68A2CA1F7A000E958D0 /* LocalInference.swift */,
114+ 5CCBC68B2CA1F7A000E958D0 /* Parsing.swift */,
115+ 5CCBC6892CA1F7A000E958D0 /* PromptTemplate.swift */,
116+ 5CCBC68C2CA1F7A100E958D0 /* SystemPrompts.swift */,
117+ 5CCBC60B2CA1F04A00E958D0 /* LocalInference.h */,
118+ );
119+ path = LocalInferenceImpl;
120+ sourceTree = "<group>";
121+ };
122+ 5CCBC6772CA1F63F00E958D0 /* Products */ = {
123+ isa = PBXGroup;
124+ children = (
125+ 5CCBC67E2CA1F63F00E958D0 /* LLaMA.app */,
126+ 5CCBC6802CA1F63F00E958D0 /* LLaMARunner.framework */,
127+ 5CCBC69F2CA2036B00E958D0 /* LLaMAPerfBenchmark.app */,
128+ 5CCBC6A12CA2036B00E958D0 /* LLaMAPerfBenchmarkTests.xctest */,
129+ );
130+ name = Products;
131+ sourceTree = "<group>";
132+ };
133+ 5CCBC6852CA1F64A00E958D0 /* Frameworks */ = {
134+ isa = PBXGroup;
135+ children = (
136+ );
137+ name = Frameworks;
138+ sourceTree = "<group>";
139+ };
140+/* End PBXGroup section */
141+
142+/* Begin PBXHeadersBuildPhase section */
143+ 5CCBC6032CA1F04A00E958D0 /* Headers */ = {
144+ isa = PBXHeadersBuildPhase;
145+ buildActionMask = 2147483647;
146+ files = (
147+ 5CCBC60C2CA1F04A00E958D0 /* LocalInference.h in Headers */,
148+ );
149+ runOnlyForDeploymentPostprocessing = 0;
150+ };
151+/* End PBXHeadersBuildPhase section */
152+
153+/* Begin PBXNativeTarget section */
154+ 5CCBC6072CA1F04A00E958D0 /* LocalInferenceImpl */ = {
155+ isa = PBXNativeTarget;
156+ buildConfigurationList = 5CCBC60F2CA1F04A00E958D0 /* Build configuration list for PBXNativeTarget "LocalInferenceImpl" */;
157+ buildPhases = (
158+ 5CCBC6032CA1F04A00E958D0 /* Headers */,
159+ 5CCBC6042CA1F04A00E958D0 /* Sources */,
160+ 5CCBC6052CA1F04A00E958D0 /* Frameworks */,
161+ 5CCBC6062CA1F04A00E958D0 /* Resources */,
162+ 5CCBC6882CA1F64A00E958D0 /* Embed Frameworks */,
163+ );
164+ buildRules = (
165+ );
166+ dependencies = (
167+ );
168+ name = LocalInferenceImpl;
169+ packageProductDependencies = (
170+ 5CCBC6742CA1F45800E958D0 /* executorch_debug */,
171+ 5CCBC6922CA1F7D000E958D0 /* Stencil */,
172+ 5CADC7192CA471CC007662D2 /* LlamaStackClient */,
173+ );
174+ productName = LocalInferenceProvider;
175+ productReference = 5CCBC6082CA1F04A00E958D0 /* LocalInferenceImpl.framework */;
176+ productType = "com.apple.product-type.framework";
177+ };
178+/* End PBXNativeTarget section */
179+
180+/* Begin PBXProject section */
181+ 5CCBC5FF2CA1F04A00E958D0 /* Project object */ = {
182+ isa = PBXProject;
183+ attributes = {
184+ BuildIndependentTargetsInParallel = 1;
185+ LastUpgradeCheck = 1540;
186+ TargetAttributes = {
187+ 5CCBC6072CA1F04A00E958D0 = {
188+ CreatedOnToolsVersion = 15.4;
189+ LastSwiftMigration = 1540;
190+ };
191+ };
192+ };
193+ buildConfigurationList = 5CCBC6022CA1F04A00E958D0 /* Build configuration list for PBXProject "LocalInferenceImpl" */;
194+ compatibilityVersion = "Xcode 14.0";
195+ developmentRegion = en;
196+ hasScannedForEncodings = 0;
197+ knownRegions = (
198+ en,
199+ Base,
200+ );
201+ mainGroup = 5CCBC5FE2CA1F04A00E958D0;
202+ packageReferences = (
203+ 5CCBC6732CA1F45800E958D0 /* XCRemoteSwiftPackageReference "executorch" */,
204+ 5CCBC6912CA1F7D000E958D0 /* XCRemoteSwiftPackageReference "Stencil" */,
205+ 5CADC7182CA471CC007662D2 /* XCLocalSwiftPackageReference "internal-llama-stack-client-swift" */,
206+ );
207+ productRefGroup = 5CCBC6092CA1F04A00E958D0 /* Products */;
208+ projectDirPath = "";
209+ projectReferences = (
210+ {
211+ ProductGroup = 5CCBC6772CA1F63F00E958D0 /* Products */;
212+ ProjectRef = 5CCBC6762CA1F63F00E958D0 /* LLaMA.xcodeproj */;
213+ },
214+ );
215+ projectRoot = "";
216+ targets = (
217+ 5CCBC6072CA1F04A00E958D0 /* LocalInferenceImpl */,
218+ );
219+ };
220+/* End PBXProject section */
221+
222+/* Begin PBXReferenceProxy section */
223+ 5CCBC67E2CA1F63F00E958D0 /* LLaMA.app */ = {
224+ isa = PBXReferenceProxy;
225+ fileType = wrapper.application;
226+ path = LLaMA.app;
227+ remoteRef = 5CCBC67D2CA1F63F00E958D0 /* PBXContainerItemProxy */;
228+ sourceTree = BUILT_PRODUCTS_DIR;
229+ };
230+ 5CCBC6802CA1F63F00E958D0 /* LLaMARunner.framework */ = {
231+ isa = PBXReferenceProxy;
232+ fileType = wrapper.framework;
233+ path = LLaMARunner.framework;
234+ remoteRef = 5CCBC67F2CA1F63F00E958D0 /* PBXContainerItemProxy */;
235+ sourceTree = BUILT_PRODUCTS_DIR;
236+ };
237+ 5CCBC69F2CA2036B00E958D0 /* LLaMAPerfBenchmark.app */ = {
238+ isa = PBXReferenceProxy;
239+ fileType = wrapper.application;
240+ path = LLaMAPerfBenchmark.app;
241+ remoteRef = 5CCBC69E2CA2036B00E958D0 /* PBXContainerItemProxy */;
242+ sourceTree = BUILT_PRODUCTS_DIR;
243+ };
244+ 5CCBC6A12CA2036B00E958D0 /* LLaMAPerfBenchmarkTests.xctest */ = {
245+ isa = PBXReferenceProxy;
246+ fileType = wrapper.cfbundle;
247+ path = LLaMAPerfBenchmarkTests.xctest;
248+ remoteRef = 5CCBC6A02CA2036B00E958D0 /* PBXContainerItemProxy */;
249+ sourceTree = BUILT_PRODUCTS_DIR;
250+ };
251+/* End PBXReferenceProxy section */
252+
253+/* Begin PBXResourcesBuildPhase section */
254+ 5CCBC6062CA1F04A00E958D0 /* Resources */ = {
255+ isa = PBXResourcesBuildPhase;
256+ buildActionMask = 2147483647;
257+ files = (
258+ );
259+ runOnlyForDeploymentPostprocessing = 0;
260+ };
261+/* End PBXResourcesBuildPhase section */
262+
263+/* Begin PBXSourcesBuildPhase section */
264+ 5CCBC6042CA1F04A00E958D0 /* Sources */ = {
265+ isa = PBXSourcesBuildPhase;
266+ buildActionMask = 2147483647;
267+ files = (
268+ 5CCBC6902CA1F7A100E958D0 /* SystemPrompts.swift in Sources */,
269+ 5CCBC68D2CA1F7A100E958D0 /* PromptTemplate.swift in Sources */,
270+ 5CCBC68F2CA1F7A100E958D0 /* Parsing.swift in Sources */,
271+ 5CCBC68E2CA1F7A100E958D0 /* LocalInference.swift in Sources */,
272+ );
273+ runOnlyForDeploymentPostprocessing = 0;
274+ };
275+/* End PBXSourcesBuildPhase section */
276+
277+/* Begin XCBuildConfiguration section */
278+ 5CCBC60D2CA1F04A00E958D0 /* Debug */ = {
279+ isa = XCBuildConfiguration;
280+ buildSettings = {
281+ ALWAYS_SEARCH_USER_PATHS = NO;
282+ ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES;
283+ CLANG_ANALYZER_NONNULL = YES;
284+ CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE;
285+ CLANG_CXX_LANGUAGE_STANDARD = "gnu++20";
286+ CLANG_ENABLE_MODULES = YES;
287+ CLANG_ENABLE_OBJC_ARC = YES;
288+ CLANG_ENABLE_OBJC_WEAK = YES;
289+ CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES;
290+ CLANG_WARN_BOOL_CONVERSION = YES;
291+ CLANG_WARN_COMMA = YES;
292+ CLANG_WARN_CONSTANT_CONVERSION = YES;
293+ CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES;
294+ CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR;
295+ CLANG_WARN_DOCUMENTATION_COMMENTS = YES;
296+ CLANG_WARN_EMPTY_BODY = YES;
297+ CLANG_WARN_ENUM_CONVERSION = YES;
298+ CLANG_WARN_INFINITE_RECURSION = YES;
299+ CLANG_WARN_INT_CONVERSION = YES;
300+ CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES;
301+ CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES;
302+ CLANG_WARN_OBJC_LITERAL_CONVERSION = YES;
303+ CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR;
304+ CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = YES;
305+ CLANG_WARN_RANGE_LOOP_ANALYSIS = YES;
306+ CLANG_WARN_STRICT_PROTOTYPES = YES;
307+ CLANG_WARN_SUSPICIOUS_MOVE = YES;
308+ CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE;
309+ CLANG_WARN_UNREACHABLE_CODE = YES;
310+ CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;
311+ COPY_PHASE_STRIP = NO;
312+ CURRENT_PROJECT_VERSION = 1;
313+ DEBUG_INFORMATION_FORMAT = dwarf;
314+ ENABLE_STRICT_OBJC_MSGSEND = YES;
315+ ENABLE_TESTABILITY = YES;
316+ ENABLE_USER_SCRIPT_SANDBOXING = YES;
317+ GCC_C_LANGUAGE_STANDARD = gnu17;
318+ GCC_DYNAMIC_NO_PIC = NO;
319+ GCC_NO_COMMON_BLOCKS = YES;
320+ GCC_OPTIMIZATION_LEVEL = 0;
321+ GCC_PREPROCESSOR_DEFINITIONS = (
322+ "DEBUG=1",
323+ "$(inherited)",
324+ );
325+ GCC_WARN_64_TO_32_BIT_CONVERSION = YES;
326+ GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR;
327+ GCC_WARN_UNDECLARED_SELECTOR = YES;
328+ GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
329+ GCC_WARN_UNUSED_FUNCTION = YES;
330+ GCC_WARN_UNUSED_VARIABLE = YES;
331+ IPHONEOS_DEPLOYMENT_TARGET = 17.5;
332+ LOCALIZATION_PREFERS_STRING_CATALOGS = YES;
333+ MTL_ENABLE_DEBUG_INFO = INCLUDE_SOURCE;
334+ MTL_FAST_MATH = YES;
335+ ONLY_ACTIVE_ARCH = YES;
336+ SDKROOT = iphoneos;
337+ SWIFT_ACTIVE_COMPILATION_CONDITIONS = "DEBUG $(inherited)";
338+ SWIFT_OPTIMIZATION_LEVEL = "-Onone";
339+ VERSIONING_SYSTEM = "apple-generic";
340+ VERSION_INFO_PREFIX = "";
341+ };
342+ name = Debug;
343+ };
344+ 5CCBC60E2CA1F04A00E958D0 /* Release */ = {
345+ isa = XCBuildConfiguration;
346+ buildSettings = {
347+ ALWAYS_SEARCH_USER_PATHS = NO;
348+ ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES;
349+ CLANG_ANALYZER_NONNULL = YES;
350+ CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE;
351+ CLANG_CXX_LANGUAGE_STANDARD = "gnu++20";
352+ CLANG_ENABLE_MODULES = YES;
353+ CLANG_ENABLE_OBJC_ARC = YES;
354+ CLANG_ENABLE_OBJC_WEAK = YES;
355+ CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES;
356+ CLANG_WARN_BOOL_CONVERSION = YES;
357+ CLANG_WARN_COMMA = YES;
358+ CLANG_WARN_CONSTANT_CONVERSION = YES;
359+ CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES;
360+ CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR;
361+ CLANG_WARN_DOCUMENTATION_COMMENTS = YES;
362+ CLANG_WARN_EMPTY_BODY = YES;
363+ CLANG_WARN_ENUM_CONVERSION = YES;
364+ CLANG_WARN_INFINITE_RECURSION = YES;
365+ CLANG_WARN_INT_CONVERSION = YES;
366+ CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES;
367+ CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES;
368+ CLANG_WARN_OBJC_LITERAL_CONVERSION = YES;
369+ CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR;
370+ CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = YES;
371+ CLANG_WARN_RANGE_LOOP_ANALYSIS = YES;
372+ CLANG_WARN_STRICT_PROTOTYPES = YES;
373+ CLANG_WARN_SUSPICIOUS_MOVE = YES;
374+ CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE;
375+ CLANG_WARN_UNREACHABLE_CODE = YES;
376+ CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;
377+ COPY_PHASE_STRIP = NO;
378+ CURRENT_PROJECT_VERSION = 1;
379+ DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym";
380+ ENABLE_NS_ASSERTIONS = NO;
381+ ENABLE_STRICT_OBJC_MSGSEND = YES;
382+ ENABLE_USER_SCRIPT_SANDBOXING = YES;
383+ GCC_C_LANGUAGE_STANDARD = gnu17;
384+ GCC_NO_COMMON_BLOCKS = YES;
385+ GCC_WARN_64_TO_32_BIT_CONVERSION = YES;
386+ GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR;
387+ GCC_WARN_UNDECLARED_SELECTOR = YES;
388+ GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
389+ GCC_WARN_UNUSED_FUNCTION = YES;
390+ GCC_WARN_UNUSED_VARIABLE = YES;
391+ IPHONEOS_DEPLOYMENT_TARGET = 17.5;
392+ LOCALIZATION_PREFERS_STRING_CATALOGS = YES;
393+ MTL_ENABLE_DEBUG_INFO = NO;
394+ MTL_FAST_MATH = YES;
395+ SDKROOT = iphoneos;
396+ SWIFT_COMPILATION_MODE = wholemodule;
397+ VALIDATE_PRODUCT = YES;
398+ VERSIONING_SYSTEM = "apple-generic";
399+ VERSION_INFO_PREFIX = "";
400+ };
401+ name = Release;
402+ };
403+ 5CCBC6102CA1F04A00E958D0 /* Debug */ = {
404+ isa = XCBuildConfiguration;
405+ buildSettings = {
406+ BUILD_LIBRARY_FOR_DISTRIBUTION = YES;
407+ CLANG_ENABLE_MODULES = YES;
408+ CODE_SIGN_STYLE = Automatic;
409+ CURRENT_PROJECT_VERSION = 1;
410+ DEFINES_MODULE = YES;
411+ DYLIB_COMPATIBILITY_VERSION = 1;
412+ DYLIB_CURRENT_VERSION = 1;
413+ DYLIB_INSTALL_NAME_BASE = "@rpath";
414+ ENABLE_MODULE_VERIFIER = YES;
415+ GENERATE_INFOPLIST_FILE = YES;
416+ HEADER_SEARCH_PATHS = "";
417+ INFOPLIST_KEY_NSHumanReadableCopyright = "";
418+ INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks";
419+ LD_RUNPATH_SEARCH_PATHS = (
420+ "$(inherited)",
421+ "@executable_path/Frameworks",
422+ "@loader_path/Frameworks",
423+ );
424+ MARKETING_VERSION = 1.0;
425+ MODULE_VERIFIER_SUPPORTED_LANGUAGES = "objective-c objective-c++";
426+ MODULE_VERIFIER_SUPPORTED_LANGUAGE_STANDARDS = "gnu17 gnu++20";
427+ OTHER_LDFLAGS = "";
428+ PRODUCT_BUNDLE_IDENTIFIER = meta.llamatsack.LocalInferenceProvider;
429+ PRODUCT_NAME = "$(TARGET_NAME:c99extidentifier)";
430+ SKIP_INSTALL = YES;
431+ SWIFT_EMIT_LOC_STRINGS = YES;
432+ SWIFT_INSTALL_OBJC_HEADER = NO;
433+ SWIFT_OPTIMIZATION_LEVEL = "-Onone";
434+ SWIFT_VERSION = 5.0;
435+ TARGETED_DEVICE_FAMILY = "1,2";
436+ };
437+ name = Debug;
438+ };
439+ 5CCBC6112CA1F04A00E958D0 /* Release */ = {
440+ isa = XCBuildConfiguration;
441+ buildSettings = {
442+ BUILD_LIBRARY_FOR_DISTRIBUTION = YES;
443+ CLANG_ENABLE_MODULES = YES;
444+ CODE_SIGN_STYLE = Automatic;
445+ CURRENT_PROJECT_VERSION = 1;
446+ DEFINES_MODULE = YES;
447+ DYLIB_COMPATIBILITY_VERSION = 1;
448+ DYLIB_CURRENT_VERSION = 1;
449+ DYLIB_INSTALL_NAME_BASE = "@rpath";
450+ ENABLE_MODULE_VERIFIER = YES;
451+ GENERATE_INFOPLIST_FILE = YES;
452+ HEADER_SEARCH_PATHS = "";
453+ INFOPLIST_KEY_NSHumanReadableCopyright = "";
454+ INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks";
455+ LD_RUNPATH_SEARCH_PATHS = (
456+ "$(inherited)",
457+ "@executable_path/Frameworks",
458+ "@loader_path/Frameworks",
459+ );
460+ MARKETING_VERSION = 1.0;
461+ MODULE_VERIFIER_SUPPORTED_LANGUAGES = "objective-c objective-c++";
462+ MODULE_VERIFIER_SUPPORTED_LANGUAGE_STANDARDS = "gnu17 gnu++20";
463+ OTHER_LDFLAGS = "";
464+ PRODUCT_BUNDLE_IDENTIFIER = meta.llamatsack.LocalInferenceProvider;
465+ PRODUCT_NAME = "$(TARGET_NAME:c99extidentifier)";
466+ SKIP_INSTALL = YES;
467+ SWIFT_EMIT_LOC_STRINGS = YES;
468+ SWIFT_INSTALL_OBJC_HEADER = NO;
469+ SWIFT_VERSION = 5.0;
470+ TARGETED_DEVICE_FAMILY = "1,2";
471+ };
472+ name = Release;
473+ };
474+/* End XCBuildConfiguration section */
475+
476+/* Begin XCConfigurationList section */
477+ 5CCBC6022CA1F04A00E958D0 /* Build configuration list for PBXProject "LocalInferenceImpl" */ = {
478+ isa = XCConfigurationList;
479+ buildConfigurations = (
480+ 5CCBC60D2CA1F04A00E958D0 /* Debug */,
481+ 5CCBC60E2CA1F04A00E958D0 /* Release */,
482+ );
483+ defaultConfigurationIsVisible = 0;
484+ defaultConfigurationName = Release;
485+ };
486+ 5CCBC60F2CA1F04A00E958D0 /* Build configuration list for PBXNativeTarget "LocalInferenceImpl" */ = {
487+ isa = XCConfigurationList;
488+ buildConfigurations = (
489+ 5CCBC6102CA1F04A00E958D0 /* Debug */,
490+ 5CCBC6112CA1F04A00E958D0 /* Release */,
491+ );
492+ defaultConfigurationIsVisible = 0;
493+ defaultConfigurationName = Release;
494+ };
495+/* End XCConfigurationList section */
496+
497+/* Begin XCLocalSwiftPackageReference section */
498+ 5CADC7182CA471CC007662D2 /* XCLocalSwiftPackageReference "internal-llama-stack-client-swift" */ = {
499+ isa = XCLocalSwiftPackageReference;
500+ relativePath = "internal-llama-stack-client-swift";
501+ };
502+/* End XCLocalSwiftPackageReference section */
503+
504+/* Begin XCRemoteSwiftPackageReference section */
505+ 5CCBC6732CA1F45800E958D0 /* XCRemoteSwiftPackageReference "executorch" */ = {
506+ isa = XCRemoteSwiftPackageReference;
507+ repositoryURL = "https://github.com/pytorch/executorch";
508+ requirement = {
509+ branch = latest;
510+ kind = branch;
511+ };
512+ };
513+ 5CCBC6912CA1F7D000E958D0 /* XCRemoteSwiftPackageReference "Stencil" */ = {
514+ isa = XCRemoteSwiftPackageReference;
515+ repositoryURL = "https://github.com/stencilproject/Stencil";
516+ requirement = {
517+ kind = upToNextMajorVersion;
518+ minimumVersion = 0.15.1;
519+ };
520+ };
521+/* End XCRemoteSwiftPackageReference section */
522+
523+/* Begin XCSwiftPackageProductDependency section */
524+ 5CADC7192CA471CC007662D2 /* LlamaStackClient */ = {
525+ isa = XCSwiftPackageProductDependency;
526+ productName = LlamaStackClient;
527+ };
528+ 5CCBC6742CA1F45800E958D0 /* executorch_debug */ = {
529+ isa = XCSwiftPackageProductDependency;
530+ package = 5CCBC6732CA1F45800E958D0 /* XCRemoteSwiftPackageReference "executorch" */;
531+ productName = executorch_debug;
532+ };
533+ 5CCBC6922CA1F7D000E958D0 /* Stencil */ = {
534+ isa = XCSwiftPackageProductDependency;
535+ package = 5CCBC6912CA1F7D000E958D0 /* XCRemoteSwiftPackageReference "Stencil" */;
536+ productName = Stencil;
537+ };
538+/* End XCSwiftPackageProductDependency section */
539+ };
540+ rootObject = 5CCBC5FF2CA1F04A00E958D0 /* Project object */;
541+}
added llama_stack/providers/impls/ios/inference/LocalInference/LocalInferenceImpl.xcodeproj/project.xcworkspace/contents.xcworkspacedata +7 −0
@@ -0,0 +1,7 @@
1+<?xml version="1.0" encoding="UTF-8"?>
2+<Workspace
3+ version = "1.0">
4+ <FileRef
5+ location = "self:">
6+ </FileRef>
7+</Workspace>
added llama_stack/providers/impls/ios/inference/LocalInference/LocalInferenceImpl.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist +8 −0
@@ -0,0 +1,8 @@
1+<?xml version="1.0" encoding="UTF-8"?>
2+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
3+<plist version="1.0">
4+<dict>
5+ <key>IDEDidComputeMac32BitWarning</key>
6+ <true/>
7+</dict>
8+</plist>
added llama_stack/providers/impls/ios/inference/LocalInference/LocalInferenceImpl/LocalInference.h +16 −0
@@ -0,0 +1,16 @@
1+//
2+// LocalInference.h
3+// LocalInference
4+//
5+// Created by Dalton Flanagan on 9/23/24.
6+//
7+
8+#import <Foundation/Foundation.h>
9+
10+//! Project version number for LocalInference.
11+FOUNDATION_EXPORT double LocalInferenceVersionNumber;
12+
13+//! Project version string for LocalInference.
14+FOUNDATION_EXPORT const unsigned char LocalInferenceVersionString[];
15+
16+// In this header, you should import all the public headers of your framework using statements like #import <LocalInference/PublicHeader.h>
added llama_stack/providers/impls/ios/inference/LocalInference/LocalInferenceImpl/LocalInference.swift +167 −0
@@ -0,0 +1,167 @@
1+import Foundation
2+
3+import LLaMARunner
4+import LlamaStackClient
5+
6+class RunnerHolder: ObservableObject {
7+ var runner: Runner?
8+}
9+
10+public class LocalInference: Inference {
11+ private var runnerHolder = RunnerHolder()
12+ private let runnerQueue: DispatchQueue
13+
14+ public init (queue: DispatchQueue) {
15+ runnerQueue = queue
16+ }
17+
18+ public func loadModel(modelPath: String, tokenizerPath: String, completion: @escaping (Result<Void, Error>) -> Void) {
19+ runnerHolder.runner = runnerHolder.runner ?? Runner(
20+ modelPath: modelPath,
21+ tokenizerPath: tokenizerPath
22+ )
23+
24+
25+ runnerQueue.async {
26+ let runner = self.runnerHolder.runner
27+ do {
28+ try runner!.load()
29+ completion(.success(()))
30+ } catch let loadError {
31+ print("error: " + loadError.localizedDescription)
32+ completion(.failure(loadError))
33+ }
34+ }
35+ }
36+
37+ public func chatCompletion(request: Components.Schemas.ChatCompletionRequest) -> AsyncStream<Components.Schemas.ChatCompletionResponseStreamChunk> {
38+ return AsyncStream { continuation in
39+ runnerQueue.async {
40+ do {
41+ var tokens: [String] = []
42+
43+ let prompt = try encodeDialogPrompt(messages: prepareMessages(request: request))
44+ var stopReason: Components.Schemas.StopReason? = nil
45+ var buffer = ""
46+ var ipython = false
47+ var echoDropped = false
48+
49+ try self.runnerHolder.runner?.generate(prompt, sequenceLength: 4096) { token in
50+ buffer += token
51+
52+ // HACK: Workaround until LlamaRunner exposes echo param
53+ if (!echoDropped) {
54+ if (buffer.hasPrefix(prompt)) {
55+ buffer = String(buffer.dropFirst(prompt.count))
56+ echoDropped = true
57+ }
58+ return
59+ }
60+
61+ tokens.append(token)
62+
63+ if !ipython && (buffer.starts(with: "<|python_tag|>") || buffer.starts(with: "[") ) {
64+ ipython = true
65+ continuation.yield(
66+ Components.Schemas.ChatCompletionResponseStreamChunk(
67+ event: Components.Schemas.ChatCompletionResponseEvent(
68+ delta: .ToolCallDelta(Components.Schemas.ToolCallDelta(
69+ content: .case1(""),
70+ parse_status: Components.Schemas.ToolCallParseStatus.started
71+ )
72+ ),
73+ event_type: .progress
74+ )
75+ )
76+ )
77+
78+ if (buffer.starts(with: "<|python_tag|>")) {
79+ buffer = String(buffer.dropFirst("<|python_tag|>".count))
80+ }
81+ }
82+
83+ // TODO: Non-streaming lobprobs
84+
85+ var text = ""
86+ if token == "<|eot_id|>" {
87+ stopReason = Components.Schemas.StopReason.end_of_turn
88+ } else if token == "<|eom_id|>" {
89+ stopReason = Components.Schemas.StopReason.end_of_message
90+ } else {
91+ text = token
92+ }
93+
94+ var delta: Components.Schemas.ChatCompletionResponseEvent.deltaPayload
95+ if ipython {
96+ delta = .ToolCallDelta(Components.Schemas.ToolCallDelta(
97+ content: .case1(text),
98+ parse_status: .in_progress
99+ ))
100+ } else {
101+ delta = .case1(text)
102+ }
103+
104+ if stopReason == nil {
105+ continuation.yield(
106+ Components.Schemas.ChatCompletionResponseStreamChunk(
107+ event: Components.Schemas.ChatCompletionResponseEvent(
108+ delta: delta,
109+ event_type: .progress
110+ )
111+ )
112+ )
113+ }
114+ }
115+
116+ if stopReason == nil {
117+ stopReason = Components.Schemas.StopReason.out_of_tokens
118+ }
119+
120+ let message = decodeAssistantMessage(tokens: tokens.joined(), stopReason: stopReason!)
121+ // TODO: non-streaming support
122+
123+ let didParseToolCalls = message.tool_calls.count > 0
124+ if ipython && !didParseToolCalls {
125+ continuation.yield(
126+ Components.Schemas.ChatCompletionResponseStreamChunk(
127+ event: Components.Schemas.ChatCompletionResponseEvent(
128+ delta: .ToolCallDelta(Components.Schemas.ToolCallDelta(content: .case1(""), parse_status: .failure)),
129+ event_type: .progress
130+ )
131+ // TODO: stopReason
132+ )
133+ )
134+ }
135+
136+ for toolCall in message.tool_calls {
137+ continuation.yield(
138+ Components.Schemas.ChatCompletionResponseStreamChunk(
139+ event: Components.Schemas.ChatCompletionResponseEvent(
140+ delta: .ToolCallDelta(Components.Schemas.ToolCallDelta(
141+ content: .ToolCall(toolCall),
142+ parse_status: .success
143+ )),
144+ event_type: .progress
145+ )
146+ // TODO: stopReason
147+ )
148+ )
149+ }
150+
151+ continuation.yield(
152+ Components.Schemas.ChatCompletionResponseStreamChunk(
153+ event: Components.Schemas.ChatCompletionResponseEvent(
154+ delta: .case1(""),
155+ event_type: .complete
156+ )
157+ // TODO: stopReason
158+ )
159+ )
160+ }
161+ catch (let error) {
162+ print("Inference error: " + error.localizedDescription)
163+ }
164+ }
165+ }
166+ }
167+}
added llama_stack/providers/impls/ios/inference/LocalInference/LocalInferenceImpl/Parsing.swift +235 −0
@@ -0,0 +1,235 @@
1+import Foundation
2+
3+import LlamaStackClient
4+
5+func encodeHeader(role: String) -> String {
6+ return "<|start_header_id|>\(role)<|end_header_id|>\n\n"
7+}
8+
9+func encodeDialogPrompt(messages: [Components.Schemas.ChatCompletionRequest.messagesPayloadPayload]) -> String {
10+ var prompt = ""
11+
12+ prompt.append("<|begin_of_text|>")
13+ for message in messages {
14+ let msg = encodeMessage(message: message)
15+ prompt += msg
16+ }
17+
18+ prompt.append(encodeHeader(role: "assistant"))
19+
20+ return prompt
21+}
22+
23+func getRole(message: Components.Schemas.ChatCompletionRequest.messagesPayloadPayload) -> String {
24+ switch (message) {
25+ case .UserMessage(let m):
26+ return m.role.rawValue
27+ case .SystemMessage(let m):
28+ return m.role.rawValue
29+ case .ToolResponseMessage(let m):
30+ return m.role.rawValue
31+ case .CompletionMessage(let m):
32+ return m.role.rawValue
33+ }
34+}
35+
36+func encodeMessage(message: Components.Schemas.ChatCompletionRequest.messagesPayloadPayload) -> String {
37+ var prompt = encodeHeader(role: getRole(message: message))
38+
39+ switch (message) {
40+ case .CompletionMessage(let m):
41+ if (m.tool_calls.count > 0) {
42+ prompt += "<|python_tag|>"
43+ }
44+ default:
45+ break
46+ }
47+
48+ func _processContent(_ content: Any) -> String {
49+ func _process(_ c: Any) {
50+ if let str = c as? String {
51+ prompt += str
52+ }
53+ }
54+
55+ if let str = content as? String {
56+ _process(str)
57+ } else if let list = content as? [Any] {
58+ for c in list {
59+ _process(c)
60+ }
61+ }
62+
63+ return ""
64+ }
65+
66+ switch (message) {
67+ case .UserMessage(let m):
68+ prompt += _processContent(m.content)
69+ case .SystemMessage(let m):
70+ prompt += _processContent(m.content)
71+ case .ToolResponseMessage(let m):
72+ prompt += _processContent(m.content)
73+ case .CompletionMessage(let m):
74+ prompt += _processContent(m.content)
75+ }
76+
77+ var eom = false
78+
79+ switch (message) {
80+ case .UserMessage(let m):
81+ switch (m.content) {
82+ case .case1(let c):
83+ prompt += _processContent(c)
84+ case .case2(let c):
85+ prompt += _processContent(c)
86+ }
87+ case .CompletionMessage(let m):
88+ // TODO: Support encoding past tool call history
89+ // for t in m.tool_calls {
90+ // _processContent(t.)
91+ //}
92+ eom = m.stop_reason == Components.Schemas.StopReason.end_of_message
93+ case .SystemMessage(_):
94+ break
95+ case .ToolResponseMessage(_):
96+ break
97+ }
98+
99+ if (eom) {
100+ prompt += "<|eom_id|>"
101+ } else {
102+ prompt += "<|eot_id|>"
103+ }
104+
105+ return prompt
106+}
107+
108+func prepareMessages(request: Components.Schemas.ChatCompletionRequest) throws -> [Components.Schemas.ChatCompletionRequest.messagesPayloadPayload] {
109+ var existingMessages = request.messages
110+ var existingSystemMessage: Components.Schemas.ChatCompletionRequest.messagesPayloadPayload?
111+ // TODO: Existing system message
112+
113+ var messages: [Components.Schemas.ChatCompletionRequest.messagesPayloadPayload] = []
114+
115+ let defaultGen = SystemDefaultGenerator()
116+ let defaultTemplate = defaultGen.gen()
117+
118+ var sysContent = ""
119+
120+ // TODO: Built-in tools
121+
122+ sysContent += try defaultTemplate.render()
123+
124+ messages.append(.SystemMessage(Components.Schemas.SystemMessage(
125+ content: .case1(sysContent),
126+ role: .system))
127+ )
128+
129+ if request.tools?.isEmpty == false {
130+ // TODO: Separate built-ins and custom tools (right now everything treated as custom)
131+ let toolGen = FunctionTagCustomToolGenerator()
132+ let toolTemplate = try toolGen.gen(customTools: request.tools!)
133+ let tools = try toolTemplate.render()
134+ messages.append(.UserMessage(Components.Schemas.UserMessage(
135+ content: .case1(tools),
136+ role: .user)
137+ ))
138+ }
139+
140+ messages.append(contentsOf: existingMessages)
141+
142+ return messages
143+}
144+
145+struct FunctionCall {
146+ let name: String
147+ let params: [String: Any]
148+}
149+
150+public func maybeExtractCustomToolCalls(input: String) -> [Components.Schemas.ToolCall] {
151+ guard input.hasPrefix("[") && input.hasSuffix("]") else {
152+ return []
153+ }
154+
155+ do {
156+ let trimmed = input.trimmingCharacters(in: CharacterSet(charactersIn: "[]"))
157+ let calls = trimmed.components(separatedBy: "),").map { $0.hasSuffix(")") ? $0 : $0 + ")" }
158+
159+ var result: [Components.Schemas.ToolCall] = []
160+
161+ for call in calls {
162+ guard let nameEndIndex = call.firstIndex(of: "("),
163+ let paramsStartIndex = call.firstIndex(of: "{"),
164+ let paramsEndIndex = call.lastIndex(of: "}") else {
165+ return []
166+ }
167+
168+ let name = String(call[..<nameEndIndex]).trimmingCharacters(in: .whitespacesAndNewlines)
169+ let paramsString = String(call[paramsStartIndex...paramsEndIndex])
170+
171+ guard let data = paramsString.data(using: .utf8),
172+ let params = try? JSONSerialization.jsonObject(with: data, options: []) as? [String: Any] else {
173+ return []
174+ }
175+
176+ var props: [String : Components.Schemas.ToolCall.argumentsPayload.additionalPropertiesPayload] = [:]
177+ for (param_name, param) in params {
178+ switch (param) {
179+ case let value as String:
180+ props[param_name] = .case1(value)
181+ case let value as Int:
182+ props[param_name] = .case2(value)
183+ case let value as Double:
184+ props[param_name] = .case3(value)
185+ case let value as Bool:
186+ props[param_name] = .case4(value)
187+ default:
188+ return []
189+ }
190+ }
191+
192+ result.append(
193+ Components.Schemas.ToolCall(
194+ arguments: .init(additionalProperties: props),
195+ call_id: UUID().uuidString,
196+ tool_name: .case2(name) // custom_tool
197+ )
198+ )
199+ }
200+
201+ return result.isEmpty ? [] : result
202+ } catch {
203+ return []
204+ }
205+}
206+
207+func decodeAssistantMessage(tokens: String, stopReason: Components.Schemas.StopReason) -> Components.Schemas.CompletionMessage {
208+ var content = tokens
209+
210+ let roles = ["user", "system", "assistant"]
211+ for role in roles {
212+ let headerStr = encodeHeader(role: role)
213+ if content.hasPrefix(headerStr) {
214+ content = String(content.dropFirst(encodeHeader(role: role).count))
215+ }
216+ }
217+
218+ if content.hasPrefix("<|python_tag|>") {
219+ content = String(content.dropFirst("<|python_tag|>".count))
220+ }
221+
222+
223+ if content.hasSuffix("<|eot_id|>") {
224+ content = String(content.dropLast("<|eot_id|>".count))
225+ } else {
226+ content = String(content.dropLast("<|eom_id|>".count))
227+ }
228+
229+ return Components.Schemas.CompletionMessage(
230+ content: .case1(content),
231+ role: .assistant,
232+ stop_reason: stopReason,
233+ tool_calls: maybeExtractCustomToolCalls(input: content)
234+ )
235+}
added llama_stack/providers/impls/ios/inference/LocalInference/LocalInferenceImpl/PromptTemplate.swift +12 −0
@@ -0,0 +1,12 @@
1+import Foundation
2+import Stencil
3+
4+public struct PromptTemplate {
5+ let template: String
6+ let data: [String: Any]
7+
8+ public func render() throws -> String {
9+ let template = Template(templateString: self.template)
10+ return try template.render(self.data)
11+ }
12+}
added llama_stack/providers/impls/ios/inference/LocalInference/LocalInferenceImpl/SystemPrompts.swift +91 −0
@@ -0,0 +1,91 @@
1+import Foundation
2+
3+import LlamaStackClient
4+
5+func convertToNativeSwiftType(_ value: Any) -> Any {
6+ switch value {
7+ case let number as NSNumber:
8+ if CFGetTypeID(number) == CFBooleanGetTypeID() {
9+ return number.boolValue
10+ }
11+ if floor(number.doubleValue) == number.doubleValue {
12+ return number.intValue
13+ }
14+ return number.doubleValue
15+ case let string as String:
16+ return string
17+ case let array as [Any]:
18+ return array.map(convertToNativeSwiftType)
19+ case let dict as [String: Any]:
20+ return dict.mapValues(convertToNativeSwiftType)
21+ case is NSNull:
22+ return NSNull()
23+ default:
24+ return value
25+ }
26+}
27+
28+public class SystemDefaultGenerator {
29+ public init() {}
30+
31+ public func gen() -> PromptTemplate {
32+ let templateStr = """
33+ Cutting Knowledge Date: December 2023
34+ Today Date: {{ today }}
35+ """
36+
37+ let dateFormatter = DateFormatter()
38+ dateFormatter.dateFormat = "dd MMMM yyyy"
39+
40+ return PromptTemplate(
41+ template: templateStr,
42+ data: ["today": dateFormatter.string(from: Date())]
43+ )
44+ }
45+}
46+
47+
48+public class FunctionTagCustomToolGenerator {
49+ public init() {}
50+
51+ public func gen(customTools: [Components.Schemas.ToolDefinition]) throws -> PromptTemplate {
52+ // TODO: required params
53+ // TODO: {{#unless @last}},{{/unless}}
54+
55+ let templateStr = """
56+ You are an expert in composing functions. You are given a question and a set of possible functions.
57+ Based on the question, you will need to make one or more function/tool calls to achieve the purpose.
58+ If none of the function can be used, point it out. If the given question lacks the parameters required by the function,
59+ also point it out. You should only return the function call in tools call sections.
60+
61+ If you decide to invoke any of the function(s), you MUST put it in the format of [func_name1(params_name1=params_value1, params_name2=params_value2...), func_name2(params)]
62+ You SHOULD NOT include any other text in the response.
63+
64+ Here is a list of functions in JSON format that you can invoke.
65+
66+ [
67+ {% for t in custom_tools %}
68+ {
69+ "name": "{{t.tool_name}}",
70+ "description": "{{t.description}}",
71+ "parameters": {
72+ "type": "dict",
73+ "properties": { {{t.parameters}} }
74+ }
75+
76+ {{/let}}
77+ {% endfor -%}
78+ ]
79+ """
80+
81+ let encoder = JSONEncoder()
82+ return PromptTemplate(
83+ template: templateStr,
84+ data: ["custom_tools": try customTools.map {
85+ let data = try encoder.encode($0)
86+ let obj = try JSONSerialization.jsonObject(with: data)
87+ return convertToNativeSwiftType(obj)
88+ }]
89+ )
90+ }
91+}
added llama_stack/providers/impls/ios/inference/LocalInference/README.md +109 −0
@@ -0,0 +1,109 @@
1+# LocalInference
2+
3+LocalInference provides a local inference implementation powered by [executorch](https://github.com/pytorch/executorch/).
4+
5+Llama Stack currently supports on-device inference for iOS with Android coming soon. You can run on-device inference on Android today using [executorch](https://github.com/pytorch/executorch/tree/main/examples/demo-apps/android/LlamaDemo), PyTorch’s on-device inference library.
6+
7+## Installation
8+
9+We're working on making LocalInference easier to set up. For now, you'll need to import it via `.xcframework`:
10+
11+1. Clone the executorch submodule in this repo and its dependencies: `git submodule update --init --recursive`
12+1. Install [Cmake](https://cmake.org/) for the executorch build`
13+1. Drag `LocalInference.xcodeproj` into your project
14+1. Add `LocalInference` as a framework in your app target
15+1. Add a package dependency on https://github.com/pytorch/executorch (branch latest)
16+1. Add all the kernels / backends from executorch (but not exectuorch itself!) as frameworks in your app target:
17+ - backend_coreml
18+ - backend_mps
19+ - backend_xnnpack
20+ - kernels_custom
21+ - kernels_optimized
22+ - kernels_portable
23+ - kernels_quantized
24+1. In "Build Settings" > "Other Linker Flags" > "Any iOS Simulator SDK", add:
25+ ```
26+ -force_load
27+ $(BUILT_PRODUCTS_DIR)/libkernels_optimized-simulator-release.a
28+ -force_load
29+ $(BUILT_PRODUCTS_DIR)/libkernels_custom-simulator-release.a
30+ -force_load
31+ $(BUILT_PRODUCTS_DIR)/libkernels_quantized-simulator-release.a
32+ -force_load
33+ $(BUILT_PRODUCTS_DIR)/libbackend_xnnpack-simulator-release.a
34+ -force_load
35+ $(BUILT_PRODUCTS_DIR)/libbackend_coreml-simulator-release.a
36+ -force_load
37+ $(BUILT_PRODUCTS_DIR)/libbackend_mps-simulator-release.a
38+ ```
39+
40+1. In "Build Settings" > "Other Linker Flags" > "Any iOS SDK", add:
41+
42+ ```
43+ -force_load
44+ $(BUILT_PRODUCTS_DIR)/libkernels_optimized-simulator-release.a
45+ -force_load
46+ $(BUILT_PRODUCTS_DIR)/libkernels_custom-simulator-release.a
47+ -force_load
48+ $(BUILT_PRODUCTS_DIR)/libkernels_quantized-simulator-release.a
49+ -force_load
50+ $(BUILT_PRODUCTS_DIR)/libbackend_xnnpack-simulator-release.a
51+ -force_load
52+ $(BUILT_PRODUCTS_DIR)/libbackend_coreml-simulator-release.a
53+ -force_load
54+ $(BUILT_PRODUCTS_DIR)/libbackend_mps-simulator-release.a
55+ ```
56+
57+## Preparing a model
58+
59+1. Prepare a `.pte` file [following the executorch docs](https://github.com/pytorch/executorch/blob/main/examples/models/llama2/README.md#step-2-prepare-model)
60+2. Bundle the `.pte` and `tokenizer.model` file into your app
61+
62+## Using LocalInference
63+
64+1. Instantiate LocalInference with a DispatchQueue. Optionally, pass it into your agents service:
65+
66+```swift
67+ init () {
68+ runnerQueue = DispatchQueue(label: "org.meta.llamastack")
69+ inferenceService = LocalInferenceService(queue: runnerQueue)
70+ agentsService = LocalAgentsService(inference: inferenceService)
71+ }
72+```
73+
74+2. Before making any inference calls, load your model from your bundle:
75+
76+```swift
77+let mainBundle = Bundle.main
78+inferenceService.loadModel(
79+ modelPath: mainBundle.url(forResource: "llama32_1b_spinquant", withExtension: "pte"),
80+ tokenizerPath: mainBundle.url(forResource: "tokenizer", withExtension: "model"),
81+ completion: {_ in } // use to handle load failures
82+)
83+```
84+
85+3. Make inference calls (or agents calls) as you normally would with LlamaStack:
86+
87+```
88+for await chunk in try await agentsService.initAndCreateTurn(
89+ messages: [
90+ .UserMessage(Components.Schemas.UserMessage(
91+ content: .case1("Call functions as needed to handle any actions in the following text:\n\n" + text),
92+ role: .user))
93+ ]
94+) {
95+```
96+
97+## Troubleshooting
98+
99+If you receive errors like "missing package product" or "invalid checksum", try cleaning the build folder and resetting the Swift package cache:
100+
101+(Opt+Click) Product > Clean Build Folder Immediately
102+
103+```
104+rm -rf \
105+ ~/Library/org.swift.swiftpm \
106+ ~/Library/Caches/org.swift.swiftpm \
107+ ~/Library/Caches/com.apple.dt.Xcode \
108+ ~/Library/Developer/Xcode/DerivedData
109+```
modified llama_stack/providers/impls/meta_reference/agents/agent_instance.py +12 −1
@@ -398,7 +398,11 @@
398398 color = "yellow"
399399 else:
400400 color = None
401- cprint(f"{str(msg)}", color=color)
401+ if len(str(msg)) > 1000:
402+ msg_str = f"{str(msg)[:500]}...<more>...{str(msg)[-500:]}"
403+ else:
404+ msg_str = str(msg)
405+ cprint(f"{msg_str}", color=color)
402406
403407 step_id = str(uuid.uuid4())
404408 yield AgentTurnResponseStreamChunk(
@@ -466,6 +470,13 @@
466470 stop_reason = event.stop_reason
467471
468472 stop_reason = stop_reason or StopReason.out_of_tokens
473+
474+ # If tool calls are parsed successfully,
475+ # if content is not made null the tool call str will also be in the content
476+ # and tokens will have tool call syntax included twice
477+ if tool_calls:
478+ content = ""
479+
469480 message = CompletionMessage(
470481 content=content,
471482 stop_reason=stop_reason,
modified llama_stack/providers/impls/meta_reference/agents/rag/context_retriever.py +2 −1
@@ -10,13 +10,14 @@
1010 from llama_models.llama3.api import * # noqa: F403
1111
1212
13+from termcolor import cprint # noqa: F401
14+
1315 from llama_stack.apis.agents import (
1416 DefaultMemoryQueryGeneratorConfig,
1517 LLMMemoryQueryGeneratorConfig,
1618 MemoryQueryGenerator,
1719 MemoryQueryGeneratorConfig,
1820 )
19-from termcolor import cprint # noqa: F401
2021 from llama_stack.apis.inference import * # noqa: F403
2122
2223
modified llama_stack/providers/impls/meta_reference/inference/config.py +4 −9
@@ -16,7 +16,7 @@
1616
1717 class MetaReferenceImplConfig(BaseModel):
1818 model: str = Field(
19- default="Meta-Llama3.1-8B-Instruct",
19+ default="Llama3.1-8B-Instruct",
2020 description="Model descriptor from `llama model list`",
2121 )
2222 quantization: Optional[QuantizationConfig] = None
@@ -30,7 +30,7 @@
3030 permitted_models = [
3131 m.descriptor()
3232 for m in all_registered_models()
33- if m.model_family == ModelFamily.llama3_1
33+ if m.model_family in {ModelFamily.llama3_1, ModelFamily.llama3_2}
3434 or m.core_model_id == CoreModelId.llama_guard_3_8b
3535 ]
3636 if model not in permitted_models:
@@ -42,14 +42,9 @@
4242
4343 @property
4444 def model_parallel_size(self) -> int:
45- # HUGE HACK ALERT: this will be fixed when we move inference configuration
45+ # HACK ALERT: this will be fixed when we move inference configuration
4646 # to ModelsRegistry and we can explicitly ask for `model_parallel_size`
4747 # as configuration there
48- gpu_count = 1
4948 resolved = resolve_model(self.model)
5049 assert resolved is not None
51- descriptor = resolved.descriptor().lower()
52- if "-70b" in descriptor or "-405b" in descriptor:
53- gpu_count = 8
54-
55- return gpu_count
50+ return resolved.pth_file_count
modified llama_stack/providers/impls/meta_reference/inference/generation.py +71 −10
@@ -24,21 +24,31 @@
2424 )
2525 from llama_models.llama3.api.args import ModelArgs
2626 from llama_models.llama3.api.chat_format import ChatFormat, ModelInput
27-from llama_models.llama3.api.datatypes import Message, ToolPromptFormat
27+from llama_models.llama3.api.datatypes import (
28+ InterleavedTextMedia,
29+ Message,
30+ ToolPromptFormat,
31+)
2832 from llama_models.llama3.api.tokenizer import Tokenizer
2933 from llama_models.llama3.reference_impl.model import Transformer
34+from llama_models.llama3.reference_impl.multimodal.model import (
35+ CrossAttentionTransformer,
36+)
3037 from llama_models.sku_list import resolve_model
38+from termcolor import cprint
39+
3140 from llama_stack.apis.inference import QuantizationType
3241
3342 from llama_stack.distribution.utils.model_utils import model_local_dir
34-from termcolor import cprint
3543
3644 from .config import MetaReferenceImplConfig
3745
3846
3947 def model_checkpoint_dir(model) -> str:
4048 checkpoint_dir = Path(model_local_dir(model.descriptor()))
41- if not Path(checkpoint_dir / "consolidated.00.pth").exists():
49+
50+ paths = [Path(checkpoint_dir / f"consolidated.{ext}") for ext in ["pth", "00.pth"]]
51+ if not any(p.exists() for p in paths):
4252 checkpoint_dir = checkpoint_dir / "original"
4353
4454 assert checkpoint_dir.exists(), (
@@ -134,7 +144,11 @@
134144 # load on CPU in bf16 so that fp8 conversion does not find an
135145 # unexpected (fp32, e.g.) datatype
136146 torch.set_default_tensor_type(torch.BFloat16Tensor)
137- model = Transformer(model_args)
147+ if model_args.vision_chunk_size > 0:
148+ model = CrossAttentionTransformer(model_args)
149+ model.setup_cache(model_args.max_batch_size, torch.bfloat16)
150+ else:
151+ model = Transformer(model_args)
138152 model.load_state_dict(state_dict, strict=False)
139153 model = convert_to_quantized_model(model, config)
140154 else:
@@ -142,7 +156,11 @@
142156 torch.set_default_tensor_type(torch.cuda.BFloat16Tensor)
143157 else:
144158 torch.set_default_tensor_type(torch.cuda.HalfTensor)
145- model = Transformer(model_args)
159+ if model_args.vision_chunk_size > 0:
160+ model = CrossAttentionTransformer(model_args)
161+ model.setup_cache(model_args.max_batch_size, torch.bfloat16)
162+ else:
163+ model = Transformer(model_args)
146164 model.load_state_dict(state_dict, strict=False)
147165
148166 print(f"Loaded in {time.time() - start_time:.2f} seconds")
@@ -167,7 +185,11 @@
167185 ) -> Generator:
168186 params = self.model.params
169187
170- # cprint("Input to model -> " + self.tokenizer.decode(model_input.tokens), "red")
188+ # input_tokens = [
189+ # self.formatter.vision_token if t == 128256 else t
190+ # for t in model_input.tokens
191+ # ]
192+ # cprint("Input to model -> " + self.tokenizer.decode(input_tokens), "red")
171193 prompt_tokens = [model_input.tokens]
172194
173195 bsz = 1
@@ -183,6 +205,21 @@
183205 return
184206
185207 total_len = min(max_gen_len + max_prompt_len, params.max_seq_len)
208+
209+ is_vision = isinstance(self.model, CrossAttentionTransformer)
210+ if is_vision:
211+ images = model_input.vision.images if model_input.vision is not None else []
212+ mask = model_input.vision.mask if model_input.vision is not None else []
213+
214+ # the method works for bsz > 1 so add a batch dimension
215+ xattn_caches, cross_attention_masks, full_text_row_masked_out_mask = (
216+ self.model.compute_vision_tokens_masks(
217+ batch_images=[images],
218+ batch_masks=[mask],
219+ total_len=total_len,
220+ )
221+ )
222+
186223 pad_id = self.tokenizer.pad_id
187224 tokens = torch.full((bsz, total_len), pad_id, dtype=torch.long, device="cuda")
188225 for k, t in enumerate(prompt_tokens):
@@ -206,7 +243,19 @@
206243 stop_tokens = torch.tensor(self.tokenizer.stop_tokens)
207244
208245 for cur_pos in range(min_prompt_len, total_len):
209- logits = self.model.forward(tokens[:, prev_pos:cur_pos], prev_pos)
246+ if is_vision:
247+ position_ids = torch.arange(
248+ prev_pos, cur_pos, dtype=torch.long, device="cuda"
249+ )
250+ logits = self.model.forward(
251+ position_ids,
252+ tokens,
253+ cross_attention_masks,
254+ full_text_row_masked_out_mask,
255+ xattn_caches,
256+ )
257+ else:
258+ logits = self.model.forward(tokens[:, prev_pos:cur_pos], prev_pos)
210259
211260 if temperature > 0:
212261 probs = torch.softmax(logits[:, -1] / temperature, dim=-1)
@@ -222,6 +271,18 @@
222271 tokens[:, cur_pos] = next_token
223272
224273 target = tokens[:, prev_pos + 1 : cur_pos + 1]
274+ if is_vision:
275+ # the logits space (num_classes) is designed to never contain a media_token
276+ # however our input token stream does contain them. we need to nuke them here
277+ # or else the CUDA kernels will crash with an illegal memory access
278+ vision_tokens = [self.tokenizer.special_tokens["<|image|>"], 128256]
279+ masks = [target.eq(t) for t in vision_tokens]
280+ if len(masks) > 1:
281+ mask = torch.logical_or(*masks)
282+ else:
283+ mask = masks[0]
284+ target[mask] = 0
285+
225286 if logprobs:
226287 token_logprobs[:, prev_pos + 1 : cur_pos + 1] = -F.cross_entropy(
227288 input=logits.transpose(1, 2),
@@ -248,7 +309,7 @@
248309
249310 def text_completion(
250311 self,
251- prompt: str,
312+ content: InterleavedTextMedia,
252313 temperature: float = 0.6,
253314 top_p: float = 0.9,
254315 max_gen_len: Optional[int] = None,
@@ -262,10 +323,10 @@
262323 ):
263324 max_gen_len = self.model.params.max_seq_len - 1
264325
265- prompt_tokens = self.tokenizer.encode(prompt, bos=True, eos=False)
326+ model_input = self.formatter.encode_content(content)
266327
267328 yield from self.generate(
268- model_input=ModelInput(tokens=prompt_tokens),
329+ model_input=model_input,
269330 max_gen_len=max_gen_len,
270331 temperature=temperature,
271332 top_p=top_p,
modified llama_stack/providers/impls/meta_reference/inference/inference.py +6 −4
@@ -21,7 +21,9 @@
2121 ToolCallDelta,
2222 ToolCallParseStatus,
2323 )
24-from llama_stack.providers.utils.inference.prepare_messages import prepare_messages
24+from llama_stack.providers.utils.inference.augment_messages import (
25+ augment_messages_for_tools,
26+)
2527
2628 from .config import MetaReferenceImplConfig
2729 from .model_parallel import LlamaModelParallelGenerator
@@ -57,7 +59,7 @@
5759 model: str,
5860 messages: List[Message],
5961 sampling_params: Optional[SamplingParams] = SamplingParams(),
60- tools: Optional[List[ToolDefinition]] = [],
62+ tools: Optional[List[ToolDefinition]] = None,
6163 tool_choice: Optional[ToolChoice] = ToolChoice.auto,
6264 tool_prompt_format: Optional[ToolPromptFormat] = ToolPromptFormat.json,
6365 stream: Optional[bool] = False,
@@ -70,14 +72,14 @@
7072 model=model,
7173 messages=messages,
7274 sampling_params=sampling_params,
73- tools=tools,
75+ tools=tools or [],
7476 tool_choice=tool_choice,
7577 tool_prompt_format=tool_prompt_format,
7678 stream=stream,
7779 logprobs=logprobs,
7880 )
7981
80- messages = prepare_messages(request)
82+ messages = augment_messages_for_tools(request)
8183 model = resolve_model(request.model)
8284 if model is None:
8385 raise RuntimeError(
modified llama_stack/providers/impls/meta_reference/safety/__init__.py +2 −2
@@ -7,11 +7,11 @@
77 from .config import SafetyConfig
88
99
10-async def get_provider_impl(config: SafetyConfig, _deps):
10+async def get_provider_impl(config: SafetyConfig, deps):
1111 from .safety import MetaReferenceSafetyImpl
1212
1313 assert isinstance(config, SafetyConfig), f"Unexpected config type: {type(config)}"
1414
15- impl = MetaReferenceSafetyImpl(config)
15+ impl = MetaReferenceSafetyImpl(config, deps)
1616 await impl.initialize()
1717 return impl
modified llama_stack/providers/impls/meta_reference/safety/config.py +4 −1
@@ -31,7 +31,10 @@
3131 permitted_models = [
3232 m.descriptor()
3333 for m in safety_models()
34- if m.core_model_id == CoreModelId.llama_guard_3_8b
34+ if (
35+ m.core_model_id
36+ in {CoreModelId.llama_guard_3_8b, CoreModelId.llama_guard_3_11b_vision}
37+ )
3538 ]
3639 if model not in permitted_models:
3740 raise ValueError(
modified llama_stack/providers/impls/meta_reference/safety/safety.py +14 −14
@@ -7,8 +7,10 @@
77 from llama_models.sku_list import resolve_model
88
99 from llama_stack.distribution.utils.model_utils import model_local_dir
10+from llama_stack.apis.inference import * # noqa: F403
1011 from llama_stack.apis.safety import * # noqa: F403
1112 from llama_models.llama3.api.datatypes import * # noqa: F403
13+from llama_stack.distribution.datatypes import Api
1214
1315 from llama_stack.providers.impls.meta_reference.safety.shields.base import (
1416 OnViolationAction,
@@ -34,20 +36,11 @@
3436
3537
3638 class MetaReferenceSafetyImpl(Safety):
37- def __init__(self, config: SafetyConfig) -> None:
39+ def __init__(self, config: SafetyConfig, deps) -> None:
3840 self.config = config
41+ self.inference_api = deps[Api.inference]
3942
4043 async def initialize(self) -> None:
41- shield_cfg = self.config.llama_guard_shield
42- if shield_cfg is not None:
43- model_dir = resolve_and_get_path(shield_cfg.model)
44- _ = LlamaGuardShield.instance(
45- model_dir=model_dir,
46- excluded_categories=shield_cfg.excluded_categories,
47- disable_input_check=shield_cfg.disable_input_check,
48- disable_output_check=shield_cfg.disable_output_check,
49- )
50-
5144 shield_cfg = self.config.prompt_guard_shield
5245 if shield_cfg is not None:
5346 model_dir = resolve_and_get_path(shield_cfg.model)
@@ -91,11 +84,18 @@
9184 def get_shield_impl(self, typ: MetaReferenceShieldType) -> ShieldBase:
9285 cfg = self.config
9386 if typ == MetaReferenceShieldType.llama_guard:
87+ cfg = cfg.llama_guard_shield
9488 assert (
95- cfg.llama_guard_shield is not None
89+ cfg is not None
9690 ), "Cannot use LlamaGuardShield since not present in config"
97- model_dir = resolve_and_get_path(cfg.llama_guard_shield.model)
98- return LlamaGuardShield.instance(model_dir=model_dir)
91+
92+ return LlamaGuardShield(
93+ model=cfg.model,
94+ inference_api=self.inference_api,
95+ excluded_categories=cfg.excluded_categories,
96+ disable_input_check=cfg.disable_input_check,
97+ disable_output_check=cfg.disable_output_check,
98+ )
9999 elif typ == MetaReferenceShieldType.jailbreak_shield:
100100 assert (
101101 cfg.prompt_guard_shield is not None
modified llama_stack/providers/impls/meta_reference/safety/shields/llama_guard.py +22 −56
@@ -9,9 +9,8 @@
99 from string import Template
1010 from typing import List, Optional
1111
12-import torch
1312 from llama_models.llama3.api.datatypes import Message, Role
14-from transformers import AutoModelForCausalLM, AutoTokenizer
13+from llama_stack.apis.inference import * # noqa: F403
1514
1615 from .base import CANNED_RESPONSE_TEXT, OnViolationAction, ShieldBase, ShieldResponse
1716
@@ -100,39 +99,17 @@
10099
101100
102101 class LlamaGuardShield(ShieldBase):
103- @staticmethod
104- def instance(
105- on_violation_action=OnViolationAction.RAISE,
106- model_dir: str = None,
107- excluded_categories: List[str] = None,
108- disable_input_check: bool = False,
109- disable_output_check: bool = False,
110- ) -> "LlamaGuardShield":
111- global _INSTANCE
112- if _INSTANCE is None:
113- _INSTANCE = LlamaGuardShield(
114- on_violation_action,
115- model_dir,
116- excluded_categories,
117- disable_input_check,
118- disable_output_check,
119- )
120- return _INSTANCE
121-
122102 def __init__(
123103 self,
124- on_violation_action: OnViolationAction = OnViolationAction.RAISE,
125- model_dir: str = None,
104+ model: str,
105+ inference_api: Inference,
126106 excluded_categories: List[str] = None,
127107 disable_input_check: bool = False,
128108 disable_output_check: bool = False,
109+ on_violation_action: OnViolationAction = OnViolationAction.RAISE,
129110 ):
130111 super().__init__(on_violation_action)
131112
132- dtype = torch.bfloat16
133-
134- assert model_dir is not None, "Llama Guard model_dir is None"
135-
136113 if excluded_categories is None:
137114 excluded_categories = []
138115
@@ -140,18 +117,12 @@
140117 x in SAFETY_CATEGORIES_TO_CODE_MAP.values() for x in excluded_categories
141118 ), "Invalid categories in excluded categories. Expected format is ['S1', 'S2', ..]"
142119
143- self.device = "cuda"
120+ self.model = model
121+ self.inference_api = inference_api
144122 self.excluded_categories = excluded_categories
145123 self.disable_input_check = disable_input_check
146124 self.disable_output_check = disable_output_check
147125
148- # load model
149- torch_dtype = torch.bfloat16
150- self.tokenizer = AutoTokenizer.from_pretrained(model_dir)
151- self.model = AutoModelForCausalLM.from_pretrained(
152- model_dir, torch_dtype=torch_dtype, device_map=self.device
153- )
154-
155126 def check_unsafe_response(self, response: str) -> Optional[str]:
156127 match = re.match(r"^unsafe\n(.*)$", response)
157128 if match:
@@ -212,26 +183,21 @@
212183 )
213184 else:
214185 prompt = self.build_prompt(messages)
215- llama_guard_input = {
216- "role": "user",
217- "content": prompt,
218- }
219- input_ids = self.tokenizer.apply_chat_template(
220- [llama_guard_input], return_tensors="pt", tokenize=True
221- ).to(self.device)
222- prompt_len = input_ids.shape[1]
223- output = self.model.generate(
224- input_ids=input_ids,
225- max_new_tokens=20,
226- output_scores=True,
227- return_dict_in_generate=True,
228- pad_token_id=0,
229- )
230- generated_tokens = output.sequences[:, prompt_len:]
231186
232- response = self.tokenizer.decode(
233- generated_tokens[0], skip_special_tokens=True
234- )
235- response = response.strip()
236- shield_response = self.get_shield_response(response)
187+ # TODO: llama-stack inference protocol has issues with non-streaming inference code
188+ content = ""
189+ async for chunk in self.inference_api.chat_completion(
190+ model=self.model,
191+ messages=[
192+ UserMessage(content=prompt),
193+ ],
194+ stream=True,
195+ ):
196+ event = chunk.event
197+ if event.event_type == ChatCompletionResponseEventType.progress:
198+ assert isinstance(event.delta, str)
199+ content += event.delta
200+
201+ content = content.strip()
202+ shield_response = self.get_shield_response(content)
237203 return shield_response
modified llama_stack/providers/registry/inference.py +1 −11
@@ -20,6 +20,7 @@
2020 "fairscale",
2121 "fbgemm-gpu==0.8.0",
2222 "torch",
23+ "torchvision",
2324 "transformers",
2425 "zmq",
2526 ],
@@ -75,15 +76,4 @@
7576 header_extractor_class="llama_stack.providers.adapters.inference.together.TogetherHeaderExtractor",
7677 ),
7778 ),
78- remote_provider_spec(
79- api=Api.inference,
80- adapter=AdapterSpec(
81- adapter_id="bedrock",
82- pip_packages=[
83- "boto3",
84- ],
85- module="llama_stack.providers.adapters.inference.bedrock",
86- config_class="llama_stack.providers.adapters.inference.bedrock.BedrockConfig",
87- ),
88- ),
8979 ]
modified llama_stack/providers/registry/safety.py +4 −2
@@ -21,13 +21,15 @@
2121 api=Api.safety,
2222 provider_id="meta-reference",
2323 pip_packages=[
24- "accelerate",
2524 "codeshield",
26- "torch",
2725 "transformers",
26+ "torch --index-url https://download.pytorch.org/whl/cpu",
2827 ],
2928 module="llama_stack.providers.impls.meta_reference.safety",
3029 config_class="llama_stack.providers.impls.meta_reference.safety.SafetyConfig",
30+ api_dependencies=[
31+ Api.inference,
32+ ],
3133 ),
3234 remote_provider_spec(
3335 api=Api.safety,
added llama_stack/providers/utils/inference/augment_messages.py +170 −0
@@ -0,0 +1,170 @@
1+# Copyright (c) Meta Platforms, Inc. and affiliates.
2+# All rights reserved.
3+#
4+# This source code is licensed under the terms described in the LICENSE file in
5+# the root directory of this source tree.
6+from termcolor import cprint
7+from llama_models.llama3.api.datatypes import * # noqa: F403
8+from llama_stack.apis.inference import * # noqa: F403
9+from llama_models.datatypes import ModelFamily
10+from llama_models.llama3.prompt_templates import (
11+ BuiltinToolGenerator,
12+ FunctionTagCustomToolGenerator,
13+ JsonCustomToolGenerator,
14+ PythonListCustomToolGenerator,
15+ SystemDefaultGenerator,
16+)
17+from llama_models.sku_list import resolve_model
18+
19+
20+def augment_messages_for_tools(request: ChatCompletionRequest) -> List[Message]:
21+ """Reads chat completion request and augments the messages to handle tools.
22+ For eg. for llama_3_1, add system message with the appropriate tools or
23+ add user messsage for custom tools, etc.
24+ """
25+ model = resolve_model(request.model)
26+ if model is None:
27+ cprint(f"Could not resolve model {request.model}", color="red")
28+ return request.messages
29+
30+ if model.model_family not in [ModelFamily.llama3_1, ModelFamily.llama3_2]:
31+ cprint(f"Model family {model.model_family} not llama 3_1 or 3_2", color="red")
32+ return request.messages
33+
34+ if model.model_family == ModelFamily.llama3_1 or (
35+ model.model_family == ModelFamily.llama3_2 and is_multimodal(model)
36+ ):
37+ # llama3.1 and llama3.2 multimodal models follow the same tool prompt format
38+ return augment_messages_for_tools_llama_3_1(request)
39+ elif model.model_family == ModelFamily.llama3_2:
40+ return augment_messages_for_tools_llama_3_2(request)
41+ else:
42+ return request.messages
43+
44+
45+def augment_messages_for_tools_llama_3_1(
46+ request: ChatCompletionRequest,
47+) -> List[Message]:
48+
49+ assert request.tool_choice == ToolChoice.auto, "Only `ToolChoice.auto` supported"
50+
51+ existing_messages = request.messages
52+ existing_system_message = None
53+ if existing_messages[0].role == Role.system.value:
54+ existing_system_message = existing_messages.pop(0)
55+
56+ assert (
57+ existing_messages[0].role != Role.system.value
58+ ), "Should only have 1 system message"
59+
60+ messages = []
61+
62+ default_gen = SystemDefaultGenerator()
63+ default_template = default_gen.gen()
64+
65+ sys_content = ""
66+
67+ tool_template = None
68+ if request.tools:
69+ tool_gen = BuiltinToolGenerator()
70+ tool_template = tool_gen.gen(request.tools)
71+
72+ sys_content += tool_template.render()
73+ sys_content += "\n"
74+
75+ sys_content += default_template.render()
76+
77+ if existing_system_message:
78+ # TODO: this fn is needed in many places
79+ def _process(c):
80+ if isinstance(c, str):
81+ return c
82+ else:
83+ return "<media>"
84+
85+ sys_content += "\n"
86+
87+ if isinstance(existing_system_message.content, str):
88+ sys_content += _process(existing_system_message.content)
89+ elif isinstance(existing_system_message.content, list):
90+ sys_content += "\n".join(
91+ [_process(c) for c in existing_system_message.content]
92+ )
93+
94+ messages.append(SystemMessage(content=sys_content))
95+
96+ has_custom_tools = any(isinstance(dfn.tool_name, str) for dfn in request.tools)
97+ if has_custom_tools:
98+ if request.tool_prompt_format == ToolPromptFormat.json:
99+ tool_gen = JsonCustomToolGenerator()
100+ elif request.tool_prompt_format == ToolPromptFormat.function_tag:
101+ tool_gen = FunctionTagCustomToolGenerator()
102+ else:
103+ raise ValueError(
104+ f"Non supported ToolPromptFormat {request.tool_prompt_format}"
105+ )
106+
107+ custom_tools = [t for t in request.tools if isinstance(t.tool_name, str)]
108+ custom_template = tool_gen.gen(custom_tools)
109+ messages.append(UserMessage(content=custom_template.render()))
110+
111+ # Add back existing messages from the request
112+ messages += existing_messages
113+
114+ return messages
115+
116+
117+def augment_messages_for_tools_llama_3_2(
118+ request: ChatCompletionRequest,
119+) -> List[Message]:
120+ assert request.tool_choice == ToolChoice.auto, "Only `ToolChoice.auto` supported"
121+
122+ existing_messages = request.messages
123+ existing_system_message = None
124+ if existing_messages[0].role == Role.system.value:
125+ existing_system_message = existing_messages.pop(0)
126+
127+ assert (
128+ existing_messages[0].role != Role.system.value
129+ ), "Should only have 1 system message"
130+
131+ messages = []
132+ sys_content = ""
133+ custom_tools, builtin_tools = [], []
134+ for t in request.tools:
135+ if isinstance(t.tool_name, str):
136+ custom_tools.append(t)
137+ else:
138+ builtin_tools.append(t)
139+
140+ tool_template = None
141+ if builtin_tools:
142+ tool_gen = BuiltinToolGenerator()
143+ tool_template = tool_gen.gen(builtin_tools)
144+
145+ sys_content += tool_template.render()
146+ sys_content += "\n"
147+
148+ custom_tools = [dfn for dfn in request.tools if isinstance(dfn.tool_name, str)]
149+ if custom_tools:
150+ if request.tool_prompt_format != ToolPromptFormat.python_list:
151+ raise ValueError(
152+ f"Non supported ToolPromptFormat {request.tool_prompt_format}"
153+ )
154+
155+ tool_gen = PythonListCustomToolGenerator()
156+ tool_template = tool_gen.gen(custom_tools)
157+
158+ sys_content += tool_template.render()
159+ sys_content += "\n"
160+
161+ if existing_system_message:
162+ sys_content += interleaved_text_media_as_str(
163+ existing_system_message.content, sep="\n"
164+ )
165+
166+ messages.append(SystemMessage(content=sys_content))
167+
168+ # Add back existing messages from the request
169+ messages += existing_messages
170+ return messages
deleted llama_stack/providers/utils/inference/prepare_messages.py +0 −84
@@ -1,84 +0,0 @@
1-# Copyright (c) Meta Platforms, Inc. and affiliates.
2-# All rights reserved.
3-#
4-# This source code is licensed under the terms described in the LICENSE file in
5-# the root directory of this source tree.
6-
7-from llama_models.llama3.api.datatypes import * # noqa: F403
8-from llama_stack.apis.inference import * # noqa: F403
9-from llama_models.llama3.prompt_templates import (
10- BuiltinToolGenerator,
11- FunctionTagCustomToolGenerator,
12- JsonCustomToolGenerator,
13- SystemDefaultGenerator,
14-)
15-
16-
17-def prepare_messages(request: ChatCompletionRequest) -> List[Message]:
18-
19- assert request.tool_choice == ToolChoice.auto, "Only `ToolChoice.auto` supported"
20-
21- existing_messages = request.messages
22- existing_system_message = None
23- if existing_messages[0].role == Role.system.value:
24- existing_system_message = existing_messages.pop(0)
25-
26- assert (
27- existing_messages[0].role != Role.system.value
28- ), "Should only have 1 system message"
29-
30- messages = []
31-
32- default_gen = SystemDefaultGenerator()
33- default_template = default_gen.gen()
34-
35- sys_content = ""
36-
37- tool_template = None
38- if request.tools:
39- tool_gen = BuiltinToolGenerator()
40- tool_template = tool_gen.gen(request.tools)
41-
42- sys_content += tool_template.render()
43- sys_content += "\n"
44-
45- sys_content += default_template.render()
46-
47- if existing_system_message:
48- # TODO: this fn is needed in many places
49- def _process(c):
50- if isinstance(c, str):
51- return c
52- else:
53- return "<media>"
54-
55- sys_content += "\n"
56-
57- if isinstance(existing_system_message.content, str):
58- sys_content += _process(existing_system_message.content)
59- elif isinstance(existing_system_message.content, list):
60- sys_content += "\n".join(
61- [_process(c) for c in existing_system_message.content]
62- )
63-
64- messages.append(SystemMessage(content=sys_content))
65-
66- has_custom_tools = any(isinstance(dfn.tool_name, str) for dfn in request.tools)
67- if has_custom_tools:
68- if request.tool_prompt_format == ToolPromptFormat.json:
69- tool_gen = JsonCustomToolGenerator()
70- elif request.tool_prompt_format == ToolPromptFormat.function_tag:
71- tool_gen = FunctionTagCustomToolGenerator()
72- else:
73- raise ValueError(
74- f"Non supported ToolPromptFormat {request.tool_prompt_format}"
75- )
76-
77- custom_tools = [t for t in request.tools if isinstance(t.tool_name, str)]
78- custom_template = tool_gen.gen(custom_tools)
79- messages.append(UserMessage(content=custom_template.render()))
80-
81- # Add back existing messages from the request
82- messages += existing_messages
83-
84- return messages
modified requirements.txt +1 −0
@@ -7,4 +7,5 @@
77 python-dotenv
88 pydantic
99 requests
10+rich
1011 termcolor
added tests/test_augment_messages.py +126 −0
@@ -0,0 +1,126 @@
1+# Copyright (c) Meta Platforms, Inc. and affiliates.
2+# All rights reserved.
3+#
4+# This source code is licensed under the terms described in the LICENSE file in
5+# the root directory of this source tree.
6+
7+import unittest
8+
9+from llama_models.llama3.api import * # noqa: F403
10+from llama_stack.inference.api import * # noqa: F403
11+from llama_stack.inference.augment_messages import augment_messages_for_tools
12+
13+MODEL = "Llama3.1-8B-Instruct"
14+
15+
16+class PrepareMessagesTests(unittest.IsolatedAsyncioTestCase):
17+ async def test_system_default(self):
18+ content = "Hello !"
19+ request = ChatCompletionRequest(
20+ model=MODEL,
21+ messages=[
22+ UserMessage(content=content),
23+ ],
24+ )
25+ messages = augment_messages_for_tools(request)
26+ self.assertEqual(len(messages), 2)
27+ self.assertEqual(messages[-1].content, content)
28+ self.assertTrue("Cutting Knowledge Date: December 2023" in messages[0].content)
29+
30+ async def test_system_builtin_only(self):
31+ content = "Hello !"
32+ request = ChatCompletionRequest(
33+ model=MODEL,
34+ messages=[
35+ UserMessage(content=content),
36+ ],
37+ tools=[
38+ ToolDefinition(tool_name=BuiltinTool.code_interpreter),
39+ ToolDefinition(tool_name=BuiltinTool.brave_search),
40+ ],
41+ )
42+ messages = augment_messages_for_tools(request)
43+ self.assertEqual(len(messages), 2)
44+ self.assertEqual(messages[-1].content, content)
45+ self.assertTrue("Cutting Knowledge Date: December 2023" in messages[0].content)
46+ self.assertTrue("Tools: brave_search" in messages[0].content)
47+
48+ async def test_system_custom_only(self):
49+ content = "Hello !"
50+ request = ChatCompletionRequest(
51+ model=MODEL,
52+ messages=[
53+ UserMessage(content=content),
54+ ],
55+ tools=[
56+ ToolDefinition(
57+ tool_name="custom1",
58+ description="custom1 tool",
59+ parameters={
60+ "param1": ToolParamDefinition(
61+ param_type="str",
62+ description="param1 description",
63+ required=True,
64+ ),
65+ },
66+ )
67+ ],
68+ tool_prompt_format=ToolPromptFormat.json,
69+ )
70+ messages = augment_messages_for_tools(request)
71+ self.assertEqual(len(messages), 3)
72+ self.assertTrue("Environment: ipython" in messages[0].content)
73+
74+ self.assertTrue("Return function calls in JSON format" in messages[1].content)
75+ self.assertEqual(messages[-1].content, content)
76+
77+ async def test_system_custom_and_builtin(self):
78+ content = "Hello !"
79+ request = ChatCompletionRequest(
80+ model=MODEL,
81+ messages=[
82+ UserMessage(content=content),
83+ ],
84+ tools=[
85+ ToolDefinition(tool_name=BuiltinTool.code_interpreter),
86+ ToolDefinition(tool_name=BuiltinTool.brave_search),
87+ ToolDefinition(
88+ tool_name="custom1",
89+ description="custom1 tool",
90+ parameters={
91+ "param1": ToolParamDefinition(
92+ param_type="str",
93+ description="param1 description",
94+ required=True,
95+ ),
96+ },
97+ ),
98+ ],
99+ )
100+ messages = augment_messages_for_tools(request)
101+ self.assertEqual(len(messages), 3)
102+
103+ self.assertTrue("Environment: ipython" in messages[0].content)
104+ self.assertTrue("Tools: brave_search" in messages[0].content)
105+
106+ self.assertTrue("Return function calls in JSON format" in messages[1].content)
107+ self.assertEqual(messages[-1].content, content)
108+
109+ async def test_user_provided_system_message(self):
110+ content = "Hello !"
111+ system_prompt = "You are a pirate"
112+ request = ChatCompletionRequest(
113+ model=MODEL,
114+ messages=[
115+ SystemMessage(content=system_prompt),
116+ UserMessage(content=content),
117+ ],
118+ tools=[
119+ ToolDefinition(tool_name=BuiltinTool.code_interpreter),
120+ ],
121+ )
122+ messages = augment_messages_for_tools(request)
123+ self.assertEqual(len(messages), 2, messages)
124+ self.assertTrue(messages[0].content.endswith(system_prompt))
125+
126+ self.assertEqual(messages[-1].content, content)
modified tests/test_e2e.py +1 −1
@@ -59,7 +59,7 @@
5959 host=TestE2E.HOST,
6060 port=TestE2E.PORT,
6161 custom_tools=custom_tools,
62- # model="Meta-Llama3.1-70B-Instruct", # Defaults to 8B
62+ # model="Llama3.1-70B-Instruct", # Defaults to 8B
6363 tool_prompt_format=tool_prompt_format,
6464 )
6565 await client.create_session(__file__)
modified tests/test_inference.py +5 −23
@@ -9,31 +9,15 @@
99
1010 import asyncio
1111 import os
12-import textwrap
1312 import unittest
1413
15-from datetime import datetime
16-
17-from llama_models.llama3.api.datatypes import (
18- BuiltinTool,
19- StopReason,
20- SystemMessage,
21- ToolDefinition,
22- ToolParamDefinition,
23- ToolPromptFormat,
24- ToolResponseMessage,
25- UserMessage,
26-)
27-
28-from llama_stack.inference.api import (
29- ChatCompletionRequest,
30- ChatCompletionResponseEventType,
31-)
14+from llama_models.llama3.api.datatypes import * # noqa: F403
15+from llama_stack.inference.api import * # noqa: F403
3216 from llama_stack.inference.meta_reference.config import MetaReferenceImplConfig
3317 from llama_stack.inference.meta_reference.inference import get_provider_impl
3418
3519
36-MODEL = "Meta-Llama3.1-8B-Instruct"
20+MODEL = "Llama3.1-8B-Instruct"
3721 HELPER_MSG = """
3822 This test needs llama-3.1-8b-instruct models.
3923 Please donwload using the llama cli
@@ -45,11 +29,10 @@
4529 class InferenceTests(unittest.IsolatedAsyncioTestCase):
4630 @classmethod
4731 def setUpClass(cls):
48- # This runs the async setup function
4932 asyncio.run(cls.asyncSetUpClass())
5033
5134 @classmethod
52- async def asyncSetUpClass(cls):
35+ async def asyncSetUpClass(cls): # noqa
5336 # assert model exists on local
5437 model_dir = os.path.expanduser(f"~/.llama/checkpoints/{MODEL}/original/")
5538 assert os.path.isdir(model_dir), HELPER_MSG
@@ -67,11 +50,10 @@
6750
6851 @classmethod
6952 def tearDownClass(cls):
70- # This runs the async teardown function
7153 asyncio.run(cls.asyncTearDownClass())
7254
7355 @classmethod
74- async def asyncTearDownClass(cls):
56+ async def asyncTearDownClass(cls): # noqa
7557 await cls.api.shutdown()
7658
7759 async def asyncSetUp(self):
modified tests/test_ollama_inference.py +5 −21
@@ -4,26 +4,10 @@
44 # This source code is licensed under the terms described in the LICENSE file in
55 # the root directory of this source tree.
66
7-import textwrap
87 import unittest
9-from datetime import datetime
10-
11-from llama_models.llama3.api.datatypes import (
12- BuiltinTool,
13- SamplingParams,
14- SamplingStrategy,
15- StopReason,
16- SystemMessage,
17- ToolDefinition,
18- ToolParamDefinition,
19- ToolPromptFormat,
20- ToolResponseMessage,
21- UserMessage,
22-)
23-from llama_stack.inference.api import (
24- ChatCompletionRequest,
25- ChatCompletionResponseEventType,
26-)
8+
9+from llama_models.llama3.api.datatypes import * # noqa: F403
10+from llama_stack.inference.api import * # noqa: F403
2711 from llama_stack.inference.ollama.config import OllamaImplConfig
2812 from llama_stack.inference.ollama.ollama import get_provider_impl
2913
@@ -52,7 +36,7 @@
5236 ),
5337 },
5438 )
55- self.valid_supported_model = "Meta-Llama3.1-8B-Instruct"
39+ self.valid_supported_model = "Llama3.1-8B-Instruct"
5640
5741 async def asyncTearDown(self):
5842 await self.api.shutdown()
@@ -272,7 +256,7 @@
272256 ollama_model = self.api.resolve_ollama_model(self.valid_supported_model)
273257 self.assertEqual(ollama_model, "llama3.1:8b-instruct-fp16")
274258
275- invalid_model = "Meta-Llama3.1-8B"
259+ invalid_model = "Llama3.1-8B"
276260 with self.assertRaisesRegex(
277261 AssertionError, f"Unsupported model: {invalid_model}"
278262 ):
deleted tests/test_prepare_messages.py +0 −126
@@ -1,126 +0,0 @@
1-# Copyright (c) Meta Platforms, Inc. and affiliates.
2-# All rights reserved.
3-#
4-# This source code is licensed under the terms described in the LICENSE file in
5-# the root directory of this source tree.
6-
7-import unittest
8-
9-from llama_models.llama3.api import * # noqa: F403
10-from llama_stack.inference.api import * # noqa: F403
11-from llama_stack.inference.prepare_messages import prepare_messages
12-
13-MODEL = "Meta-Llama3.1-8B-Instruct"
14-
15-
16-class PrepareMessagesTests(unittest.IsolatedAsyncioTestCase):
17- async def test_system_default(self):
18- content = "Hello !"
19- request = ChatCompletionRequest(
20- model=MODEL,
21- messages=[
22- UserMessage(content=content),
23- ],
24- )
25- messages = prepare_messages(request)
26- self.assertEqual(len(messages), 2)
27- self.assertEqual(messages[-1].content, content)
28- self.assertTrue("Cutting Knowledge Date: December 2023" in messages[0].content)
29-
30- async def test_system_builtin_only(self):
31- content = "Hello !"
32- request = ChatCompletionRequest(
33- model=MODEL,
34- messages=[
35- UserMessage(content=content),
36- ],
37- tools=[
38- ToolDefinition(tool_name=BuiltinTool.code_interpreter),
39- ToolDefinition(tool_name=BuiltinTool.brave_search),
40- ],
41- )
42- messages = prepare_messages(request)
43- self.assertEqual(len(messages), 2)
44- self.assertEqual(messages[-1].content, content)
45- self.assertTrue("Cutting Knowledge Date: December 2023" in messages[0].content)
46- self.assertTrue("Tools: brave_search" in messages[0].content)
47-
48- async def test_system_custom_only(self):
49- content = "Hello !"
50- request = ChatCompletionRequest(
51- model=MODEL,
52- messages=[
53- UserMessage(content=content),
54- ],
55- tools=[
56- ToolDefinition(
57- tool_name="custom1",
58- description="custom1 tool",
59- parameters={
60- "param1": ToolParamDefinition(
61- param_type="str",
62- description="param1 description",
63- required=True,
64- ),
65- },
66- )
67- ],
68- tool_prompt_format=ToolPromptFormat.json,
69- )
70- messages = prepare_messages(request)
71- self.assertEqual(len(messages), 3)
72- self.assertTrue("Environment: ipython" in messages[0].content)
73-
74- self.assertTrue("Return function calls in JSON format" in messages[1].content)
75- self.assertEqual(messages[-1].content, content)
76-
77- async def test_system_custom_and_builtin(self):
78- content = "Hello !"
79- request = ChatCompletionRequest(
80- model=MODEL,
81- messages=[
82- UserMessage(content=content),
83- ],
84- tools=[
85- ToolDefinition(tool_name=BuiltinTool.code_interpreter),
86- ToolDefinition(tool_name=BuiltinTool.brave_search),
87- ToolDefinition(
88- tool_name="custom1",
89- description="custom1 tool",
90- parameters={
91- "param1": ToolParamDefinition(
92- param_type="str",
93- description="param1 description",
94- required=True,
95- ),
96- },
97- ),
98- ],
99- )
100- messages = prepare_messages(request)
101- self.assertEqual(len(messages), 3)
102-
103- self.assertTrue("Environment: ipython" in messages[0].content)
104- self.assertTrue("Tools: brave_search" in messages[0].content)
105-
106- self.assertTrue("Return function calls in JSON format" in messages[1].content)
107- self.assertEqual(messages[-1].content, content)
108-
109- async def test_user_provided_system_message(self):
110- content = "Hello !"
111- system_prompt = "You are a pirate"
112- request = ChatCompletionRequest(
113- model=MODEL,
114- messages=[
115- SystemMessage(content=system_prompt),
116- UserMessage(content=content),
117- ],
118- tools=[
119- ToolDefinition(tool_name=BuiltinTool.code_interpreter),
120- ],
121- )
122- messages = prepare_messages(request)
123- self.assertEqual(len(messages), 2, messages)
124- self.assertTrue(messages[0].content.endswith(system_prompt))
125-
126- self.assertEqual(messages[-1].content, content)