|
| 1 | +package main |
| 2 | + |
| 3 | +import ( |
| 4 | + "bufio" |
| 5 | + "context" |
| 6 | + "encoding/json" |
| 7 | + "fmt" |
| 8 | + "os" |
| 9 | + "strings" |
| 10 | + |
| 11 | + // Packages |
| 12 | + "github.com/djthorpe/go-tablewriter" |
| 13 | + "github.com/mutablelogic/go-client" |
| 14 | + "github.com/mutablelogic/go-client/pkg/anthropic" |
| 15 | + "github.com/mutablelogic/go-client/pkg/newsapi" |
| 16 | + "github.com/mutablelogic/go-client/pkg/openai/schema" |
| 17 | +) |
| 18 | + |
| 19 | +/////////////////////////////////////////////////////////////////////////////// |
| 20 | +// GLOBALS |
| 21 | + |
| 22 | +var ( |
| 23 | + samName = "sam" |
| 24 | + samWeatherTool = schema.NewTool("get_weather", "Get the weather for a location") |
| 25 | + samNewsHeadlinesTool = schema.NewTool("get_news_headlines", "Get the news headlines") |
| 26 | + samNewsSearchTool = schema.NewTool("search_news", "Search news articles") |
| 27 | + samSystemPrompt = `Your name is Samantha, you are a friendly AI assistant, here to help you with |
| 28 | + anything you need. Your responses should be short and to the point, and you should always be polite.` |
| 29 | +) |
| 30 | + |
| 31 | +/////////////////////////////////////////////////////////////////////////////// |
| 32 | +// LIFECYCLE |
| 33 | + |
| 34 | +func samRegister(flags *Flags) { |
| 35 | + flags.Register(Cmd{ |
| 36 | + Name: samName, |
| 37 | + Description: "Interact with Samantha, a friendly AI assistant, to query news and weather", |
| 38 | + Parse: samParse, |
| 39 | + Fn: []Fn{ |
| 40 | + {Name: "chat", Call: samChat, Description: "Chat with Sam"}, |
| 41 | + }, |
| 42 | + }) |
| 43 | +} |
| 44 | + |
| 45 | +func samParse(flags *Flags, opts ...client.ClientOpt) error { |
| 46 | + // Initialize weather |
| 47 | + if err := weatherapiParse(flags, opts...); err != nil { |
| 48 | + return err |
| 49 | + } |
| 50 | + // Initialize news |
| 51 | + if err := newsapiParse(flags, opts...); err != nil { |
| 52 | + return err |
| 53 | + } |
| 54 | + |
| 55 | + // Initialize anthropic |
| 56 | + opts = append(opts, client.OptHeader("Anthropic-Beta", "tools-2024-04-04")) |
| 57 | + if err := anthropicParse(flags, opts...); err != nil { |
| 58 | + return err |
| 59 | + } |
| 60 | + |
| 61 | + // Add tool parameters |
| 62 | + if err := samWeatherTool.AddParameter("location", "The city to get the weather for", true); err != nil { |
| 63 | + return err |
| 64 | + } |
| 65 | + if err := samNewsHeadlinesTool.AddParameter("category", "The cateogry of news, which should be one of business, entertainment, general, health, science, sports or technology", true); err != nil { |
| 66 | + return err |
| 67 | + } |
| 68 | + if err := samNewsSearchTool.AddParameter("query", "The query with which to search news", true); err != nil { |
| 69 | + return err |
| 70 | + } |
| 71 | + |
| 72 | + // Return success |
| 73 | + return nil |
| 74 | +} |
| 75 | + |
| 76 | +/////////////////////////////////////////////////////////////////////////////// |
| 77 | +// METHODS |
| 78 | + |
| 79 | +func samChat(ctx context.Context, w *tablewriter.Writer, _ []string) error { |
| 80 | + var toolResult bool |
| 81 | + |
| 82 | + messages := []*schema.Message{} |
| 83 | + for { |
| 84 | + if ctx.Err() != nil { |
| 85 | + return nil |
| 86 | + } |
| 87 | + |
| 88 | + // Read if there hasn't been any tool results yet |
| 89 | + if !toolResult { |
| 90 | + reader := bufio.NewReader(os.Stdin) |
| 91 | + fmt.Print("Chat: ") |
| 92 | + text, err := reader.ReadString('\n') |
| 93 | + if err != nil { |
| 94 | + return err |
| 95 | + } |
| 96 | + messages = append(messages, schema.NewMessage("user", schema.Text(strings.TrimSpace(text)))) |
| 97 | + } |
| 98 | + |
| 99 | + // Curtail requests to the last N history |
| 100 | + if len(messages) > 10 { |
| 101 | + messages = messages[len(messages)-10:] |
| 102 | + // First message must have role 'user' |
| 103 | + for { |
| 104 | + if len(messages) == 0 || messages[0].Role == "user" { |
| 105 | + break |
| 106 | + } |
| 107 | + messages = messages[1:] |
| 108 | + } |
| 109 | + // TODO: We must remove the first instance tool_result if there is no tool_use |
| 110 | + } |
| 111 | + |
| 112 | + // Request -> Response |
| 113 | + responses, err := anthropicClient.Messages(ctx, messages, anthropic.OptSystem(samSystemPrompt), anthropic.OptTool(samWeatherTool), anthropic.OptTool(samNewsHeadlinesTool), anthropic.OptTool(samNewsSearchTool)) |
| 114 | + if err != nil { |
| 115 | + return err |
| 116 | + } |
| 117 | + toolResult = false |
| 118 | + |
| 119 | + for _, response := range responses { |
| 120 | + switch response.Type { |
| 121 | + case "text": |
| 122 | + messages = samAppend(messages, schema.NewMessage("assistant", schema.Text(response.Text))) |
| 123 | + fmt.Println(response.Text) |
| 124 | + fmt.Println("") |
| 125 | + case "tool_use": |
| 126 | + messages = samAppend(messages, schema.NewMessage("assistant", response)) |
| 127 | + result := samCall(ctx, response) |
| 128 | + messages = samAppend(messages, schema.NewMessage("user", result)) |
| 129 | + toolResult = true |
| 130 | + } |
| 131 | + } |
| 132 | + } |
| 133 | +} |
| 134 | + |
| 135 | +func samCall(_ context.Context, content schema.Content) *schema.Content { |
| 136 | + if content.Type != "tool_use" { |
| 137 | + return schema.ToolResult(content.Id, fmt.Sprint("unexpected content type:", content.Type)) |
| 138 | + } |
| 139 | + switch content.Name { |
| 140 | + case samWeatherTool.Name: |
| 141 | + var location string |
| 142 | + if v, exists := content.GetString(content.Name, "location"); exists { |
| 143 | + location = v |
| 144 | + } else { |
| 145 | + location = "auto:ip" |
| 146 | + } |
| 147 | + if weather, err := weatherapiClient.Current(location); err != nil { |
| 148 | + return schema.ToolResult(content.Id, fmt.Sprint("Unable to get the current weather, the error is ", err)) |
| 149 | + } else if data, err := json.MarshalIndent(weather, "", " "); err != nil { |
| 150 | + return schema.ToolResult(content.Id, fmt.Sprint("Unable to marshal the weather data, the error is ", err)) |
| 151 | + } else { |
| 152 | + return schema.ToolResult(content.Id, string(data)) |
| 153 | + } |
| 154 | + case samNewsHeadlinesTool.Name: |
| 155 | + var category string |
| 156 | + if v, exists := content.GetString(content.Name, "category"); exists { |
| 157 | + category = v |
| 158 | + } else { |
| 159 | + category = "general" |
| 160 | + } |
| 161 | + if headlines, err := newsapiClient.Headlines(newsapi.OptCategory(category)); err != nil { |
| 162 | + return schema.ToolResult(content.Id, fmt.Sprint("Unable to get the news headlines, the error is ", err)) |
| 163 | + } else if data, err := json.MarshalIndent(headlines, "", " "); err != nil { |
| 164 | + return schema.ToolResult(content.Id, fmt.Sprint("Unable to marshal the headlines data, the error is ", err)) |
| 165 | + } else { |
| 166 | + return schema.ToolResult(content.Id, string(data)) |
| 167 | + } |
| 168 | + case samNewsSearchTool.Name: |
| 169 | + var query string |
| 170 | + if v, exists := content.GetString(content.Name, "query"); exists { |
| 171 | + query = v |
| 172 | + } else { |
| 173 | + return schema.ToolResult(content.Id, "Unable to search news due to missing query") |
| 174 | + } |
| 175 | + if articles, err := newsapiClient.Articles(newsapi.OptQuery(query), newsapi.OptLimit(5)); err != nil { |
| 176 | + return schema.ToolResult(content.Id, fmt.Sprint("Unable to search news, the error is ", err)) |
| 177 | + } else if data, err := json.MarshalIndent(articles, "", " "); err != nil { |
| 178 | + return schema.ToolResult(content.Id, fmt.Sprint("Unable to marshal the articles data, the error is ", err)) |
| 179 | + } else { |
| 180 | + return schema.ToolResult(content.Id, string(data)) |
| 181 | + } |
| 182 | + } |
| 183 | + return schema.ToolResult(content.Id, fmt.Sprint("unable to call:", content.Name)) |
| 184 | +} |
| 185 | + |
| 186 | +func samAppend(messages []*schema.Message, message *schema.Message) []*schema.Message { |
| 187 | + // if the previous message was of the same role, then append the new message to the previous one |
| 188 | + if len(messages) > 0 && messages[len(messages)-1].Role == message.Role { |
| 189 | + messages[len(messages)-1].Add(message.Content) |
| 190 | + return messages |
| 191 | + } else { |
| 192 | + return append(messages, message) |
| 193 | + } |
| 194 | +} |
0 commit comments