Skip to content

Commit

Permalink
openapi generator pingchat
Browse files Browse the repository at this point in the history
  • Loading branch information
zhangyangyu committed Sep 4, 2024
1 parent bd7c1f2 commit d7b3d91
Show file tree
Hide file tree
Showing 31 changed files with 2,572 additions and 1,210 deletions.
11 changes: 2 additions & 9 deletions Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -26,18 +26,11 @@ generate-mocks: ## Generate mock objects
mockery --name EventsSender --recursive --output=internal/mock --outpkg mock --filename sender.go
mockery --name Uploader --recursive --output=internal/mock --outpkg mock --filename uploader.go

# Required to install go-swagger https://goswagger.io/install.html
.PHONY: generate-import-client
generate-import-client: ## Generate import client
@echo "==> Generating import client"
go install github.com/go-swagger/go-swagger/cmd/swagger@latest
swagger generate client -f pkg/tidbcloud/import/import-api.json -A tidbcloud-import -t pkg/tidbcloud/import

.PHONY: generate-pingchat-client
generate-pingchat-client: ## Generate PingChat client
@echo "==> Generating PingChat client"
go install github.com/go-swagger/go-swagger/cmd/swagger@latest
swagger generate client -f pkg/tidbcloud/pingchat/pingchat_swagger.json -A tidbcloud-pingchat -t pkg/tidbcloud/pingchat
rm -rf pkg/tidbcloud/pingchat
cd tools/openapi-generator && npx openapi-generator-cli generate --additional-properties=withGoMod=false,enumClassPrefix=true --global-property=apiTests=false,apiDocs=false,modelDocs=false,modelTests=false -i ../../pkg/tidbcloud/pingchat.swagger.json -g go -o ../../pkg/tidbcloud/pingchat --package-name pingchat

.PHONY: addcopy
addcopy: ## Add copyright to all files
Expand Down
41 changes: 19 additions & 22 deletions internal/cli/ai/ai.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,8 +24,7 @@ import (
"tidbcloud-cli/internal/output"
"tidbcloud-cli/internal/ui"
"tidbcloud-cli/internal/util"
"tidbcloud-cli/pkg/tidbcloud/pingchat/client/operations"
"tidbcloud-cli/pkg/tidbcloud/pingchat/models"
"tidbcloud-cli/pkg/tidbcloud/pingchat"

tea "github.com/charmbracelet/bubbletea"
"github.com/pingcap/errors"
Expand Down Expand Up @@ -93,12 +92,11 @@ func AICmd(h *internal.Helper) *cobra.Command {
if err != nil {
return err
}
param := operations.NewChatParams()

context := cmd.Context()
if opts.interactive {
task := func(messages []ui.ChatMessage) tea.Msg {
msgs := make([]*models.PingchatChatMessage, 0, len(messages))
msgs := make([]pingchat.PingchatChatMessage, 0, len(messages))
for _, message := range messages {
content := message.Content
role, err := convertRole(message.Role)
Expand All @@ -107,16 +105,16 @@ func AICmd(h *internal.Helper) *cobra.Command {
Err: err,
}
}
msg := models.PingchatChatMessage{
Content: &content,
Role: &role,
msg := pingchat.PingchatChatMessage{
Content: content,
Role: role,
}
msgs = append(msgs, &msg)
msgs = append(msgs, msg)
}
chat, err := client.Chat(param.WithChatInfo(&models.PingchatChatInfo{
chat, err := client.Chat(context, &pingchat.PingchatChatInfo{
Messages: msgs,
Domain: domain,
}).WithContext(context))
})

if err != nil {
return ui.EndSendingMsg{
Expand All @@ -125,12 +123,12 @@ func AICmd(h *internal.Helper) *cobra.Command {
}

linkContent := "\n\n"
for i, link := range chat.Payload.Links {
linkContent = fmt.Sprintf("%s[%d] [%s](%s)\n", linkContent, i+1, link.Title, link.Link)
for i, link := range chat.Links {
linkContent = fmt.Sprintf("%s[%d] [%s](%s)\n", linkContent, i+1, *link.Title, *link.Link)
}

// Replace occurrences of [^\d+] with [\d+] for better user comprehension.
content := re.ReplaceAllString(chat.Payload.Content, "[$1]")
content := re.ReplaceAllString(*chat.Content, "[$1]")

return ui.EndSendingMsg{
Msg: ui.ChatMessage{
Expand Down Expand Up @@ -161,21 +159,20 @@ func AICmd(h *internal.Helper) *cobra.Command {
return errors.Trace(err)
}

role := models.PingchatChatMessageRoleUser
chat, err := client.Chat(param.WithChatInfo(&models.PingchatChatInfo{
Messages: []*models.PingchatChatMessage{
chat, err := client.Chat(context, &pingchat.PingchatChatInfo{
Messages: []pingchat.PingchatChatMessage{
{
Content: &query,
Role: &role,
Content: query,
Role: "user",
},
},
Domain: domain,
}).WithContext(context))
})
if err != nil {
return err
}

err = output.PrintJson(h.IOStreams.Out, chat.Payload)
err = output.PrintJson(h.IOStreams.Out, chat)
return errors.Trace(err)
}

Expand All @@ -190,9 +187,9 @@ func AICmd(h *internal.Helper) *cobra.Command {
func convertRole(role ui.Role) (string, error) {
switch role {
case ui.RoleUser:
return models.PingchatChatMessageRoleUser, nil
return "user", nil
case ui.RoleBot:
return models.PingchatChatMessageRoleAssistant, nil
return "assistant", nil
default:
return "", errors.New("unknown chat role")
}
Expand Down
21 changes: 11 additions & 10 deletions internal/cli/ai/ai_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ package ai

import (
"bytes"
"context"
"encoding/json"
"fmt"
"os"
Expand All @@ -25,8 +26,7 @@ import (
"tidbcloud-cli/internal/iostream"
"tidbcloud-cli/internal/mock"
"tidbcloud-cli/internal/service/cloud"
"tidbcloud-cli/pkg/tidbcloud/pingchat/client/operations"
"tidbcloud-cli/pkg/tidbcloud/pingchat/models"
"tidbcloud-cli/pkg/tidbcloud/pingchat"

mockTool "github.com/stretchr/testify/mock"
"github.com/stretchr/testify/require"
Expand Down Expand Up @@ -56,20 +56,21 @@ func (suite *AISuite) SetupTest() {
func (suite *AISuite) TestAIArgs() {
assert := require.New(suite.T())

links := []*models.PingchatLink{
link := "https://tidbcloud.com"
links := []pingchat.PingchatLink{
{
Link: "https://tidbcloud.com",
Link: &link,
},
}
chatOK := operations.ChatOK{Payload: &models.PingchatChatResponse{
Content: "hello",
answer := "hello"
chatResp := &pingchat.PingchatChatResponse{
Content: &answer,
Links: links,
}}
}

res, _ := json.MarshalIndent(chatOK.Payload, "", " ")
res, _ := json.MarshalIndent(chatResp, "", " ")

suite.mockClient.On("Chat", mockTool.Anything).
Return(&chatOK, nil)
suite.mockClient.On("Chat", context.Background(), mockTool.Anything).Return(chatResp, nil)

tests := []struct {
name string
Expand Down
31 changes: 12 additions & 19 deletions internal/mock/api_client.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

37 changes: 22 additions & 15 deletions internal/service/cloud/api_client.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,8 +26,7 @@ import (
"tidbcloud-cli/internal/config"
"tidbcloud-cli/internal/prop"
"tidbcloud-cli/internal/version"
pingchatClient "tidbcloud-cli/pkg/tidbcloud/pingchat/client"
pingchatOp "tidbcloud-cli/pkg/tidbcloud/pingchat/client/operations"
"tidbcloud-cli/pkg/tidbcloud/pingchat"
"tidbcloud-cli/pkg/tidbcloud/v1beta1/iam"
"tidbcloud-cli/pkg/tidbcloud/v1beta1/serverless/br"
"tidbcloud-cli/pkg/tidbcloud/v1beta1/serverless/branch"
Expand All @@ -36,14 +35,13 @@ import (
serverlessImportClient "tidbcloud-cli/pkg/tidbcloud/v1beta1/serverless_import/client"
serverlessImportOp "tidbcloud-cli/pkg/tidbcloud/v1beta1/serverless_import/client/import_service"

apiClient "github.com/c4pt0r/go-tidbcloud-sdk-v1/client"
httpTransport "github.com/go-openapi/runtime/client"
"github.com/go-openapi/strfmt"
"github.com/icholy/digest"
)

const (
DefaultApiUrl = "https://" + apiClient.DefaultHost
DefaultApiUrl = "https://api.tidbcloud.com"
DefaultServerlessEndpoint = "https://serverless.tidbapi.com"
DefaultIAMEndpoint = "https://iam.tidbapi.com"
userAgent = "User-Agent"
Expand Down Expand Up @@ -80,7 +78,7 @@ type TiDBCloudClient interface {

DeleteBranch(ctx context.Context, clusterId string, branchId string) (*branch.Branch, error)

Chat(params *pingchatOp.ChatParams, opts ...pingchatOp.ClientOption) (*pingchatOp.ChatOK, error)
Chat(ctx context.Context, chatInfo *pingchat.PingchatChatInfo) (*pingchat.PingchatChatResponse, error)

DeleteBackup(ctx context.Context, backupId string) (*br.V1beta1Backup, error)

Expand Down Expand Up @@ -122,7 +120,7 @@ type TiDBCloudClient interface {
type ClientDelegate struct {
ic *iam.APIClient
bc *branch.APIClient
pc *pingchatClient.TidbcloudPingchat
pc *pingchat.APIClient
brc *br.APIClient
sc *cluster.APIClient
sic *serverlessImportClient.TidbcloudServerless
Expand Down Expand Up @@ -276,8 +274,13 @@ func (d *ClientDelegate) DeleteBranch(ctx context.Context, clusterId string, bra
return b, parseError(err, h)
}

func (d *ClientDelegate) Chat(params *pingchatOp.ChatParams, opts ...pingchatOp.ClientOption) (*pingchatOp.ChatOK, error) {
return d.pc.Operations.Chat(params, opts...)
func (d *ClientDelegate) Chat(ctx context.Context, chatInfo *pingchat.PingchatChatInfo) (*pingchat.PingchatChatResponse, error) {
r := d.pc.DefaultAPI.Chat(ctx)
if chatInfo != nil {
r = r.ChatInfo(*chatInfo)
}
resp, h, err := r.Execute()
return resp, parseError(err, h)
}

func (d *ClientDelegate) DeleteBackup(ctx context.Context, backupId string) (*br.V1beta1Backup, error) {
Expand Down Expand Up @@ -414,7 +417,7 @@ func (d *ClientDelegate) UpdateSQLUser(ctx context.Context, clusterID string, us
return res, parseError(err, h)
}

func NewApiClient(rt http.RoundTripper, apiUrl string, serverlessEndpoint string, iamEndpoint string) (*branch.APIClient, *cluster.APIClient, *pingchatClient.TidbcloudPingchat, *br.APIClient, *serverlessImportClient.TidbcloudServerless, *export.APIClient, *iam.APIClient, error) {
func NewApiClient(rt http.RoundTripper, apiUrl string, serverlessEndpoint string, iamEndpoint string) (*branch.APIClient, *cluster.APIClient, *pingchat.APIClient, *br.APIClient, *serverlessImportClient.TidbcloudServerless, *export.APIClient, *iam.APIClient, error) {
httpclient := &http.Client{
Transport: rt,
}
Expand All @@ -424,22 +427,22 @@ func NewApiClient(rt http.RoundTripper, apiUrl string, serverlessEndpoint string
if err != nil {
return nil, nil, nil, nil, nil, nil, nil, err
}
transport := httpTransport.NewWithClient(u.Host, u.Path, []string{u.Scheme}, httpclient)

// v1beta1 api (serverless)
serverlessURL, err := prop.ValidateApiUrl(serverlessEndpoint)
if err != nil {
return nil, nil, nil, nil, nil, nil, nil, err
}

importTransport := httpTransport.NewWithClient(serverlessURL.Host, serverlessImportClient.DefaultBasePath, []string{serverlessURL.Scheme}, httpclient)

iamCfg := iam.NewConfiguration()
iamCfg.HTTPClient = httpclient
iamURL, err := prop.ValidateApiUrl(iamEndpoint)
if err != nil {
return nil, nil, nil, nil, nil, nil, nil, err
}

importTransport := httpTransport.NewWithClient(serverlessURL.Host, serverlessImportClient.DefaultBasePath, []string{serverlessURL.Scheme}, httpclient)

iamCfg := iam.NewConfiguration()
iamCfg.HTTPClient = httpclient
iamCfg.Host = iamURL.Host

clusterCfg := cluster.NewConfiguration()
Expand All @@ -458,8 +461,12 @@ func NewApiClient(rt http.RoundTripper, apiUrl string, serverlessEndpoint string
backupRestoreCfg.HTTPClient = httpclient
backupRestoreCfg.Host = serverlessURL.Host

pingchatCfg := pingchat.NewConfiguration()
pingchatCfg.HTTPClient = httpclient
pingchatCfg.Host = u.Host

return branch.NewAPIClient(branchCfg), cluster.NewAPIClient(clusterCfg),
pingchatClient.New(transport, strfmt.Default), br.NewAPIClient(backupRestoreCfg),
pingchat.NewAPIClient(pingchatCfg), br.NewAPIClient(backupRestoreCfg),
serverlessImportClient.New(importTransport, strfmt.Default), export.NewAPIClient(exportCfg),
iam.NewAPIClient(iamCfg), nil
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"schemes": [
"http"
"https"
],
"swagger": "2.0",
"info": {
Expand Down
24 changes: 24 additions & 0 deletions pkg/tidbcloud/pingchat/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
# Compiled Object files, Static and Dynamic libs (Shared Objects)
*.o
*.a
*.so

# Folders
_obj
_test

# Architecture specific extensions/prefixes
*.[568vq]
[568vq].out

*.cgo1.go
*.cgo2.c
_cgo_defun.c
_cgo_gotypes.go
_cgo_export.*

_testmain.go

*.exe
*.test
*.prof
23 changes: 23 additions & 0 deletions pkg/tidbcloud/pingchat/.openapi-generator-ignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
# OpenAPI Generator Ignore
# Generated by openapi-generator https://github.com/openapitools/openapi-generator

# Use this file to prevent files from being overwritten by the generator.
# The patterns follow closely to .gitignore or .dockerignore.

# As an example, the C# client generator defines ApiClient.cs.
# You can make changes and tell OpenAPI Generator to ignore just this file by uncommenting the following line:
#ApiClient.cs

# You can match any string of characters against a directory, file or extension with a single asterisk (*):
#foo/*/qux
# The above matches foo/bar/qux and foo/baz/qux, but not foo/bar/baz/qux

# You can recursively match patterns against a directory, file or extension with a double asterisk (**):
#foo/**/qux
# This matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux

# You can also negate patterns with an exclamation (!).
# For example, you can ignore all files in a docs folder with the file extension .md:
#docs/*.md
# Then explicitly reverse the ignore rule for a single file:
#!docs/README.md
Loading

0 comments on commit d7b3d91

Please sign in to comment.