-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
145 lines (120 loc) · 4.42 KB
/
Copy pathmain.go
File metadata and controls
145 lines (120 loc) · 4.42 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
package main
import (
"context"
"encoding/json"
"fmt"
"log"
"github.com/anthropics/anthropic-sdk-go"
)
// Person represents a structured person record extracted from unstructured text.
type Person struct {
Name string `json:"name"`
Age int `json:"age"`
Occupation string `json:"occupation"`
Summary string `json:"summary"`
}
// MovieReview represents a structured movie review extracted from unstructured text.
type MovieReview struct {
Title string `json:"title"`
Rating int `json:"rating"`
Sentiment string `json:"sentiment"`
Pros []string `json:"pros"`
Cons []string `json:"cons"`
}
const extractionSystemPrompt = "You are a data extraction assistant. Always respond with valid JSON only, no markdown, no explanation. Match the exact schema requested."
func extractText(ctx context.Context, client *anthropic.Client, userPrompt string) (string, error) {
msg, err := client.Messages.New(ctx, anthropic.MessageNewParams{
Model: anthropic.ModelClaudeOpus4_7,
MaxTokens: 1024,
System: []anthropic.TextBlockParam{
{Text: extractionSystemPrompt},
},
Messages: []anthropic.MessageParam{
anthropic.NewUserMessage(anthropic.NewTextBlock(userPrompt)),
},
})
if err != nil {
return "", fmt.Errorf("API call failed: %w", err)
}
for _, block := range msg.Content {
switch v := block.AsAny().(type) {
case anthropic.TextBlock:
return v.Text, nil
}
}
return "", fmt.Errorf("no text block found in response")
}
func extractPerson(ctx context.Context, client *anthropic.Client) error {
blurb := `Meet Dr. Sarah Chen, a 38-year-old neuroscientist at the Karolinska Institute in Stockholm.
She has spent the last decade mapping the neural correlates of memory consolidation during sleep.
Originally from Vancouver, Canada, Sarah completed her PhD at MIT before moving to Sweden.
Her colleagues describe her as meticulous, collaborative, and endlessly curious about the brain.`
prompt := fmt.Sprintf(`Extract the person's details from the following text and return a JSON object with these exact fields:
- name (string)
- age (integer)
- occupation (string)
- summary (string, one or two sentences)
Text:
%s`, blurb)
raw, err := extractText(ctx, client, prompt)
if err != nil {
return err
}
var person Person
if err := json.Unmarshal([]byte(raw), &person); err != nil {
return fmt.Errorf("failed to unmarshal person: %w\nraw response: %s", err, raw)
}
fmt.Println("=== Extracted Person ===")
fmt.Printf("Name: %s\n", person.Name)
fmt.Printf("Age: %d\n", person.Age)
fmt.Printf("Occupation: %s\n", person.Occupation)
fmt.Printf("Summary: %s\n\n", person.Summary)
return nil
}
func extractMovieReview(ctx context.Context, client *anthropic.Client) error {
blurb := `I just watched Dune: Part Two and honestly it blew me away. The cinematography is jaw-dropping,
Hans Zimmer's score is hypnotic, and Zendaya finally gets the screen time she deserved. Denis Villeneuve
proves once again that he's one of the best directors working today. My only gripes are that some of the
political subtext felt rushed in the third act, and a couple of minor characters were underwritten.
Still, I'd give it a 9 out of 10 — an absolute must-watch for sci-fi fans.`
prompt := fmt.Sprintf(`Extract the movie review details from the following text and return a JSON object with these exact fields:
- title (string)
- rating (integer, out of 10)
- sentiment (string: "positive", "negative", or "mixed")
- pros (array of strings)
- cons (array of strings)
Text:
%s`, blurb)
raw, err := extractText(ctx, client, prompt)
if err != nil {
return err
}
var review MovieReview
if err := json.Unmarshal([]byte(raw), &review); err != nil {
return fmt.Errorf("failed to unmarshal movie review: %w\nraw response: %s", err, raw)
}
fmt.Println("=== Extracted Movie Review ===")
fmt.Printf("Title: %s\n", review.Title)
fmt.Printf("Rating: %d/10\n", review.Rating)
fmt.Printf("Sentiment: %s\n", review.Sentiment)
fmt.Println("Pros:")
for _, pro := range review.Pros {
fmt.Printf(" + %s\n", pro)
}
fmt.Println("Cons:")
for _, con := range review.Cons {
fmt.Printf(" - %s\n", con)
}
fmt.Println()
return nil
}
func main() {
client := anthropic.NewClient()
ctx := context.Background()
if err := extractPerson(ctx, client); err != nil {
log.Fatalf("extractPerson: %v", err)
}
if err := extractMovieReview(ctx, client); err != nil {
log.Fatalf("extractMovieReview: %v", err)
}
}