34 lines
967 B
Go
34 lines
967 B
Go
package gollama
|
|
|
|
import (
|
|
"context"
|
|
"encoding/json"
|
|
"fmt"
|
|
)
|
|
|
|
// CompleteJSON requests JSON output and unmarshals it into v.
|
|
func (c *Client) CompleteJSON(ctx context.Context, prompt string, v any, opts ...CallOption) error {
|
|
opts = append([]CallOption{WithFormatJSON()}, opts...)
|
|
result, err := c.Complete(ctx, prompt, opts...)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if err := json.Unmarshal([]byte(result.Text), v); err != nil {
|
|
return fmt.Errorf("unmarshal JSON response: %w", err)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// ChatJSON sends messages with JSON format and unmarshals the response into v.
|
|
func (c *Client) ChatJSON(ctx context.Context, messages []Message, v any, opts ...CallOption) error {
|
|
opts = append([]CallOption{WithFormatJSON()}, opts...)
|
|
result, err := c.ChatMessages(ctx, messages, opts...)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if err := json.Unmarshal([]byte(result.Text), v); err != nil {
|
|
return fmt.Errorf("unmarshal JSON response: %w", err)
|
|
}
|
|
return nil
|
|
}
|