Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feat/messages api #546

Merged
merged 17 commits into from
Nov 13, 2023
Merged
Show file tree
Hide file tree
Changes from 11 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion fine_tuning_job_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ func TestFineTuningJob(t *testing.T) {
)

server.RegisterHandler(
"/fine_tuning/jobs/"+testFineTuninigJobID+"/cancel",
"/v1/fine_tuning/jobs/"+testFineTuninigJobID+"/cancel",
func(w http.ResponseWriter, _ *http.Request) {
resBytes, _ := json.Marshal(openai.FineTuningJob{})
fmt.Fprintln(w, string(resBytes))
Expand Down
10 changes: 8 additions & 2 deletions internal/test/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (
"net/http"
"net/http/httptest"
"regexp"
"strings"
)

const testAPI = "this-is-my-secure-token-do-not-steal!!"
Expand All @@ -23,13 +24,16 @@ func NewTestServer() *ServerTest {
}

func (ts *ServerTest) RegisterHandler(path string, handler handler) {
// to make the registered paths friendlier to a regex match in the route handler
// in OpenAITestServer
path = strings.ReplaceAll(path, "*", ".*")
ts.handlers[path] = handler
}

// OpenAITestServer Creates a mocked OpenAI server which can pretend to handle requests during testing.
func (ts *ServerTest) OpenAITestServer() *httptest.Server {
return httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
log.Printf("received request at path %q\n", r.URL.Path)
log.Printf("received a %s request at path %q\n", r.Method, r.URL.Path)

// check auth
if r.Header.Get("Authorization") != "Bearer "+GetTestToken() && r.Header.Get("api-key") != GetTestToken() {
Expand All @@ -38,8 +42,10 @@ func (ts *ServerTest) OpenAITestServer() *httptest.Server {
}

// Handle /path/* routes.
// Note: the * is converted to a .* in register handler for proper regex handling
for route, handler := range ts.handlers {
pattern, _ := regexp.Compile(route)
// Adding ^ and $ to make path matching deterministic since go map iteration isn't ordered
pattern, _ := regexp.Compile("^" + route + "$")
if pattern.MatchString(r.URL.Path) {
handler(w, r)
return
Expand Down
173 changes: 173 additions & 0 deletions messages.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,173 @@
package openai

import (
"context"
"fmt"
"net/http"
"net/url"
)

const (
messagesSuffix = "/messages"
)

type Message struct {
ID string `json:"id"`
Object string `json:"object"`
CreatedAt int `json:"created_at"`
ThreadID string `json:"thread_id"`
Role string `json:"role"`
Content []MessageContent `json:"content"`
FileIds []interface{} `json:"file_ids"`
urjitbhatia marked this conversation as resolved.
Show resolved Hide resolved
AssistantID string `json:"assistant_id"`
RunID string `json:"run_id"`
urjitbhatia marked this conversation as resolved.
Show resolved Hide resolved
Metadata map[string]any `json:"metadata"`

httpHeader
}

type MessagesList struct {
Messages []Message `json:"data"`

httpHeader
}

type MessageContent struct {
Type string `json:"type"`
Text MessageText `json:"text"`
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
Text MessageText `json:"text"`
Text *MessageText `json:"text,omitempty"`
ImageFile *ImageFile `json:"image_file,omitempty"` // <- define this one

}
type MessageText struct {
Value string `json:"value"`
Annotations []interface{} `json:"annotations"`
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

let's use any instead of interface{}

}

type MessageRequest struct {
Role string `json:"role"`
Content string `json:"content"`
FileIds []string `json:"file_ids,omitempty"`
Metadata map[string]any `json:"metadata,omitempty"`
}

type MessageFile struct {
ID string `json:"id"`
Object string `json:"object"`
CreatedAt int `json:"created_at"`
MessageID string `json:"message_id"`

httpHeader
}

type MessageFilesList struct {
MessageFiles []MessageFile `json:"data"`

httpHeader
}

// CreateMessage creates a new message.
func (c *Client) CreateMessage(ctx context.Context, threadID string, request MessageRequest) (msg Message, err error) {
urlSuffix := fmt.Sprintf("/threads/%s%s", threadID, messagesSuffix)
req, err := c.newRequest(ctx, http.MethodPost, c.fullURL(urlSuffix), withBody(request))

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Any reason for not adding withBetaAssistantV1() here ? When using CreateMessage I still get the error You must provide the 'OpenAI-Beta' header to access the Assistants API. Please try again by setting the header 'OpenAI-Beta: assistants=v1'.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@lowczarc I ran into this and submitted: #566

if err != nil {
return
}

Check warning on line 72 in messages.go

View check run for this annotation

Codecov / codecov/patch

messages.go#L71-L72

Added lines #L71 - L72 were not covered by tests

err = c.sendRequest(req, &msg)
return
}

// ListMessage fetches all messages in the thread.
func (c *Client) ListMessage(ctx context.Context, threadID string,
limit *int,
order *string,
after *string,
before *string,
) (messages MessagesList, err error) {
urlValues := url.Values{}
if limit != nil {
urlValues.Add("limit", fmt.Sprintf("%d", *limit))
}
if order != nil {
urlValues.Add("order", *order)
}
if after != nil {
urlValues.Add("after", *after)
}
if before != nil {
urlValues.Add("before", *before)
}
encodedValues := ""
if len(urlValues) > 0 {
encodedValues = "?" + urlValues.Encode()
}

urlSuffix := fmt.Sprintf("/threads/%s%s%s", threadID, messagesSuffix, encodedValues)
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Just a suggestion: changing messagesSuffix from /messages to messages would make formatting more consistent without %s%s mixed with %s/%s

req, err := c.newRequest(ctx, http.MethodGet, c.fullURL(urlSuffix), withBetaAssistantV1())
if err != nil {
return
}

Check warning on line 107 in messages.go

View check run for this annotation

Codecov / codecov/patch

messages.go#L106-L107

Added lines #L106 - L107 were not covered by tests

err = c.sendRequest(req, &messages)
return
}

// RetrieveMessage retrieves a Message.
func (c *Client) RetrieveMessage(
ctx context.Context,
threadID, messageID string,
) (msg Message, err error) {
urlSuffix := fmt.Sprintf("/threads/%s%s/%s", threadID, messagesSuffix, messageID)
req, err := c.newRequest(ctx, http.MethodGet, c.fullURL(urlSuffix), withBetaAssistantV1())
if err != nil {
return
}

Check warning on line 122 in messages.go

View check run for this annotation

Codecov / codecov/patch

messages.go#L121-L122

Added lines #L121 - L122 were not covered by tests

err = c.sendRequest(req, &msg)
return
}

// ModifyMessage modifies a message.
func (c *Client) ModifyMessage(
ctx context.Context,
threadID, messageID string,
metadata map[string]any,
) (msg Message, err error) {
urlSuffix := fmt.Sprintf("/threads/%s%s/%s", threadID, messagesSuffix, messageID)
req, err := c.newRequest(ctx, http.MethodPost, c.fullURL(urlSuffix),
withBody(metadata), withBetaAssistantV1())
if err != nil {
return
}

Check warning on line 139 in messages.go

View check run for this annotation

Codecov / codecov/patch

messages.go#L138-L139

Added lines #L138 - L139 were not covered by tests

err = c.sendRequest(req, &msg)
return
}

// RetrieveMessageFile fetches a message file.
func (c *Client) RetrieveMessageFile(
ctx context.Context,
threadID, messageID, fileID string,
) (file MessageFile, err error) {
urlSuffix := fmt.Sprintf("/threads/%s%s/%s/files/%s", threadID, messagesSuffix, messageID, fileID)
req, err := c.newRequest(ctx, http.MethodGet, c.fullURL(urlSuffix), withBetaAssistantV1())
if err != nil {
return
}

Check warning on line 154 in messages.go

View check run for this annotation

Codecov / codecov/patch

messages.go#L153-L154

Added lines #L153 - L154 were not covered by tests

err = c.sendRequest(req, &file)
return
}

// ListMessageFiles fetches all files attached to a message.
func (c *Client) ListMessageFiles(
ctx context.Context,
threadID, messageID string,
) (files MessageFilesList, err error) {
urlSuffix := fmt.Sprintf("/threads/%s%s/%s/files", threadID, messagesSuffix, messageID)
req, err := c.newRequest(ctx, http.MethodGet, c.fullURL(urlSuffix), withBetaAssistantV1())
if err != nil {
return
}

Check warning on line 169 in messages.go

View check run for this annotation

Codecov / codecov/patch

messages.go#L168-L169

Added lines #L168 - L169 were not covered by tests

err = c.sendRequest(req, &files)
return
}
Loading
Loading