| 1 |
package main |
| 2 |
|
| 3 |
import ( |
| 4 |
"context" |
| 5 |
"encoding/json" |
| 6 |
"fmt" |
| 7 |
|
| 8 |
"github.com/anthropics/anthropic-sdk-go" |
| 9 |
"github.com/invopop/jsonschema" |
| 10 |
) |
| 11 |
|
| 12 |
// Example struct with various field types and constraints |
| 13 |
type WeatherQuery struct { |
| 14 |
Location string `json:"location" jsonschema:"title=Location,description=The city and state e.g. San Francisco CA"` |
| 15 |
Units string `json:"units,omitempty" jsonschema:"enum=celsius,enum=fahrenheit,default=fahrenheit"` |
| 16 |
Days int `json:"days" jsonschema:"minimum=1,maximum=7,description=Number of days to forecast"` |
| 17 |
IncludeWind bool `json:"include_wind,omitempty"` |
| 18 |
Details []string `json:"details,omitempty" jsonschema:"minItems=1,maxItems=5"` |
| 19 |
} |
| 20 |
|
| 21 |
func main() { |
| 22 |
schemaMap := generateJSONSchema(&WeatherQuery{}) |
| 23 |
|
| 24 |
fmt.Println("schema generated by invopop/jsonschema:") |
| 25 |
printJSON(schemaMap) |
| 26 |
|
| 27 |
client := anthropic.NewClient() |
| 28 |
|
| 29 |
messages := []anthropic.BetaMessageParam{ |
| 30 |
anthropic.NewBetaUserMessage(anthropic.NewBetaTextBlock("What's the weather like in San Francisco for the next 3 days? Include wind information.")), |
| 31 |
} |
| 32 |
|
| 33 |
msg, err := client.Beta.Messages.New(context.TODO(), anthropic.BetaMessageNewParams{ |
| 34 |
Model: anthropic.Model("claude-sonnet-4-5"), |
| 35 |
MaxTokens: 1024, |
| 36 |
Messages: messages, |
| 37 |
OutputFormat: anthropic.BetaJSONSchemaOutputFormat(schemaMap), |
| 38 |
Betas: []anthropic.AnthropicBeta{"structured-outputs-2025-11-13"}, |
| 39 |
}) |
| 40 |
|
| 41 |
if err != nil { |
| 42 |
fmt.Printf("Error calling API: %v\n", err) |
| 43 |
return |
| 44 |
} |
| 45 |
|
| 46 |
fmt.Println("\nAPI Response:") |
| 47 |
for _, block := range msg.Content { |
| 48 |
switch v := block.AsAny().(type) { |
| 49 |
case anthropic.BetaTextBlock: |
| 50 |
fmt.Printf("Text: %s\n", v.Text) |
| 51 |
case anthropic.BetaToolUseBlock: |
| 52 |
fmt.Printf("Tool use: %s\n", v.Name) |
| 53 |
fmt.Printf("Input: %s\n", v.JSON.Input.Raw()) |
| 54 |
} |
| 55 |
} |
| 56 |
|
| 57 |
} |
| 58 |
|
| 59 |
func generateJSONSchema(t any) map[string]any { |
| 60 |
reflector := jsonschema.Reflector{ |
| 61 |
AllowAdditionalProperties: false, |
| 62 |
DoNotReference: true, |
| 63 |
} |
| 64 |
schema := reflector.Reflect(t) |
| 65 |
schemaBytes, err := json.Marshal(schema) |
| 66 |
if err != nil { |
| 67 |
panic(err) |
| 68 |
} |
| 69 |
var schemaMap map[string]any |
| 70 |
if err := json.Unmarshal(schemaBytes, &schemaMap); err != nil { |
| 71 |
panic(err) |
| 72 |
} |
| 73 |
return schemaMap |
| 74 |
|
| 75 |
} |
| 76 |
|
| 77 |
func printJSON(v any) { |
| 78 |
b, err := json.MarshalIndent(v, "", " ") |
| 79 |
if err != nil { |
| 80 |
fmt.Printf("Error: %v\n", err) |
| 81 |
return |
| 82 |
} |
| 83 |
fmt.Println(string(b)) |
| 84 |
} |