provider_options.go

 1// Package openaicompat provides an implementation of the fantasy AI SDK for OpenAI-compatible APIs.
 2package openaicompat
 3
 4import (
 5	"encoding/json"
 6
 7	"charm.land/fantasy"
 8	"charm.land/fantasy/providers/openai"
 9)
10
11// Global type identifiers for OpenAI-compatible provider data.
12const (
13	TypeProviderOptions = Name + ".options"
14)
15
16// Register OpenAI-compatible provider-specific types with the global registry.
17func init() {
18	fantasy.RegisterProviderType(TypeProviderOptions, func(data []byte) (fantasy.ProviderOptionsData, error) {
19		var v ProviderOptions
20		if err := json.Unmarshal(data, &v); err != nil {
21			return nil, err
22		}
23		return &v, nil
24	})
25}
26
27// ProviderOptions represents additional options for the OpenAI-compatible provider.
28type ProviderOptions struct {
29	User            *string                 `json:"user"`
30	ReasoningEffort *openai.ReasoningEffort `json:"reasoning_effort"`
31}
32
33// ReasoningData represents reasoning data for OpenAI-compatible provider.
34// Some providers use "reasoning_content" (e.g. Avian), others use "reasoning" (e.g. Moonshot AI/Kimi).
35type ReasoningData struct {
36	ReasoningContent string `json:"reasoning_content"`
37	Reasoning        string `json:"reasoning"`
38}
39
40// GetReasoningContent returns the reasoning text from whichever field is populated.
41func (r ReasoningData) GetReasoningContent() string {
42	if r.ReasoningContent != "" {
43		return r.ReasoningContent
44	}
45	return r.Reasoning
46}
47
48// Options implements the ProviderOptions interface.
49func (*ProviderOptions) Options() {}
50
51// MarshalJSON implements custom JSON marshaling with type info for ProviderOptions.
52func (o ProviderOptions) MarshalJSON() ([]byte, error) {
53	type plain ProviderOptions
54	return fantasy.MarshalProviderType(TypeProviderOptions, plain(o))
55}
56
57// UnmarshalJSON implements custom JSON unmarshaling with type info for ProviderOptions.
58func (o *ProviderOptions) UnmarshalJSON(data []byte) error {
59	type plain ProviderOptions
60	var p plain
61	if err := fantasy.UnmarshalProviderType(data, &p); err != nil {
62		return err
63	}
64	*o = ProviderOptions(p)
65	return nil
66}
67
68// NewProviderOptions creates new provider options for the OpenAI-compatible provider.
69func NewProviderOptions(opts *ProviderOptions) fantasy.ProviderOptions {
70	return fantasy.ProviderOptions{
71		Name: opts,
72	}
73}
74
75// ParseOptions parses provider options from a map for OpenAI-compatible provider.
76func ParseOptions(data map[string]any) (*ProviderOptions, error) {
77	var options ProviderOptions
78	if err := fantasy.ParseOptions(data, &options); err != nil {
79		return nil, err
80	}
81	return &options, nil
82}