Thanks to visit codestin.com
Credit goes to pkg.go.dev

sarufi

package module
v0.3.3 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Sep 22, 2023 License: MIT Imports: 9 Imported by: 2

README

Sarufi Golang SDK

Pre-requisites

You need to register with Sarufi in order to get your login credentials (client ID and client secret).

Installation

Simply install with the go get command:

go get github.com/sarufi-io/[email protected]

And import it to your package as:

package main

import (
    sarufi "github.com/sarufi-io/[email protected]"
)

Usage

I have divided the explanation into two parts;

  • Information relating to type Sarufi.Application and
  • Information relating to type Sarufi.Bot

Type Sarufi.Application

This type handles tasks that affect all bots such getting all bots, creating new bots and so on. Detailed explanation below.

Set Token

First create a new variable of type sarufi.Application and place your API KEY as shown below. You can get your API key from your Sarufi Dashboard

var app sarufi.Application

app.GetToken("your_api_key")

Creating a New Bot

Use the app.CreateBot method to create a new bot. You'll fill in the;

  • name of your bot
  • its description
  • industry and
  • a boolean on whether the bot should be visible on the playground.

The method will return a new bot of type Bot and an error if any. See below:

example_bot, err := app.CreateBot("Name of your bot", "Description", "Industry", bool)
if err != nil {
    log.Fatal(err)
}

fmt.Println(example_bot.Name)

Getting All Your Bots

To get all your bots, use the app.GetAllBots which will return a list of all available bots and an error if any:

myBots, err := app.GetAllBots()
if err != nil {
    log.Fatal(err)
}

for _, bot := range myBots {
    fmt.Println(bot.Name)
    fmt.Println(bot.Description)
}

Fetch A Single Bot

To fetch a particular bot, use the method app.GetBot filling in the ID of the bot you want. It will return the requested bot and an error if any:

example_bot, err := app.GetBot(bot_id)

if err != nil {
    log.Fatal(err)
}

fmt.Println(example_bot.Name)

Updating A Bot

To update information of a specific bot, use the app.UpdateBot placing the bot itself as a parameter. It will return an error if any:

example_bot.Name = "New Name"

if err := app.UpdateBot(example_bot); err != nil {
    log.Fatal(err)
}

Delete A Bot

To delete a bot, use the app.DeleteBot method filling in the ID of the bot as a parameter. It will return an error if any:

if err := app.DeleteBot(bot_id); err != nil {
    log.Fatal(err)
}

Get Profile

To get information about your user account use the app.GetUser method. The details of the user account will also be stored in the app.User field:

profile, err := app.GetUser()
if err != nil {
    log.Fatal(err)
}

fmt.Println(profile.ID)
fmt.Println(profile.FullName)

Type Sarufi.Bot

This is the actual Bot. Below are explanations on all methods that affect a specific bot such as creating new intents, flows and so on.

NOTE: For any changes to take effect, you MUST call the app.Update method with the bot as a parameter, otherwise changes will not take effect.

Creating A New Intent

You can create a new Intent with the bot.CreateIntents method. Note that this WILL delete any existing intents.

// Create a string in JSON format
intents := `
{
    "goodbye": ["bye", "goodbye", "see ya"],
    "greets": ["hey", "hello", "hi"],
    "order_pizza": ["I need pizza", "I want pizza"]
}`

if err := example_bot.CreateIntents(intents); err != nil {
    log.Fatal(err)
}

// For changes to take effect
if err = app.UpdateBot(example_bot); err != nil {
    log.Fatal(err)
}
  • You can also create a new Intent with a JSON file. Just pass in the file name as a parameter:
example_bot.CreateIntents("intentFile.json")

Adding An Intent

You can add a new Intent to the ones already available as follows:

// Create a title of the new intent
title := "example_title"

// Create a slice of strings with intent messages
newIntent := []string{"example intent content"}

// I am ignoring errors but you should handle them 
example_bot.AddIntent(title, newIntent)
app.UpdateBot(example_bot)

Note that this WILL NOT delete previous Intents. It will simple add itself to them.

Deleting An Intent

You can delete a specific Intent as follow:

// I am ignoring errors but you should handle them 
example_bot.DeleteIntent("intent_title")
app.UpdateBot(example_bot)

Creating A New Flow

You can create a new Flow as follows, note that this WILL delete any existing flows:

// create a string in JSON format
newFlow := `
{
     "greets": {"message": ["Hi, How can I help you?"], "next_state": "end"},
     "order_pizza": {
     "message": ["Sure, How many pizzas would you like to order?"],
     "next_state": "number_of_pizzas"
 },
     "number_of_pizzas": {
     "message": [
         "Sure, What would you like to have on your pizza?",
         "1. Cheese",
         "2. Pepperoni",
         "3. Both"
     ],
     "next_state": "choice_pizza_toppings"
 },
     "choice_pizza_toppings": {
     "1": "pizza_toppings",
     "2": "pizza_toppings",
     "3": "pizza_toppings",
     "fallback_message": ["Sorry, the topping you chose is not available."]
 },
     "pizza_toppings": {
     "message": ["Cool, Whats your address ?"],
     "next_state": "address"
 },
     "address": {
     "message": ["Sure, What is your phone number ?"],
     "next_state": "phone_number"
 },
     "phone_number": {
     "message": ["Your order has been placed.", "Thank you for ordering with us."],
     "next_state": "end"
 },
     "goodbye": {"message": ["Bye", "See you soon"], "next_state": "end"}
}`

// I am ignoring errors but you should handle them 
example_bot.CreateFlows(newFlow)
app.UpdateBot(example_bot)
  • You can also create a new Flow with a JSON file as shown below:
example_bot.CreateFlows("flowFile.json")

Adding A Flow

Add a new Flow to the already existing ones as follows:

// Create a title string
title := "flow_title"
content := `{"message": ["Your order has been placed.", "Thank you for ordering with us."],"next_state": "end"}`

// I am ignoring errors but you should handle them 
example_bot.AddFlow(title, content)
app.UpdateBot(example_bot)

Note that this will NOT delete previous Flows. It will simple add itself to them.

Deleting A Flow

You can delete a specific Flow as follow:

// I am ignoring errors but you should handle them 
example_bot.DeleteFlow("flow_title")
app.UpdateBot(example_bot)

Respond To A Message

Use the bot.Respond method to get a bot's respond to a particular message. The response will be stored at bot.Conversation which has the fields message, memory, current and next states.

if err = example_bot.Respond("Hey", "general"); err != nil {
    log.Fatal(err)
}

fmt.Println(example_bot.Conversation.Message)

Check Chat State

You can check the current and next state of the chat using the bot.ChatState method. The states are stored at the bot.Conversation field.

if err := example_bot.ChatState(); err != nil {
    log.Fatal(err)
}

fmt.Println(example_bot.Conversation.CurrentState)

Get Chat History

You can fetch the history of a specific chat ID using the bot.GetChatHistory method passing in the chat ID as a parameter. The history will be saved in the bot.ConversationHistory field.

if err := example_bot.GetChatHistory("chat_id"); err != nil {
    log.Fatal(err)
}

for _, chat := range example_bot.ConversationHistory {
	fmt.Printf("id: %d\nmessage: %s\nsender: %s\nresponse: %v\nreceived time: %s\n\n", chat.ID, chat.Message, chat.Sender, chat.Response, chat.ReceivedTime)
}

Get Chat Users

To get a list of all users communicating with your bot, use the bot.GetChatUsers method. The list of chats information will be stored in the bot.ChatUsers field.

if err := example_bot.GetChatUsers(); err != nil {
    log.Fatal(err)
}

for _, chat := range example_bot.ChatUsers {
    fmt.Println(chat.ChatID)
    fmt.Println(chat.ReceivedTime)
}

Predict A Message

To get a prediction of a particular message on your bot, use the bot.Predict method with the message as a parameter. The result of the prediction will be stored in the bot.Prediction field.

if err := example_bot.Predict("Hey"); err != nil {
    log.Fatal(err)
}

fmt.Println(example_bot.Prediction.Confidence)

Additional Resources

Issues

Open new issues if any.

Thanks

Author

This package is authored and maintained by Avicenna

Documentation

Overview

Golang SDK for Sarufi Conversational AI Platform

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Actions added in v0.3.3

type Actions struct {
	ResponseMessage []any `json:"send_message"`
}

type Application added in v0.2.0

type Application struct {
	User User `json:"user"`
}

Application will hold all application methods. It also has details about the user

func (*Application) CreateBot added in v0.2.0

func (app *Application) CreateBot(name, description, industry string, visible bool) (*Bot, error)

CreateBot method to create a new bot. It accepts the following parameters: Name (type string) - which is the name of the bot Description (type string)- which is the description of the bot Industry (type string) - which is the related industry of the bot Visible (type bool) - allow it to be publicly available It returns a pointer to a new Bot and an error

func (*Application) DeleteBot added in v0.2.0

func (app *Application) DeleteBot(id int) error

DeleteBot() will delete the bot of with provided ID. It will return an error if deletion was unsuccessful

func (*Application) GetAllBots added in v0.2.0

func (app *Application) GetAllBots() ([]Bot, error)

GetBots() method returns a list of type Bot and an error

func (*Application) GetBot added in v0.2.0

func (app *Application) GetBot(id int) (*Bot, error)

GetBot() method to get a specific bot. It accepts the bot id (type int) as a parameter. Returns a pointer of type Bot and an error.

func (*Application) GetUser added in v0.2.0

func (app *Application) GetUser() (*User, error)

Get user's information

func (*Application) SetToken added in v0.3.0

func (app *Application) SetToken(apiKey string)

GetToken() method to generate a token for the user. The received token will be saved to Application.Token otherwise it will return an error.

func (*Application) UpdateBot added in v0.2.0

func (app *Application) UpdateBot(bot *Bot) error

UpdateBot() method to update the bot. It accepts a parameter of type *Bot and will return an error if any

type Bot

type Bot struct {
	Id                        int                    `json:"id"`
	Name                      string                 `json:"name"`
	Industry                  string                 `json:"industry"`
	Description               string                 `json:"description"`
	UserID                    int                    `json:"user_id"`
	VisibleOnCommunity        bool                   `json:"visible_on_community"`
	Intents                   map[string][]string    `json:"intents"`
	Flows                     map[string]interface{} `json:"flows"`
	ModelName                 string                 `json:"model_name"`
	WebhookURL                string                 `json:"webhook_url"`
	WebhookTriggerIntents     []string               `json:"webhook_trigger_intents"`
	EvaluationMetrics         interface{}            `json:"evaluation_metrics"`
	ChatID                    string                 `json:"chat_id"`
	Conversation              Conversation
	ConversationWithKnowledge ConversationWithKnowledge
	Prediction                Prediction
	ChatUsers                 []ChatUser
	ConversationHistory       []ConversationHistory `json:"conversation_history"`
}

Type Bot. All the fields are matched to the API JSON response. You can read more here https://neurotech-africa.stoplight.io/docs/sarufi/a3135fbb09470-create-new-chatbot

func (*Bot) AddFlow

func (bot *Bot) AddFlow(node string, flow interface{}) error

AddFlow method to add a new flow. It accepts a string that will be the title of the flow and an interface. To allow ability to add choices, flow has been made an interface. See: https://docs.sarufi.io/docs/Getting%20started%20/chatbots-addons#handling-choices

func (*Bot) AddIntent

func (bot *Bot) AddIntent(title string, message []string) error

AddIntent method to add a new intent. It accepts a string that will be the title of the intent, and a slice of message strings that will be the intent content.

func (*Bot) ChatState

func (bot *Bot) ChatState() error

To get the current and next state of the chat. It accepts no parameters. It will display the JSON response from the API.

func (*Bot) CreateFlows

func (bot *Bot) CreateFlows(flows string) error

CreateFlows method to create a new flow. It accepts a string that contains the flows arranged in JSON format. It also acceps a json file (eg: flows.json)

func (*Bot) CreateIntents

func (bot *Bot) CreateIntents(intents string) error

CreateIntents method to create a new intent. It accepts a string that contains the intents arranged in JSON format. It also acceps a json file (eg: intents.json). It will return an error if any.

func (*Bot) DeleteFlow

func (bot *Bot) DeleteFlow(title string) error

DeleteFlow method to delete a specific flow. The accepted string is the title of the flow. If the title does not exist no error will be displayed.

func (*Bot) DeleteIntent

func (bot *Bot) DeleteIntent(title string) error

DeleteIntent method to delete a specific intent. The accepted string is the title of the intent. If the title does not exist no error will be displayed.

func (*Bot) GetChatHistory added in v0.2.0

func (bot *Bot) GetChatHistory(chatID string) error

Get conversation history of a particular ChatID. The result will be stored at the bot.ConversationHistory.

func (*Bot) GetChatUsers added in v0.2.0

func (bot *Bot) GetChatUsers() error

A method to get all users communicating with the bot. A list of chat users will be stored at bot.ChatUsers field.

func (*Bot) Predict added in v0.2.0

func (bot *Bot) Predict(message string) error

A method to predict the intent of a particular message. It will return an error if any. The result will be stored at the bot.Prediction field.

func (*Bot) Respond

func (bot *Bot) Respond(message, channel string) error

To get bot responses from the API. It accepts a message to responded to and a channel. The default channel is 'general' See: https://neurotech-africa.stoplight.io/docs/sarufi/4a3ab3e807c34-handle-conversation

type ChatUser added in v0.2.0

type ChatUser struct {
	ChatID       string `json:"chat_id"`
	ReceivedTime string `json:"received_time"`
}

ChatUser type to hold information about a chat

type ConflictError added in v0.2.0

type ConflictError struct {
	Detail Detail `json:"detail"`
}

func (*ConflictError) Error added in v0.2.0

func (c *ConflictError) Error() string

type Conversation added in v0.2.0

type Conversation struct {
	Message   []string `json:"message"`
	Memory    Memory   `json:"memory"`
	NextState string   `json:"next_state"`
}

Conversation will hold all conversation related data on none knowledge base bot

type ConversationHistory added in v0.2.0

type ConversationHistory struct {
	ID           int        `json:"id"`
	Message      string     `json:"message"`
	Sender       string     `json:"sender"`
	Response     []Response `json:"response"`
	ReceivedTime string     `json:"received_time"`
}

This type will hold information of the converstion of a particular chat ID

type ConversationWithKnowledge added in v0.3.3

type ConversationWithKnowledge struct {
	Message   []Actions `json:"actions"`
	Memory    Memory    `json:"memory"`
	NextState string    `json:"next_state"`
}

ConversationWithKnowledge will hold all conversation related data on knowledge base bot

type CustomTime added in v0.2.0

type CustomTime struct {
	time.Time
}

ToDo; Make custom way of parsing time

func (*CustomTime) UnmarshalJSON added in v0.2.0

func (m *CustomTime) UnmarshalJSON(data []byte) error

type Detail added in v0.2.0

type Detail struct {
	Loc     []string `json:"loc"`
	Message string   `json:"msg"`
	Type    string   `json:"type"`
}

type Memory added in v0.3.3

type Memory interface{}

type NotFoundError added in v0.2.0

type NotFoundError struct {
	Message string `json:"message"`
	Detail  string `json:"detail"`
}

func (*NotFoundError) Error added in v0.2.0

func (nf *NotFoundError) Error() string

type Prediction added in v0.2.0

type Prediction struct {
	Message    string  `json:"message"`
	Intent     string  `json:"intent"`
	Status     bool    `json:"status"`
	Confidence float64 `json:"confidence"`
}

Prediction will hold the response of a paritcular intent prediction

type Response added in v0.2.0

type Response struct {
	Message []string `json:"send_message"`
}

This type will be used in the conversation history

type Unauthorized added in v0.2.0

type Unauthorized struct {
	Message string `json:"message"`
	Detail  string `json:"detail"`
}

func (*Unauthorized) Error added in v0.2.0

func (ua *Unauthorized) Error() string

type UnprocessableEntity added in v0.2.0

type UnprocessableEntity struct {
	Detail []Detail `json:"detail"`
}

func (*UnprocessableEntity) Error added in v0.2.0

func (ue *UnprocessableEntity) Error() string

type User added in v0.2.0

type User struct {
	ID          int    `json:"id"`
	FullName    string `json:"full_name"`
	Username    string `json:"username"`
	Password    string `json:"password"`
	Mobile      string `json:"mobile"`
	IsAdmin     bool   `json:"is_admin"`
	DateCreated string `json:"date_created"`
	UpdatedAt   string `json:"updated_at"`
}

Directories

Path Synopsis

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL