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 ExtraBody map[string]any `json:"extra_body,omitempty"`
32}
33
34// ReasoningData represents reasoning data for OpenAI-compatible provider.
35// Some providers use "reasoning_content" (e.g. Avian), others use "reasoning" (e.g. Moonshot AI/Kimi).
36type ReasoningData struct {
37 ReasoningContent string `json:"reasoning_content"`
38 Reasoning string `json:"reasoning"`
39}
40
41// GetReasoningContent returns the reasoning text from whichever field is populated.
42func (r ReasoningData) GetReasoningContent() string {
43 if r.ReasoningContent != "" {
44 return r.ReasoningContent
45 }
46 return r.Reasoning
47}
48
49// Options implements the ProviderOptions interface.
50func (*ProviderOptions) Options() {}
51
52// MarshalJSON implements custom JSON marshaling with type info for ProviderOptions.
53func (o ProviderOptions) MarshalJSON() ([]byte, error) {
54 type plain ProviderOptions
55 return fantasy.MarshalProviderType(TypeProviderOptions, plain(o))
56}
57
58// UnmarshalJSON implements custom JSON unmarshaling with type info for ProviderOptions.
59func (o *ProviderOptions) UnmarshalJSON(data []byte) error {
60 type plain ProviderOptions
61 var p plain
62 if err := fantasy.UnmarshalProviderType(data, &p); err != nil {
63 return err
64 }
65 *o = ProviderOptions(p)
66 return nil
67}
68
69// NewProviderOptions creates new provider options for the OpenAI-compatible provider.
70func NewProviderOptions(opts *ProviderOptions) fantasy.ProviderOptions {
71 return fantasy.ProviderOptions{
72 Name: opts,
73 }
74}
75
76// ParseOptions parses provider options from a map for OpenAI-compatible provider.
77func ParseOptions(data map[string]any) (*ProviderOptions, error) {
78 var options ProviderOptions
79 if err := fantasy.ParseOptions(data, &options); err != nil {
80 return nil, err
81 }
82 return &options, nil
83}