Skip to content

Commit

Permalink
✨ forward device demands to NLU
Browse files Browse the repository at this point in the history
  • Loading branch information
sylvain-reynaud committed Apr 24, 2023
1 parent 20091d4 commit 742b2b2
Show file tree
Hide file tree
Showing 5 changed files with 136 additions and 12 deletions.
19 changes: 15 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -26,8 +26,8 @@ Flow without NLU:
# Example values
export POLYXIA_GATEWAY_MORTY_API_ENDPOINT="http://localhost:8081"
export POLYXIA_GATEWAY_NLU_API_ENDPOINT="http://localhost:8082"
export POLYXIA_GATEWAY_MORTY_ADDR="localhost"
export POLYXIA_GATEWAY_MORTY_PORT="8080"
export POLYXIA_GATEWAY_ADDR="localhost"
export POLYXIA_GATEWAY_PORT="8080"
```

2. Run the API gateway with the following command:
Expand Down Expand Up @@ -56,7 +56,7 @@ make start

Follow the instructions here: https://github.com/polyxia-org/nlu/

### Use the API gateway
### Create a new skill

1. Create a new skill using the Morty CLI:

Expand Down Expand Up @@ -105,4 +105,15 @@ curl -X POST \
-F 'function_archive=@./test_data/lightOn.zip'
```

For more information, see the [OpenAPI spec](./openapi.yml).
For more information, see the [OpenAPI spec](./openapi.yml).

### Run the skill

1. Run the skill using the Morty CLI:

```bash
curl -X POST \
http://localhost:8080/v1/nlu \
-H 'Content-Type: application/json' \
-d '{"input_text": "quelle est la météo ?"}'
```
84 changes: 84 additions & 0 deletions internal/gateway/device_demand.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
package gateway

import (
"encoding/json"
"io"
"io/ioutil"
"net/http"

log "github.com/sirupsen/logrus"
)

const (
NLU_PATH = "/v1/nlu"
)

// Payload is the input data structure for the request
type Payload struct {
Payload string `json:"input_text"`
}

// NLUResponse is the output data structure for the response
type NLUResponse struct {
Body string `json:"response"`
}

func (s *Server) DeviceDemandHandler(w http.ResponseWriter, r *http.Request) {
// Check if the request method is POST
if r.Method != "POST" {
w.WriteHeader(http.StatusMethodNotAllowed)
w.Write([]byte("Only POST method is allowed."))
return
}

// Send the payload to NLU service
responseBody := SendToNLU(s.cfg.NluApiEndpoint, r.Body)

// Create the response object
nluResponse := NLUResponse{Body: responseBody}

// Marshal the response object
responseBytes, err := json.Marshal(nluResponse)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
w.Write([]byte("Error marshaling NLUResponse object."))
return
}

// Send the response to the device
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
w.Write(responseBytes)
}

func SendToNLU(NLU_API_ENDPOINT string, inputBody io.Reader) string {
if inputBody != nil {
bodyBytes, err := ioutil.ReadAll(inputBody)
if err != nil {
return err.Error()
}
log.Debugf("bodyBytes: %s", string(bodyBytes))
}

// Send intentsJson to NLU
req, err := http.NewRequest("POST", NLU_API_ENDPOINT+NLU_PATH, inputBody)
if err != nil {
return err.Error()
}
req.Header.Set("Content-Type", "application/json")

// Send intentsJson to NLU
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
return err.Error()
}
defer resp.Body.Close()

body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return err.Error()
}

return string(body)
}
11 changes: 7 additions & 4 deletions internal/gateway/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,9 @@ import (
)

const (
HEALTH_ENDPOINT = "/healthz"
SKILLS_ENDPOINT = "/v1/skills"
HEALTH_ENDPOINT = "/healthz"
SKILLS_ENDPOINT = "/v1/skills"
DEVICE_DEMAND_ENDPOINT = "/v1/nlu"
)

type (
Expand Down Expand Up @@ -53,10 +54,11 @@ func NewServer() (*Server, error) {

func (s *Server) Serve() {
p := s.cfg.Port
h := s.cfg.Addr

ctx, stop := context.WithCancel(context.Background())
server := &http.Server{
Addr: fmt.Sprintf("0.0.0.0:%d", p),
Addr: fmt.Sprintf("%s:%d", h, p),
Handler: s.router(),
}

Expand Down Expand Up @@ -84,7 +86,7 @@ func (s *Server) Serve() {
stop()
}()

log.Printf("polyxia gateway is listening on 0.0.0.0:%d\n", p)
log.Printf("polyxia gateway is listening on %s:%d\n", h, p)
if err := server.ListenAndServe(); err != nil && err != http.ErrServerClosed {
log.Fatal(err)
}
Expand All @@ -98,6 +100,7 @@ func (s *Server) router() http.Handler {
r.Use(middleware.RequestID)

r.Post(SKILLS_ENDPOINT, s.SkillsHandler)
r.Post(DEVICE_DEMAND_ENDPOINT, s.DeviceDemandHandler)
r.Get(HEALTH_ENDPOINT, s.HealthcheckHandler)

return r
Expand Down
8 changes: 4 additions & 4 deletions internal/gateway/skills.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ import (

const (
MORTY_FUNCTIONS_BUILD_ENDPOINT = "/functions/build"
NLU_SKILLS_ENDPOINT = "/skills"
NLU_SKILLS_ENDPOINT = "/v1/skills"
)

var (
Expand Down Expand Up @@ -56,12 +56,12 @@ func (s *Server) SkillsHandler(w http.ResponseWriter, r *http.Request) {
if mortyFunctionRegistryResp.StatusCode != http.StatusOK {
log.Warnf("Morty registry creation failed!")
// undo NLU skill creation with DELETE /v1/skills/:name
req, _ := http.NewRequest("DELETE", s.cfg.NluApiEndpoint+"/v1"+NLU_SKILLS_ENDPOINT+"/"+name, nil)
req, _ := http.NewRequest("DELETE", s.cfg.NluApiEndpoint+NLU_SKILLS_ENDPOINT+"/"+name, nil)
req.Header.Set("Content-Type", "application/json")
client := &http.Client{}
_, err := client.Do(req)
if err != nil {
log.Debugf("DELETE", s.cfg.NluApiEndpoint+"/v1"+NLU_SKILLS_ENDPOINT+"/"+name)
log.Debugf("DELETE", s.cfg.NluApiEndpoint+NLU_SKILLS_ENDPOINT+"/"+name)
}
log.Debugf(mortyFunctionRegistryResp.Status)
bodyBuf := new(bytes.Buffer)
Expand Down Expand Up @@ -108,7 +108,7 @@ func handleIntentsJSON(NLU_API_ENDPOINT string, r *http.Request, name string) (*
}

// Send intentsJson to NLU
req, err := http.NewRequest("POST", NLU_API_ENDPOINT+"/v1"+NLU_SKILLS_ENDPOINT, intentsJson)
req, err := http.NewRequest("POST", NLU_API_ENDPOINT+NLU_SKILLS_ENDPOINT, intentsJson)
if err != nil {
return nil, err
}
Expand Down
26 changes: 26 additions & 0 deletions openapi.yml
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,22 @@ info:
title: Gateway API
version: 1.0.0
paths:
/nlu:
post:
summary: Send a payload to recieve a response
requestBody:
required: true
content:
application/json:
schema:
$ref: '#/components/schemas/AskPayload'
responses:
'200':
description: NLU return the response
content:
application/json:
schema:
$ref: '#/components/schemas/NLUResponse'
/skills:
post:
summary: Create a new skill
Expand Down Expand Up @@ -39,6 +55,16 @@ paths:
$ref: '#/components/schemas/APIError'
components:
schemas:
AskPayload:
type: object
properties:
input_text:
type: string
NLUResponse:
type: object
properties:
response:
type: string
APIError:
type: object
properties:
Expand Down

0 comments on commit 742b2b2

Please sign in to comment.