Skip to content

Commit b6676b9

Browse files
committed
docs: update samples
1 parent e3d5f67 commit b6676b9

File tree

6 files changed

+275
-8
lines changed

6 files changed

+275
-8
lines changed

.gitignore

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
*.coverprofile
2-
.idea/modules.xml
32
sdk-go.iml
43
vcs.xml
54
settings.json
5+
.idea/
6+
.env

README.md

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -49,7 +49,7 @@ Find your API key in your user profile. To get your full API key click on "Get k
4949
Once you have a `model` and `version` identified, get authenticated with your API key.
5050

5151
```go
52-
client := modzysdk.NewClient("http://url.to.modzy/api").WithAPIKey("API Key")
52+
client := modzy.NewClient("http://url.to.modzy/api").WithAPIKey("API Key")
5353
```
5454

5555
## Basic usage
@@ -109,7 +109,7 @@ Additionally, users can set their own input names. When multiple input items are
109109
[Get a model's details](https://docs.modzy.com/reference/list-model-details):
110110

111111
```go
112-
out, err := client.Models().GetModelDetails(ctx, &modzysdk.GetModelDetailsInput{ModelID: "ed542963de"})
112+
out, err := client.Models().GetModelDetails(ctx, &modzy.GetModelDetailsInput{ModelID: "ed542963de"})
113113
if err != nil {
114114
return err
115115
}
@@ -121,7 +121,7 @@ Model specific sample requests are available in the version details and in the M
121121
[Get version details](https://docs.modzy.com/reference/get-version-details):
122122

123123
```go
124-
out, err := client.Models().GetModelVersionDetails(ctx, &modzysdk.GetModelVersionDetailsInput{ModelID: "ed542963de", Version: "0.0.27"})
124+
out, err := client.Models().GetModelVersionDetails(ctx, &modzy.GetModelVersionDetailsInput{ModelID: "ed542963de", Version: "0.0.27"})
125125
if err != nil {
126126
return err
127127
}
@@ -138,7 +138,7 @@ fmt.Println(" outputs:")
138138
for _, input := range out.Details.Inputs {
139139
fmt.Printf(
140140
" key %s, type %s, description: %s\n", output.Name, output.MediaType, output.Description
141-
);
141+
)
142142
}
143143
```
144144

@@ -155,7 +155,7 @@ Modzy supports several *input types* such as `text`, `embedded` for Base64 strin
155155
```go
156156
var inputs map[string]string
157157
inputs['my-input'] = "Modzy is great!"
158-
job, err := client.Jobs().SubmitJobText(ctx, &modzysdk.SubmitJobTextInput{ModelIdentifier="ed542963de", ModelVersion="0.0.27", Inputs=inputs})
158+
job, err := client.Jobs().SubmitJobText(ctx, &modzy.SubmitJobTextInput{ModelIdentifier="ed542963de", ModelVersion="0.0.27", Inputs=inputs})
159159
```
160160

161161
[Hold until the inference is complete and results become available](https://docs.modzy.com/reference/get-job-details):
@@ -171,7 +171,7 @@ Results are available per input item and can be identified with the name provide
171171
Jobs requested for multiple input items may have partial results available prior to job completion.
172172

173173
```go
174-
results, err := client.Jobs().GetJobResults(&modzysdk.GetJobResultsInput{JobIdentifier: job.JobIdentifier})
174+
results, err := client.Jobs().GetJobResults(&modzy.GetJobResultsInput{JobIdentifier: job.JobIdentifier})
175175
```
176176

177177
## Features
@@ -213,7 +213,7 @@ Set the base url and api key in each sample file:
213213

214214
```go
215215
// TODO: set the base url of modzy api and you api key
216-
client := modzysdk.NewClient("http://url.to.modzy/api").WithAPIKey("API Key")
216+
client := modzy.NewClient("http://url.to.modzy/api").WithAPIKey("API Key")
217217
```
218218

219219
Or follow the instructions [here](https://github.com/modzy/sdk-go/tree/main/contributing.adoc#set-environment-variables-in-bash) to learn more.

go.mod

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ go 1.16
55
require (
66
github.com/docker/go-units v0.4.0
77
github.com/hashicorp/go-version v1.3.0 // indirect
8+
github.com/joho/godotenv v1.3.0 // indirect
89
github.com/peterhellberg/link v1.1.0
910
github.com/pkg/errors v0.9.1
1011
github.com/sirupsen/logrus v1.8.1

go.sum

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,8 @@ github.com/docker/go-units v0.4.0 h1:3uh0PgVws3nIA0Q+MwDC8yjEPf9zjRfZZWXZYDct3Tw
55
github.com/docker/go-units v0.4.0/go.mod h1:fgPhTUdO+D/Jk86RDLlptpiXQzgHJF7gydDDbaIK4Dk=
66
github.com/hashicorp/go-version v1.3.0 h1:McDWVJIU/y+u1BRV06dPaLfLCaT7fUTJLp5r04x7iNw=
77
github.com/hashicorp/go-version v1.3.0/go.mod h1:fltr4n8CU8Ke44wwGCBoEymUuxUHl09ZGVZPK5anwXA=
8+
github.com/joho/godotenv v1.3.0 h1:Zjp+RcGpHhGlrMbJzXTrZZPrWj+1vfm90La1wgB6Bhc=
9+
github.com/joho/godotenv v1.3.0/go.mod h1:7hK45KPybAkOC6peb+G5yklZfMxEjkZhHbwpqxOKXbg=
810
github.com/kr/fs v0.1.0 h1:Jskdu9ieNAYnjxsi0LbQp1ulIKZV1LAFgK1tWhpZgl8=
911
github.com/kr/fs v0.1.0/go.mod h1:FFnZGqtBN9Gxj7eW1uZ42v5BccTP0vu6NEaFoC2HwRg=
1012
github.com/peterhellberg/link v1.1.0 h1:s2+RH8EGuI/mI4QwrWGSYQCRz7uNgip9BaM04HKu5kc=

samples/job_with_text_input_sample.go

Lines changed: 138 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,138 @@
1+
package main
2+
3+
import (
4+
"context"
5+
"github.com/joho/godotenv"
6+
modzy "github.com/modzy/sdk-go"
7+
"log"
8+
"os"
9+
"time"
10+
)
11+
12+
var (
13+
ctx = context.TODO()
14+
)
15+
16+
func main() {
17+
// The system admin can provide the right base API URL, the API key can be downloaded from your profile page on Modzy.
18+
// You can configure those params as is described in the README file (as environment variables, or by using the .env file),
19+
// or you can just update the BASE_URL and API_KEY variables and use this sample code (not recommended for production environments).
20+
err := godotenv.Load()
21+
if err != nil {
22+
log.Fatal("Error loading .env file")
23+
}
24+
// The MODZY_BASE_URL should point to the API services route which may be different from the Modzy page URL.
25+
// (ie: https://modzy.example.com).
26+
baseURL := os.Getenv("MODZY_BASE_URL")
27+
// The MODZY_API_KEY is your own personal API key. It is composed by a public part, a dot character, and a private part
28+
// (ie: AzQBJ3h4B1z60xNmhAJF.uQyQh8putLIRDi1nOldh).
29+
apiKey := os.Getenv("MODZY_API_KEY")
30+
// Client initialization:
31+
// Initialize the ApiClient instance with the BASE_URL and the API_KEY to store those arguments
32+
// for the following API calls.
33+
client := modzy.NewClient(baseURL).WithAPIKey(apiKey)
34+
// Create a Job with a text input, wait, and retrieve results:
35+
// Get the model object:
36+
// If you already know the model identifier (i.e.: you got it from the URL of the model details page or from the input sample),
37+
// you can skip this step. If you don't, you can find the model identifier by using its name as follows:
38+
//model, err := client.Models().GetModelDetailsByName(ctx, &modzy.GetModelDetailsByNameInput{Name: "Sentiment Analysis"})
39+
// Or if you already know the model id and want to know more about the model, you can use this instead:
40+
model, err := client.Models().GetModelDetails(ctx, &modzy.GetModelDetailsInput{ModelID: "cbf9e8d6da"})
41+
// You can find more information about how to query the models on the model_sample.go file.
42+
// The model identifier is under the ModelID key. You can take a look at the other properties under ModelDetails struct
43+
// Or just log the model identifier, and potencially the latest version
44+
log.Printf("The model identifier is %s and the latest version is %s\n", model.Details.ModelID, model.Details.LatestVersion)
45+
// Get the model version object:
46+
// If you already know the model version and the input key(s) of the model version you can skip this step. Also, you can
47+
// use the following code block to know about the inputs keys and skip the call on future job submissions.
48+
modelVersion, err := client.Models().GetModelVersionDetails(ctx, &modzy.GetModelVersionDetailsInput{ModelID: model.Details.ModelID, Version: model.Details.LatestVersion})
49+
if err != nil {
50+
log.Fatalf("Unexpected error %s", err)
51+
return
52+
}
53+
// The info stored in modelVersion provides insights about the amount of time that the model can spend processing, the inputs, and
54+
// output keys of the model.
55+
log.Printf("The model version is %s\n", modelVersion.Details.Version)
56+
log.Printf(" timeouts: status %dms, run %dms\n",modelVersion.Details.Timeout.Status, modelVersion.Details.Timeout.Run)
57+
log.Println(" inputs:")
58+
for _, input := range modelVersion.Details.Inputs {
59+
log.Printf(" key %s, type %s, description: %s\n", input.Name, input.AcceptedMediaTypes, input.Description)
60+
}
61+
log.Println(" outputs:")
62+
for _, output := range modelVersion.Details.Outputs {
63+
log.Printf(" key %s, type %s, description: %s\n", output.Name, output.MediaType, output.Description)
64+
}
65+
// Send the job:
66+
// With the info about the model (identifier), the model version (version string, input/output keys), you are ready to
67+
// submit the job. Just prepare the source map:
68+
mapSource := make(map[string]modzy.TextInputItem)
69+
mapInput := make(modzy.TextInputItem)
70+
mapInput["input.txt"] = "Modzy is great!"
71+
mapSource["source-key"] = mapInput
72+
// An inference job groups input data that you send to a model. You can send any amount of inputs to
73+
// process and you can identify and refer to a specific input by the key that you assign, for example we can add:
74+
mapInput = make(modzy.TextInputItem)
75+
mapInput["input.txt"] = "Sometimes I really hate ribs"
76+
mapSource["second-key"] = mapInput
77+
mapInput = make(modzy.TextInputItem)
78+
mapInput["input.txt"] = "Born and raised in Pennsylvania, Swift moved to Nashville, Tennessee, at the age of 14 to pursue a career in country music"
79+
mapSource["another-key"] = mapInput
80+
//If you send a wrong input key, the model fails to process the input.
81+
mapInput = make(modzy.TextInputItem)
82+
mapInput["a.wrong.key"] = "This input is wrong!"
83+
mapSource["wrong-key"] = mapInput
84+
// When you have all your inputs ready, you can use our helper method to submit the job as follows:
85+
job, err := client.Jobs().SubmitJobText(ctx, &modzy.SubmitJobTextInput{
86+
ModelIdentifier: model.Details.ModelID,
87+
ModelVersion: modelVersion.Details.Version,
88+
Inputs: mapSource,
89+
})
90+
if err != nil {
91+
log.Fatalf("Unexpected error %s", err)
92+
return
93+
}
94+
// Modzy creates the job and queue for processing. The job object contains all the info that you need to keep track
95+
// of the process, the most important being the job identifier and the job status.
96+
log.Printf("job: %s \n", job.Response.JobIdentifier)
97+
// The job moves to SUBMITTED, meaning that Modzy acknowledged the job and sent it to the queue to be processed.
98+
// We provide a helper method to listen until the job finishes processing. Its a good practice to set a max timeout
99+
// if you're doing a test (ie: 2*status+run). Otherwise, if the timeout is set to None, it will listen until the job finishes and moves to
100+
// COMPLETED, CANCELED, or TIMEOUT.
101+
job2, err := client.Jobs().WaitForJobCompletion(ctx, &modzy.WaitForJobCompletionInput{JobIdentifier: job.Response.JobIdentifier}, 20*time.Second)
102+
if err != nil {
103+
log.Fatalf("Unexpected error %s", err)
104+
return
105+
}
106+
// Get the results:
107+
// Check the status of the job. Jobs may be canceled or may reach a timeout.
108+
if job2.Details.Status == "COMPLETED" {
109+
// A completed job means that all the inputs were processed by the model. Check the results for each
110+
// input key provided in the source map to see the model output.
111+
results, err := client.Jobs().GetJobResults(ctx, &modzy.GetJobResultsInput{JobIdentifier: job.Response.JobIdentifier})
112+
if err != nil {
113+
log.Fatalf("Unexpected error %s", err)
114+
return
115+
}
116+
// The result object has some useful info:
117+
log.Printf("Result: finished: %s, total: %d, completed: %d, failed: %d",
118+
results.Results.Finished,
119+
results.Results.Total,
120+
results.Results.Completed,
121+
results.Results.Failed)
122+
// Notice that we are iterating through the same input source keys
123+
for key, _ := range mapSource{
124+
// The result object has the individual results of each job input. In this case the output key is called
125+
// results.json, so we can get the results as follows:
126+
if result, exists := results.Results.Results[key]; exists {
127+
// The output for this model comes in a JSON format, so we can directly log the model results:
128+
log.Printf(" %s: %s\n", key, result.Data["results.json"])
129+
} else {
130+
// If the model raises an error, we can get the specific error message:
131+
log.Fatalf(" %s: %s\n", key, result.Data)
132+
}
133+
}
134+
135+
} else {
136+
log.Fatalf("The job ends with status %s", job2.Details.Status)
137+
}
138+
}

samples/model_sample.go

Lines changed: 125 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,125 @@
1+
package main
2+
3+
import (
4+
"context"
5+
"github.com/joho/godotenv"
6+
modzy "github.com/modzy/sdk-go"
7+
"log"
8+
"os"
9+
)
10+
11+
var (
12+
ctx = context.TODO()
13+
)
14+
15+
func main() {
16+
// The system admin can provide the right base API URL, the API key can be downloaded from your profile page on Modzy.
17+
// You can configure those params as is described in the README file (as environment variables, or by using the .env file),
18+
// or you can just update the BASE_URL and API_KEY variables and use this sample code (not recommended for production environments).
19+
err := godotenv.Load()
20+
if err != nil {
21+
log.Fatal("Error loading .env file")
22+
}
23+
// The MODZY_BASE_URL should point to the API services route which may be different from the Modzy page URL.
24+
// (ie: https://modzy.example.com).
25+
baseURL := os.Getenv("MODZY_BASE_URL")
26+
// The MODZY_API_KEY is your own personal API key. It is composed by a public part, a dot character, and a private part
27+
// (ie: AzQBJ3h4B1z60xNmhAJF.uQyQh8putLIRDi1nOldh).
28+
apiKey := os.Getenv("MODZY_API_KEY")
29+
// Client initialization:
30+
// Initialize the ApiClient instance with the BASE_URL and the API_KEY to store those arguments
31+
// for the following API calls.
32+
client := modzy.NewClient(baseURL).WithAPIKey(apiKey)
33+
// Get all models:
34+
// You can get the full list of models from Modzy by using the get_all method to retrieve the identifier
35+
// and the latest version of each model
36+
listModelsInput := (&modzy.ListModelsInput{}).WithPaging(1000, 0)
37+
out, err := client.Models().ListModels(ctx, listModelsInput)
38+
if err != nil {
39+
log.Fatalf("Unexpected error %s", err)
40+
return
41+
}
42+
log.Printf("all models: %d\n", len(out.Models))
43+
// Also, use the get_models method to search for specific models:
44+
// Search by author:
45+
listModelsInput = (&modzy.ListModelsInput{}).WithPaging(1000, 0).WithFilterAnd(modzy.ListModelsFilterFieldAuthor, "Open Source")
46+
out, err = client.Models().ListModels(ctx, listModelsInput)
47+
if err != nil {
48+
log.Fatalf("Unexpected error %s", err)
49+
return
50+
}
51+
log.Printf("Open Source models: %d\n", len(out.Models))
52+
// Search for active models:
53+
listModelsInput = (&modzy.ListModelsInput{}).WithPaging(1000, 0).WithFilterAnd(modzy.ListModelsFilterFieldIsActive, "true")
54+
out, err = client.Models().ListModels(ctx, listModelsInput)
55+
if err != nil {
56+
log.Fatalf("Unexpected error %s", err)
57+
return
58+
}
59+
log.Printf("Active models: %d\n", len(out.Models))
60+
// Search by name (and paginate the results):
61+
listModelsInput = (&modzy.ListModelsInput{}).WithPaging(5,0).WithFilterAnd(modzy.ListModelsFilterFieldName, "Image")
62+
out, err = client.Models().ListModels(ctx, listModelsInput)
63+
if err != nil {
64+
log.Fatalf("Unexpected error %s", err)
65+
return
66+
}
67+
log.Printf("Models with name start with 'Image': %d\n", len(out.Models))
68+
// Combined search:
69+
listModelsInput = (&modzy.ListModelsInput{}).WithPaging(1000,0).
70+
WithFilterAnd(modzy.ListModelsFilterFieldName, "Image").
71+
WithFilterAnd(modzy.ListModelsFilterFieldAuthor, "Open Source").
72+
WithFilterAnd(modzy.ListModelsFilterFieldIsActive, "true")
73+
out, err = client.Models().ListModels(ctx, listModelsInput)
74+
if err != nil {
75+
log.Fatalf("Unexpected error %s", err)
76+
return
77+
}
78+
log.Printf("Active open source models which name starts with 'Image': %d\n", len(out.Models))
79+
// Get model details:
80+
// The models route only returns the modelId, latestVersion, and versions:
81+
for _, modelSummary := range out.Models {
82+
log.Println("Model: ", modelSummary)
83+
// Use the model identifier to get model details
84+
model, err := client.Models().GetModelDetails(ctx, &modzy.GetModelDetailsInput{ModelID: modelSummary.ID})
85+
if err != nil {
86+
log.Fatalf("Unexpected error %s", err)
87+
return
88+
}
89+
log.Println("Model Details: ", model)
90+
// Use the version identifier to get version details such as input and output details
91+
modelVersion, err := client.Models().GetModelVersionDetails(ctx, &modzy.GetModelVersionDetailsInput{ModelID: model.Details.ModelID, Version: model.Details.LatestVersion})
92+
if err != nil {
93+
log.Fatalf("Unexpected error %s", err)
94+
return
95+
}
96+
log.Println("Model Version detail keys: ", modelVersion)
97+
// then you'll get all the details about the specific model version
98+
log.Printf("ModelVersion Details %s\n", modelVersion.Details)
99+
// Probably the more interesting are the ones related with the inputs and outputs of the model
100+
log.Println(" inputs:")
101+
for _, input := range modelVersion.Details.Inputs {
102+
log.Printf(" key %s, type %s, description: %s\n", input.Name, input.AcceptedMediaTypes, input.Description)
103+
}
104+
log.Println(" outputs:")
105+
for _, output := range modelVersion.Details.Outputs {
106+
log.Printf(" key %s, type %s, description: %s\n", output.Name, output.MediaType, output.Description)
107+
}
108+
}
109+
// Get model by name:
110+
// You can also find models by name
111+
model, err := client.Models().GetModelDetailsByName(ctx, &modzy.GetModelDetailsByNameInput{Name: "Dataset Joining"})
112+
// this method returns the first matching model and its details
113+
log.Printf("Dataset Joining: id:%s, author: %s, is_active: %s, description: %s",
114+
model.Details.ModelID, model.Details.Author, model.Details.IsActive, model.Details.Description)
115+
116+
// Finally, you can find related models related with this search:
117+
related, err := client.Models().GetRelatedModels(ctx, &modzy.GetRelatedModelsInput{ModelID: model.Details.ModelID})
118+
log.Println("related models")
119+
for _, model := range related.RelatedModels {
120+
log.Printf(" %s :: %s (%s)", model.ModelID, model.Name, model.Author)
121+
}
122+
123+
124+
}
125+

0 commit comments

Comments
 (0)