ronantakizawa/codereview-bench huggingface dataset:
Repository: ollama/ollama
File: llm/ggml.go (Go)

Code before:
func (kv KV) BlockCount() uint64 {
	return kv.u64(fmt.Sprintf("%s.block_count", kv.Architecture()))
}

func (kv KV) HeadCount() uint64 {
	return kv.u64(fmt.Sprintf("%s.attention.head_count", kv.Architecture()))
}

func (kv KV) HeadCountKV() uint64 {
	if headCountKV := kv.u64(fmt.Sprintf("%s.attention.head_count_kv", kv.Architecture())); headCountKV > 0 {
		return headCountKV
	}

	return 1
}

func (kv KV) GQA() uint64 {
	return kv.HeadCount() / kv.HeadCountKV()
}

func (kv KV) EmbeddingLength() uint64 {
	return kv.u64(fmt.Sprintf("%s.embedding_length", kv.Architecture()))
}

func (kv KV) ContextLength() uint64 {
	return kv.u64(fmt.Sprintf("%s.context_length", kv.Architecture()))
}

func (kv KV) ChatTemplate() string {
	if tmpl, ok := kv["tokenizer.chat_template"].(string); ok {
		switch {
		case strings.Contains(tmpl, "
"):
			return "chatml"
		case strings.Contains(tmpl, "
"):
			// llama2-chat must appear before mistral
			return "llama2-chat"
		case strings.Contains(tmpl, "
"):
			return "llama3-instruct"
		case strings.Contains(tmpl, "
"):
			return "mistral-instruct"
		case strings.Contains(tmpl, "<start_of_turn>"):
			return "gemma-instruct"
		case strings.Contains(tmpl, "
"):
			return "phi-3"
		case strings.Contains(tmpl, "
"):
			return "zephyr"
		case strings.Contains(tmpl, "GPT4 Correct Assistant:"):
			return "openchat"
		case strings.Contains(tmpl, "### System:"):
			return "solar-instruct"
		case strings.Contains(tmpl, "### Instruction:\\n"):

Review comment (refactor):
Let's move this to a `template` package or similar to avoid increasing the surface area of `llm` which has quite a bit in it already. From there we can continue to tighten template handling

Code after:

func (kv KV) HeadCount() uint64 {
	return kv.u64(fmt.Sprintf("%s.attention.head_count", kv.Architecture()))
}

func (kv KV) HeadCountKV() uint64 {
	if headCountKV := kv.u64(fmt.Sprintf("%s.attention.head_count_kv", kv.Architecture())); headCountKV > 0 {
		return headCountKV
	}

	return 1
}

func (kv KV) GQA() uint64 {
	return kv.HeadCount() / kv.HeadCountKV()
}

func (kv KV) EmbeddingLength() uint64 {
	return kv.u64(fmt.Sprintf("%s.embedding_length", kv.Architecture()))
}

func (kv KV) ContextLength() uint64 {
	return kv.u64(fmt.Sprintf("%s.context_length", kv.Architecture()))
}

func (kv KV) ChatTemplate() string {
	s, _ := kv["tokenizer.chat_template"].(string)
	return s
}

type Tensors []*Tensor

func (ts Tensors) Layers() map[string]Layer {
	layers := make(map[string]Layer)
	for _, t := range ts {
		parts := strings.Split(t.Name, ".")
		if parts[0] == "blk" {
			// join first and second part, e.g. blk.%d
			parts = append([]string{fmt.Sprintf("%s.%s", parts[0], parts[1])}, parts[2:]...)
		}

		if _, ok := layers[parts[0]]; !ok {
			layers[parts[0]] = make(Layer)
		}

		layers[parts[0]][strings.Join(parts[1:], ".")] = t
	}

	return layers
}
Repository: ollama/ollama
File: envconfig/config.go (Go)

Code before:

	if nohistory := clean("OLLAMA_NOHISTORY"); nohistory != "" {
		NoHistory = true
	}

	if noprune := clean("OLLAMA_NOPRUNE"); noprune != "" {
		NoPrune = true
	}

	if origins := clean("OLLAMA_ORIGINS"); origins != "" {
		AllowOrigins = strings.Split(origins, ",")
	}
	for _, allowOrigin := range defaultAllowOrigins {
		AllowOrigins = append(AllowOrigins,
			fmt.Sprintf("http://%s", allowOrigin),
			fmt.Sprintf("https://%s", allowOrigin),
			fmt.Sprintf("http://%s", net.JoinHostPort(allowOrigin, "*")),
			fmt.Sprintf("https://%s", net.JoinHostPort(allowOrigin, "*")),
		)
	}

	additionalOrigins := []string{
		"app://*",
		"file://*",
		"chrome-extension://*",
	}

	AllowOrigins = append(AllowOrigins, additionalOrigins...)

	maxRunners := clean("OLLAMA_MAX_LOADED_MODELS")
	if maxRunners != "" {
		m, err := strconv.Atoi(maxRunners)
		if err != nil {
			slog.Error("invalid setting", "OLLAMA_MAX_LOADED_MODELS", maxRunners, "error", err)
		} else {
			MaxRunners = m
		}
	}

	if onp := os.Getenv("OLLAMA_MAX_QUEUE"); onp != "" {
		p, err := strconv.Atoi(onp)
		if err != nil || p <= 0 {
			slog.Error("invalid setting", "OLLAMA_MAX_QUEUE", onp, "error", err)
		} else {
			MaxQueuedRequests = p
		}
	}

	KeepAlive = clean("OLLAMA_KEEP_ALIVE")
}


Review comment (suggestion):
```suggestion
	additionalOrigins := []string{
		"app://*",
		"file://*",
		"chrome-extension://*",
		"tauri://",
	}
```

#2291 

Code after:

	if nohistory := clean("OLLAMA_NOHISTORY"); nohistory != "" {
		NoHistory = true
	}

	if noprune := clean("OLLAMA_NOPRUNE"); noprune != "" {
		NoPrune = true
	}

	if origins := clean("OLLAMA_ORIGINS"); origins != "" {
		AllowOrigins = strings.Split(origins, ",")
	}
	for _, allowOrigin := range defaultAllowOrigins {
		AllowOrigins = append(AllowOrigins,
			fmt.Sprintf("http://%s", allowOrigin),
			fmt.Sprintf("https://%s", allowOrigin),
			fmt.Sprintf("http://%s", net.JoinHostPort(allowOrigin, "*")),
			fmt.Sprintf("https://%s", net.JoinHostPort(allowOrigin, "*")),
		)
	}

	AllowOrigins = append(AllowOrigins,
		"app://*",
		"file://*",
		"tauri://*",
	)

	maxRunners := clean("OLLAMA_MAX_LOADED_MODELS")
	if maxRunners != "" {
		m, err := strconv.Atoi(maxRunners)
		if err != nil {
			slog.Error("invalid setting", "OLLAMA_MAX_LOADED_MODELS", maxRunners, "error", err)
		} else {
			MaxRunners = m
		}
	}

	if onp := os.Getenv("OLLAMA_MAX_QUEUE"); onp != "" {
		p, err := strconv.Atoi(onp)
		if err != nil || p <= 0 {
			slog.Error("invalid setting", "OLLAMA_MAX_QUEUE", onp, "error", err)
		} else {
			MaxQueuedRequests = p
		}
	}

	KeepAlive = clean("OLLAMA_KEEP_ALIVE")
}
Repository: ollama/ollama
File: envconfig/config.go (Go)

Code before:
		NoHistory = true
	}

	if noprune := clean("OLLAMA_NOPRUNE"); noprune != "" {
		NoPrune = true
	}

	if origins := clean("OLLAMA_ORIGINS"); origins != "" {
		AllowOrigins = strings.Split(origins, ",")
	}
	for _, allowOrigin := range defaultAllowOrigins {
		AllowOrigins = append(AllowOrigins,
			fmt.Sprintf("http://%s", allowOrigin),
			fmt.Sprintf("https://%s", allowOrigin),
			fmt.Sprintf("http://%s", net.JoinHostPort(allowOrigin, "*")),
			fmt.Sprintf("https://%s", net.JoinHostPort(allowOrigin, "*")),
		)
	}

	additionalOrigins := []string{
		"app://*",
		"file://*",
		"chrome-extension://*",
	}

	AllowOrigins = append(AllowOrigins, additionalOrigins...)

	maxRunners := clean("OLLAMA_MAX_LOADED_MODELS")
	if maxRunners != "" {
		m, err := strconv.Atoi(maxRunners)
		if err != nil {
			slog.Error("invalid setting", "OLLAMA_MAX_LOADED_MODELS", maxRunners, "error", err)
		} else {
			MaxRunners = m
		}
	}

	if onp := os.Getenv("OLLAMA_MAX_QUEUE"); onp != "" {
		p, err := strconv.Atoi(onp)
		if err != nil || p <= 0 {
			slog.Error("invalid setting", "OLLAMA_MAX_QUEUE", onp, "error", err)
		} else {
			MaxQueuedRequests = p
		}
	}

	KeepAlive = clean("OLLAMA_KEEP_ALIVE")
}


Review comment (suggestion):
Thoughts on appending directly to the AllowOrigins rather than creating the interim slice?

```
AllowOrigins = append(AllowOrigins, 
                "app://*",
		"file://*",
		"chrome-extension://*",
		"tauri://",
)
```

Code after:
		NoHistory = true
	}

	if noprune := clean("OLLAMA_NOPRUNE"); noprune != "" {
		NoPrune = true
	}

	if origins := clean("OLLAMA_ORIGINS"); origins != "" {
		AllowOrigins = strings.Split(origins, ",")
	}
	for _, allowOrigin := range defaultAllowOrigins {
		AllowOrigins = append(AllowOrigins,
			fmt.Sprintf("http://%s", allowOrigin),
			fmt.Sprintf("https://%s", allowOrigin),
			fmt.Sprintf("http://%s", net.JoinHostPort(allowOrigin, "*")),
			fmt.Sprintf("https://%s", net.JoinHostPort(allowOrigin, "*")),
		)
	}

	AllowOrigins = append(AllowOrigins,
		"app://*",
		"file://*",
		"tauri://*",
	)

	maxRunners := clean("OLLAMA_MAX_LOADED_MODELS")
	if maxRunners != "" {
		m, err := strconv.Atoi(maxRunners)
		if err != nil {
			slog.Error("invalid setting", "OLLAMA_MAX_LOADED_MODELS", maxRunners, "error", err)
		} else {
			MaxRunners = m
		}
	}

	if onp := os.Getenv("OLLAMA_MAX_QUEUE"); onp != "" {
		p, err := strconv.Atoi(onp)
		if err != nil || p <= 0 {
			slog.Error("invalid setting", "OLLAMA_MAX_QUEUE", onp, "error", err)
		} else {
			MaxQueuedRequests = p
		}
	}

	KeepAlive = clean("OLLAMA_KEEP_ALIVE")
}
Repository: ollama/ollama
File: server/routes.go (Go)

Code before:
	fmt.Fprintln(&sb, "# To build a new Modelfile based on this, replace FROM with:")
	fmt.Fprintf(&sb, "# FROM %s\n\n", model.ShortName)
	fmt.Fprint(&sb, model.String())
	resp.Modelfile = sb.String()

	ggmlData, err := getGGMLData(model)
	if err != nil {
		return nil, err
	}
	resp.ModelInfo = ggmlData

	return resp, nil
}

func getGGMLData(model *Model) ([]byte, error) {
	f, err := os.Open(model.ModelPath)
	if err != nil {
		return nil, err
	}

	ggml, _, err := llm.DecodeGGML(f)
	if err != nil {
		return nil, err
	}

	f.Close()

	kv := ggml.KV()

	for k := range kv {
		switch v := kv[k].(type) {
		case []interface{}:
			if len(v) > 5 {
				kv[k] = []string{}
			}
		}
	}

	kv["embedding_model"] = model.IsEmbedding()

	ggmlJson, err := json.Marshal(kv)
	if err != nil {
		return nil, err
	}

	return ggmlJson, nil
}

func (s *Server) ListModelsHandler(c *gin.Context) {
	ms, err := Manifests()
	if err != nil {

Review comment (suggestion):
The best way to close a file is to defer right after open succeeds, e.g.

```go
f, err := os.Open(p)
if err != nil {
  return nil, err
}
defer f.Close()
```

This ensure the file is closed even when the function returns early, e.g. DecodeGGML errors

Code after:
		default:
			params = append(params, fmt.Sprintf("%-*s %#v", cs, k, v))
		}
	}
	resp.Parameters = strings.Join(params, "\n")

	for k, v := range req.Options {
		if _, ok := req.Options[k]; ok {
			m.Options[k] = v
		}
	}

	var sb strings.Builder
	fmt.Fprintln(&sb, "# Modelfile generated by \"ollama show\"")
	fmt.Fprintln(&sb, "# To build a new Modelfile based on this, replace FROM with:")
	fmt.Fprintf(&sb, "# FROM %s\n\n", m.ShortName)
	fmt.Fprint(&sb, m.String())
	resp.Modelfile = sb.String()

	kvData, err := getKVData(m.ModelPath, req.Verbose)
	if err != nil {
		return nil, err
	}
	delete(kvData, "general.name")
	delete(kvData, "tokenizer.chat_template")
	resp.ModelInfo = kvData

	if len(m.ProjectorPaths) > 0 {
		projectorData, err := getKVData(m.ProjectorPaths[0], req.Verbose)
		if err != nil {
			return nil, err
		}
		resp.ProjectorInfo = projectorData
	}

	return resp, nil
}

func getKVData(digest string, verbose bool) (llm.KV, error) {
	kvData, err := llm.LoadModel(digest)
	if err != nil {
		return nil, err
	}

	kv := kvData.KV()

	if !verbose {
		for k := range kv {
			if t, ok := kv[k].([]any); len(t) > 5 && ok {
				kv[k] = []any{}
			}
Repository: ollama/ollama
File: server/routes.go (Go)

Code before:

func getGGMLData(model *Model) ([]byte, error) {
	f, err := os.Open(model.ModelPath)
	if err != nil {
		return nil, err
	}

	ggml, _, err := llm.DecodeGGML(f)
	if err != nil {
		return nil, err
	}

	f.Close()

	kv := ggml.KV()

	for k := range kv {
		switch v := kv[k].(type) {
		case []interface{}:
			if len(v) > 5 {
				kv[k] = []string{}
			}
		}
	}

	kv["embedding_model"] = model.IsEmbedding()

	ggmlJson, err := json.Marshal(kv)
	if err != nil {
		return nil, err
	}

	return ggmlJson, nil
}

func (s *Server) ListModelsHandler(c *gin.Context) {
	ms, err := Manifests()
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

	models := []api.ListModelResponse{}
	for n, m := range ms {
		f, err := m.Config.Open()
		if err != nil {
			slog.Warn("bad manifest filepath", "name", n, "error", err)
			continue
		}
		defer f.Close()


Review comment (suggestion):
I'm not sure about adding this as a KV since it's not part of the model itself. Ideally this can be captured as a top-level `capabilities`

Code after:
	fmt.Fprintln(&sb, "# Modelfile generated by \"ollama show\"")
	fmt.Fprintln(&sb, "# To build a new Modelfile based on this, replace FROM with:")
	fmt.Fprintf(&sb, "# FROM %s\n\n", m.ShortName)
	fmt.Fprint(&sb, m.String())
	resp.Modelfile = sb.String()

	kvData, err := getKVData(m.ModelPath, req.Verbose)
	if err != nil {
		return nil, err
	}
	delete(kvData, "general.name")
	delete(kvData, "tokenizer.chat_template")
	resp.ModelInfo = kvData

	if len(m.ProjectorPaths) > 0 {
		projectorData, err := getKVData(m.ProjectorPaths[0], req.Verbose)
		if err != nil {
			return nil, err
		}
		resp.ProjectorInfo = projectorData
	}

	return resp, nil
}

func getKVData(digest string, verbose bool) (llm.KV, error) {
	kvData, err := llm.LoadModel(digest)
	if err != nil {
		return nil, err
	}

	kv := kvData.KV()

	if !verbose {
		for k := range kv {
			if t, ok := kv[k].([]any); len(t) > 5 && ok {
				kv[k] = []any{}
			}
		}
	}

	return kv, nil
}

func (s *Server) ListModelsHandler(c *gin.Context) {
	ms, err := Manifests()
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}
Repository: ollama/ollama
File: server/routes.go (Go)

Code before:

	return resp, nil
}

func getGGMLData(model *Model) ([]byte, error) {
	f, err := os.Open(model.ModelPath)
	if err != nil {
		return nil, err
	}

	ggml, _, err := llm.DecodeGGML(f)
	if err != nil {
		return nil, err
	}

	f.Close()

	kv := ggml.KV()

	for k := range kv {
		switch v := kv[k].(type) {
		case []interface{}:
			if len(v) > 5 {
				kv[k] = []string{}
			}
		}
	}

	kv["embedding_model"] = model.IsEmbedding()

	ggmlJson, err := json.Marshal(kv)
	if err != nil {
		return nil, err
	}

	return ggmlJson, nil
}

func (s *Server) ListModelsHandler(c *gin.Context) {
	ms, err := Manifests()
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

	models := []api.ListModelResponse{}
	for n, m := range ms {
		f, err := m.Config.Open()
		if err != nil {
			slog.Warn("bad manifest filepath", "name", n, "error", err)
			continue

Review comment (suggestion):
I mentioned this in the other PR but showing an empty list is very confusing. Instead, this should show how many items are in the list. TBH this doesn't even need a length check, just always output the count

```go
if t, ok := kv[k].([]any); ok {
    kv[k] = fmt.Sprintf("(%d items)", len(t))
}
```

Code after:
	}

	var sb strings.Builder
	fmt.Fprintln(&sb, "# Modelfile generated by \"ollama show\"")
	fmt.Fprintln(&sb, "# To build a new Modelfile based on this, replace FROM with:")
	fmt.Fprintf(&sb, "# FROM %s\n\n", m.ShortName)
	fmt.Fprint(&sb, m.String())
	resp.Modelfile = sb.String()

	kvData, err := getKVData(m.ModelPath, req.Verbose)
	if err != nil {
		return nil, err
	}
	delete(kvData, "general.name")
	delete(kvData, "tokenizer.chat_template")
	resp.ModelInfo = kvData

	if len(m.ProjectorPaths) > 0 {
		projectorData, err := getKVData(m.ProjectorPaths[0], req.Verbose)
		if err != nil {
			return nil, err
		}
		resp.ProjectorInfo = projectorData
	}

	return resp, nil
}

func getKVData(digest string, verbose bool) (llm.KV, error) {
	kvData, err := llm.LoadModel(digest)
	if err != nil {
		return nil, err
	}

	kv := kvData.KV()

	if !verbose {
		for k := range kv {
			if t, ok := kv[k].([]any); len(t) > 5 && ok {
				kv[k] = []any{}
			}
		}
	}

	return kv, nil
}

func (s *Server) ListModelsHandler(c *gin.Context) {
	ms, err := Manifests()
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
Repository: ollama/ollama
File: cmd/cmd.go (Go)

Code before:
	if license {
		flagsSet++
		showType = "license"
	}

	if modelfile {
		flagsSet++
		showType = "modelfile"
	}

	if parameters {
		flagsSet++
		showType = "parameters"
	}

	if system {
		flagsSet++
		showType = "system"
	}

	if template {
		flagsSet++
		showType = "template"
	}

	switch flagsSet {
	case 0:
		req := api.ShowRequest{Name: args[0]}
		resp, err := client.Show(cmd.Context(), &req)
		if err != nil {
			return err
		}

		arch := resp.ModelInfo["general.architecture"].(string)

		modelData := [][]string{
			{"arch", arch},
			{"parameters", resp.Details.ParameterSize},
			{"quantization", resp.Details.QuantizationLevel},
			{"context length", fmt.Sprintf("%v", resp.ModelInfo[fmt.Sprintf("%s.context_length", arch)].(float64))},
			{"embedding length", fmt.Sprintf("%v", resp.ModelInfo[fmt.Sprintf("%s.embedding_length", arch)].(float64))},
		}

		mainTableData := [][]string{
			{"Model"},
			{renderSubTable(modelData, false)},
		}

		if slices.Contains(resp.Details.Families, "clip") {
			projectorData := [][]string{
				{"arch", "clip"},

Review comment (suggestion):
instead of a `switch` here, we can early return:

```
if len(flagsSet) > 1 {
  return errors.New("only one of '--license', '--modelfile', '--parameters', '--system', or '--template' can be specified")
}

if len(flagsSet) == 1 {
  ... do single flag stuff
  return nil
}

.. do default stuff
return nil


Code after:
		flagsSet++
		showType = "modelfile"
	}

	if parameters {
		flagsSet++
		showType = "parameters"
	}

	if system {
		flagsSet++
		showType = "system"
	}

	if template {
		flagsSet++
		showType = "template"
	}

	if flagsSet > 1 {
		return errors.New("only one of '--license', '--modelfile', '--parameters', '--system', or '--template' can be specified")
	}

	if flagsSet == 1 {
		req := api.ShowRequest{Name: args[0]}
		resp, err := client.Show(cmd.Context(), &req)
		if err != nil {
			return err
		}

		switch showType {
		case "license":
			fmt.Println(resp.License)
		case "modelfile":
			fmt.Println(resp.Modelfile)
		case "parameters":
			fmt.Println(resp.Parameters)
		case "system":
			fmt.Println(resp.System)
		case "template":
			fmt.Println(resp.Template)
		}

		return nil
	}

	req := api.ShowRequest{Name: args[0]}
	resp, err := client.Show(cmd.Context(), &req)
	if err != nil {
		return err
	}
Repository: ollama/ollama
File: cmd/cmd.go (Go)

Code before:
	return nil
}

func DeleteHandler(cmd *cobra.Command, args []string) error {
	client, err := api.ClientFromEnvironment()
	if err != nil {
		return err
	}

	for _, name := range args {
		req := api.DeleteRequest{Name: name}
		if err := client.Delete(cmd.Context(), &req); err != nil {
			return err
		}
		fmt.Printf("deleted '%s'\n", name)
	}
	return nil
}

func ShowHandler(cmd *cobra.Command, args []string) error {
	client, err := api.ClientFromEnvironment()
	if err != nil {
		return err
	}

	if len(args) == 0 {
		return errors.New("missing model name")
	} else if len(args) > 1 {
		return errors.New("only one model name can be specified")
	}

	license, errLicense := cmd.Flags().GetBool("license")
	modelfile, errModelfile := cmd.Flags().GetBool("modelfile")
	parameters, errParams := cmd.Flags().GetBool("parameters")
	system, errSystem := cmd.Flags().GetBool("system")
	template, errTemplate := cmd.Flags().GetBool("template")

	for _, boolErr := range []error{errLicense, errModelfile, errParams, errSystem, errTemplate} {
		if boolErr != nil {
			return errors.New("error retrieving flags")
		}
	}

	flagsSet := 0
	showType := ""

	if license {
		flagsSet++
		showType = "license"
	}


Review comment (refactor):
This is already handled by https://github.com/ollama/ollama/blob/main/cmd/cmd.go#L1119 so we can just remove this check

Code after:
	return nil
}

func DeleteHandler(cmd *cobra.Command, args []string) error {
	client, err := api.ClientFromEnvironment()
	if err != nil {
		return err
	}

	for _, name := range args {
		req := api.DeleteRequest{Name: name}
		if err := client.Delete(cmd.Context(), &req); err != nil {
			return err
		}
		fmt.Printf("deleted '%s'\n", name)
	}
	return nil
}

func ShowHandler(cmd *cobra.Command, args []string) error {
	client, err := api.ClientFromEnvironment()
	if err != nil {
		return err
	}

	license, errLicense := cmd.Flags().GetBool("license")
	modelfile, errModelfile := cmd.Flags().GetBool("modelfile")
	parameters, errParams := cmd.Flags().GetBool("parameters")
	system, errSystem := cmd.Flags().GetBool("system")
	template, errTemplate := cmd.Flags().GetBool("template")

	for _, boolErr := range []error{errLicense, errModelfile, errParams, errSystem, errTemplate} {
		if boolErr != nil {
			return errors.New("error retrieving flags")
		}
	}

	flagsSet := 0
	showType := ""

	if license {
		flagsSet++
		showType = "license"
	}

	if modelfile {
		flagsSet++
		showType = "modelfile"
	}

	if parameters {
Repository: ollama/ollama
File: server/routes.go (Go)

Code before:
	for k, v := range model.Options {
		switch val := v.(type) {
		case []interface{}:
			for _, nv := range val {
				params = append(params, fmt.Sprintf("%-*s %#v", cs, k, nv))
			}
		default:
			params = append(params, fmt.Sprintf("%-*s %#v", cs, k, v))
		}
	}
	resp.Parameters = strings.Join(params, "\n")

	for k, v := range req.Options {
		if _, ok := req.Options[k]; ok {
			model.Options[k] = v
		}
	}

	var sb strings.Builder
	fmt.Fprintln(&sb, "# Modelfile generated by \"ollama show\"")
	fmt.Fprintln(&sb, "# To build a new Modelfile based on this, replace FROM with:")
	fmt.Fprintf(&sb, "# FROM %s\n\n", model.ShortName)
	fmt.Fprint(&sb, model.String())
	resp.Modelfile = sb.String()

	ggmlData, err := getGGMLData(model.ModelPath, req.Verbose)
	if err != nil {
		return nil, err
	}
	delete(ggmlData, "tokenizer.chat_template")
	resp.ModelInfo = ggmlData

	if slices.Contains(resp.Details.Families, "clip") {
		projectorData, err := getGGMLData(model.ProjectorPaths[0], req.Verbose)
		if err != nil {
			return nil, err
		}
		resp.ProjectorInfo = projectorData
	}

	return resp, nil
}

func getGGMLData(digest string, verbose bool) (llm.KV, error) {
	f, err := os.Open(digest)
	if err != nil {
		return nil, err
	}

	defer f.Close()


Review comment (suggestion):
I believe you can use `llm.LoadModel`:

```
ggml, err := llm.LoadModel(pending.model.ModelPath)
kv := ggml.KV()
...

Code after:
		return nil, err
	}

	resp := &api.ShowResponse{
		License:    strings.Join(m.License, "\n"),
		System:     m.System,
		Template:   m.Template,
		Details:    modelDetails,
		Messages:   msgs,
		ModifiedAt: manifest.fi.ModTime(),
	}

	var params []string
	cs := 30
	for k, v := range m.Options {
		switch val := v.(type) {
		case []interface{}:
			for _, nv := range val {
				params = append(params, fmt.Sprintf("%-*s %#v", cs, k, nv))
			}
		default:
			params = append(params, fmt.Sprintf("%-*s %#v", cs, k, v))
		}
	}
	resp.Parameters = strings.Join(params, "\n")

	for k, v := range req.Options {
		if _, ok := req.Options[k]; ok {
			m.Options[k] = v
		}
	}

	var sb strings.Builder
	fmt.Fprintln(&sb, "# Modelfile generated by \"ollama show\"")
	fmt.Fprintln(&sb, "# To build a new Modelfile based on this, replace FROM with:")
	fmt.Fprintf(&sb, "# FROM %s\n\n", m.ShortName)
	fmt.Fprint(&sb, m.String())
	resp.Modelfile = sb.String()

	kvData, err := getKVData(m.ModelPath, req.Verbose)
	if err != nil {
		return nil, err
	}
	delete(kvData, "general.name")
	delete(kvData, "tokenizer.chat_template")
	resp.ModelInfo = kvData

	if len(m.ProjectorPaths) > 0 {
		projectorData, err := getKVData(m.ProjectorPaths[0], req.Verbose)
		if err != nil {
			return nil, err