package memcoai
import "github.com/memcoai/memcoai/go/memcoai"
Package memcoai is the Go SDK for Memco Shared Memory: a persistent, searchable memory that a team and its AI agents share.
An agent searches the memory before it starts work and writes back what it learned when it finishes, so what one agent establishes every teammate's agent can find. Memory is partitioned into domains, each with its own subject matter and tag vocabulary, and every result carries a reliability signal built from what readers reported back about it.
Getting started
Create a Client, prove the connection with Client.Connect, and open a Session in a domain:
client, err := memcoai.NewClient(memcoai.Options{}) // reads MEMCO_API_TOKEN
if err != nil {
return err
}
defer client.Close(ctx)
if err := client.Connect(ctx); err != nil {
return err
}
session, err := client.Memory.StartSession(ctx, "coding")
if err != nil {
return err
}
result, err := session.Search(ctx, "how should a client authenticate", memcoai.ScopedSearchParams{})
Configuration
Options fields fall back to the environment, then to built-in defaults:
MEMCO_CLIENT_ID an API client's id and secret, read as a pair; with no
MEMCO_CLIENT_SECRET credential in Options, both set win over MEMCO_API_TOKEN
MEMCO_API_TOKEN the credential, when no client pair is set
MEMCO_API_KEY read when MEMCO_API_TOKEN is unset; deprecated, and warns once
MEMCO_API_HOST the endpoint; defaults to grpc.memco.ai:443
MEMCO_API_TLS false dials without TLS, for a local server; true or
unset keeps TLS on, and anything else is refused.
Options.TLS, when set, wins over it
MEMCO_LOG the SDK logger's level: critical, error, warning, info
(the default), debug, or none to silence it
A token in Options ignores the client pair in the environment, and a token beside client credentials in Options is refused. No credential is ever written to a log record or an error. A client without TLS logs a warning as it is built.
Networks and users
An API client's credentials (Options.ClientID and Options.ClientSecret) are exchanged for a token the client renews by itself. With them, Client.Networks places your own users in memory networks, which decide what knowledge each can find, and Client.Users creates those users, known to Memco by your id for them, and their API keys.
Acting for your users
MemoryOperations.StartSession with ExternalID opens a session acting as one of your users: every call through it carries a short-lived key minted for that user, which renews itself and is ended by Session.Close. Sessions for different users run at once on one client, each under its own key.
session, err := client.Memory.StartSession(ctx, "coding", memcoai.ExternalID("customer-42"))
if err != nil {
return err
}
defer session.Close(ctx)
Contexts and timeouts
Every call that can block takes a context.Context. A context with a deadline bounds the call, whether that deadline is shorter or longer than Options.Timeout; a context without one gets Options.Timeout from the call's start. That one deadline covers the whole call: waiting for a credential, when none still serves and a new one must be minted first, and the request, which gets whatever the wait left. A context that has already ended sends nothing. Client.Close takes a context too: it waits for calls in flight until the context ends, then closes regardless.
Errors
Every error this package returns implements Error, and is one of the concrete types below. Use errors.As, and test a subtype before its parent: a *SunsetError is also a *PreconditionFailedError, and an *UnhealthyError is also an *UnavailableError.
- *ConfigError: a setting or state stopped the call before it was sent, or, in the one case its documentation names, this machine's clock did.
- *InvalidRequestError: the request is malformed. The SDK refuses many of these itself, before sending anything.
- *AuthenticationError, *PermissionError: the credential was rejected, or may not do what was asked.
- *NotFoundError: a handle resolves to nothing.
- *AlreadyExistsError: what the call would create already exists.
- *PreconditionFailedError: the account, or what the caller uses, is not in a state that allows the call. Its subtypes name why: *SunsetError, *UserAlreadyAssignedNetworkError and *ExternalUserNeedsCustomerNetworkError.
- *ResourceExhaustedError: a rate limit or quota is spent; its Kind says which.
- *UnavailableError, *UnhealthyError: the service could not be reached, or is not serving. Reads have already been retried.
- *TimeoutError: the call ran out of time. A write may have happened.
- *InternalError: anything else, including a call cancelled through its context.
When a context ends a call — the caller's, or the one Options.Timeout adds to a context without a deadline — the error also matches context.Canceled or context.DeadlineExceeded with errors.Is.
Logging
The SDK logs through its own log/slog logger, never slog.Default. Its level comes from MEMCO_LOG, Options.LogLevel or SetLevel; none silences it, deprecation notices included. Options.Logger sends one client's records to a logger of the caller's instead. An error the SDK returns is never also logged.
Agents
Session.Tools offers a session's operations to a model as tools, in the shapes Toolset.ToAnthropic and Toolset.ToOpenAI return, and Toolset.Call runs the one a model named. Briefing turns what the service says about a domain into guidance for a system prompt, and Render turns any result into text a model can read.
Index
- Constants
- func Briefing(domain DomainEntry, instructions Instructions) string
- func IsAgentRecoverable(err error) bool
- func Render(r Rendered) string
- func SetLevel(level string) error
- type APIError
- type AddMemberParams
- type AlreadyExistsError
- type AnthropicTool
- type AuthenticationError
- type Client
- type ConfigError
- type CreateKeyParams
- type CreateMemoryParams
- type CreateNetworkParams
- type CreateUserParams
- type CreatedKey
- type DataSource
- type DeletedNetwork
- type DomainEntry
- type DomainList
- type EnrichMemoryParams
- type Error
- type ExternalUser
- type ExternalUserKey
- type ExternalUserList
- type ExternalUserNeedsCustomerNetworkError
- type FeedbackEntry
- type FeedbackRating
- type FeedbackResult
- type Group
- type GroupList
- type ImportMemoriesParams
- type ImportOutcome
- type ImportResult
- type ImportStatus
- type ImportedInsight
- type ImportedMemory
- type Insight
- type Instructions
- type InternalError
- type InvalidRequestError
- type JSONSchema
- type Limits
- type ListGroupsParams
- type ListMembersParams
- type ListNetworksParams
- type ListUsersParams
- type Member
- type MemberList
- type MemberPlacement
- type Memory
- type MemoryFeedback
-
type MemoryOperations
- func (m *MemoryOperations) CreateMemory(ctx context.Context, p CreateMemoryParams) (*WriteResult, error)
- func (m *MemoryOperations) EnrichMemory(ctx context.Context, p EnrichMemoryParams) (*WriteResult, error)
- func (m *MemoryOperations) GetMemory(ctx context.Context, idx string) (*Memory, error)
- func (m *MemoryOperations) ImportMemories(ctx context.Context, memories []ImportedMemory, p ImportMemoriesParams) (*ImportResult, error)
- func (m *MemoryOperations) ListDomains(ctx context.Context) (*DomainList, error)
- func (m *MemoryOperations) ListTools(ctx context.Context) ([]ToolDescriptor, error)
- func (m *MemoryOperations) RevertMemory(ctx context.Context, operationID string) (*RevertResult, error)
- func (m *MemoryOperations) Search(ctx context.Context, query string, p SearchParams) (*SearchResult, error)
- func (m *MemoryOperations) ShareFeedback(ctx context.Context, sessionID string, feedback []FeedbackRating) (*FeedbackResult, error)
- func (m *MemoryOperations) StartSession(ctx context.Context, domain string, opts ...SessionOption) (*Session, error)
- type Network
- type NetworkList
-
type NetworkOperations
- func (n *NetworkOperations) AddGroup(ctx context.Context, networkID, groupID string) error
- func (n *NetworkOperations) AddMember(ctx context.Context, networkID, userID string, p AddMemberParams) (*MemberPlacement, error)
- func (n *NetworkOperations) Create(ctx context.Context, p CreateNetworkParams) (*Network, error)
- func (n *NetworkOperations) Delete(ctx context.Context, networkID string) (*DeletedNetwork, error)
- func (n *NetworkOperations) List(ctx context.Context, p ListNetworksParams) (*NetworkList, error)
- func (n *NetworkOperations) ListGroupMembers(ctx context.Context, groupID string) ([]Member, error)
- func (n *NetworkOperations) ListGroups(ctx context.Context, p ListGroupsParams) (*GroupList, error)
- func (n *NetworkOperations) ListMembers(ctx context.Context, networkID string, p ListMembersParams) (*MemberList, error)
- func (n *NetworkOperations) RemoveGroup(ctx context.Context, networkID, groupID string) error
- func (n *NetworkOperations) RemoveMember(ctx context.Context, networkID, userID string) error
- func (n *NetworkOperations) Update(ctx context.Context, networkID string, p UpdateNetworkParams) (*Network, error)
- type NotFoundError
- type OpenAIFunction
- type OpenAITool
- type Options
- type PermissionError
- type PreconditionFailedError
- type ProtoRecord
- type Provenance
- type Rendered
- type ResourceExhaustedError
- type ResourceExhaustedKind
- type RevertOutcome
- type RevertResult
- type ScopedCreateMemoryParams
- type ScopedEnrichMemoryParams
- type ScopedSearchParams
- type SearchParams
- type SearchResult
-
type Session
- func (s *Session) Close(ctx context.Context)
- func (s *Session) CreateMemory(ctx context.Context, p ScopedCreateMemoryParams) (*WriteResult, error)
- func (s *Session) EnrichMemory(ctx context.Context, p ScopedEnrichMemoryParams) (*WriteResult, error)
- func (s *Session) GetMemory(ctx context.Context, idx string) (*Memory, error)
- func (s *Session) ImportMemories(ctx context.Context, memories []ImportedMemory) (*ImportResult, error)
- func (s *Session) RevertMemory(ctx context.Context, operationID string) (*RevertResult, error)
- func (s *Session) Search(ctx context.Context, query string, p ScopedSearchParams) (*SearchResult, error)
- func (s *Session) ShareFeedback(ctx context.Context, feedback []FeedbackRating) (*FeedbackResult, error)
- func (s *Session) Tools() *Toolset
- type SessionOption
- type SunsetError
- type SunsetKind
- type Tag
- type TimeoutError
- type Tool
- type ToolDescriptor
- type ToolParameters
- type Toolset
- type UnavailableError
- type UnhealthyError
- type UpdateNetworkParams
- type UpdateUserParams
- type UserAlreadyAssignedNetworkError
-
type UserOperations
- func (u *UserOperations) Create(ctx context.Context, externalID string, p CreateUserParams) (*ExternalUser, error)
- func (u *UserOperations) CreateKey(ctx context.Context, externalID string, p CreateKeyParams) (*CreatedKey, error)
- func (u *UserOperations) Delete(ctx context.Context, externalID string) error
- func (u *UserOperations) DeleteKey(ctx context.Context, externalID, keyID string) error
- func (u *UserOperations) Get(ctx context.Context, externalID string) (*ExternalUser, error)
- func (u *UserOperations) List(ctx context.Context, p ListUsersParams) (*ExternalUserList, error)
- func (u *UserOperations) ListKeys(ctx context.Context, externalID string) ([]ExternalUserKey, error)
- func (u *UserOperations) Update(ctx context.Context, externalID string, p UpdateUserParams) (*ExternalUser, error)
- type WriteResult
Examples
- Briefing
- Client.Close
- Client.Connect
- Client.Provenance
- ExternalID
- Memory.Feedback
- MemoryOperations.CreateMemory
- MemoryOperations.EnrichMemory
- MemoryOperations.GetMemory
- MemoryOperations.ImportMemories
- MemoryOperations.ListDomains
- MemoryOperations.ListTools
- MemoryOperations.RevertMemory
- MemoryOperations.Search
- MemoryOperations.ShareFeedback
- MemoryOperations.StartSession
- NetworkOperations.AddGroup
- NetworkOperations.AddMember
- NetworkOperations.Create
- NetworkOperations.Delete
- NetworkOperations.List
- NetworkOperations.ListGroupMembers
- NetworkOperations.ListGroups
- NetworkOperations.ListMembers
- NetworkOperations.RemoveGroup
- NetworkOperations.RemoveMember
- NetworkOperations.Update
- NewClient
- ReadProvenance
- Render
- Session.Close
- Session.CreateMemory
- Session.EnrichMemory
- Session.GetMemory
- Session.ImportMemories
- Session.RevertMemory
- Session.Search
- Session.ShareFeedback
- Session.Tools
- SetLevel
- Tool.Call
- Toolset.Call
- Toolset.ToAnthropic
- Toolset.ToOpenAI
- UserOperations.Create
- UserOperations.CreateKey
- UserOperations.Delete
- UserOperations.DeleteKey
- UserOperations.Get
- UserOperations.List
- UserOperations.ListKeys
- UserOperations.Update
Constants
const ( // DefaultHost is the endpoint used when neither Options.Host nor // MEMCO_API_HOST names one. DefaultHost = "grpc.memco.ai" // DefaultPort is the port used when the host names none. DefaultPort = 443 // DefaultTimeout bounds a call whose context has no deadline. DefaultTimeout = 30 * time.Second // LogEnv names the environment variable that sets the SDK logger's level. LogEnv = "MEMCO_LOG" // DeprecationWarningName is the value of the "warning" attribute on a // deprecation notice's log record, for a handler to filter on. DeprecationWarningName = "MemcoDeprecationWarning" )
const NewMemory = "new"
NewMemory is the memory idx that opens a new memory when passed to an enrichment. It is case-sensitive: "New" is an ordinary handle.
const Version = "0.2.1"
Version is this SDK's release. Every call carries it in the user agent as memco-go/<Version>, and a release tag go-v<Version> must name it.
Functions
func Briefing
func Briefing(domain DomainEntry, instructions Instructions) string
Briefing turns what the service says about a domain into guidance for a model: what the domain holds, when to search and save, the tag vocabulary, and why list_domains and start_session are not among its tools.
Parameters:
- domain: the session's domain, from MemoryOperations.ListDomains.
- instructions: what the service said when the session opened, as Session.Instructions.
It returns the guidance, ready to be a system prompt or part of one.
Example
package main import ( "context" "fmt" "log" "github.com/memcoai/memcoai/go/memcoai" ) // These examples are compiled, not run: each needs a credential and the // service. They share the placeholders below, which a real program gets from // NewClient and StartSession, as ExampleNewClient shows. var ( ctx = context.Background() client *memcoai.Client ) func main() { listed, err := client.Memory.ListDomains(ctx) if err != nil { log.Fatal(err) } session, err := client.Memory.StartSession(ctx, "coding") if err != nil { log.Fatal(err) } for _, domain := range listed.Domains { if domain.Slug == "coding" { fmt.Println(memcoai.Briefing(domain, session.Instructions)) } } }
func IsAgentRecoverable
func IsAgentRecoverable(err error) bool
IsAgentRecoverable reports whether a tool hands err to the model as text rather than returning it: a malformed request, or a handle that resolves to nothing.
Parameters:
- err: an error an operation returned.
It returns true for an *InvalidRequestError or a *NotFoundError.
func Render
func Render(r Rendered) string
Render turns a result into text a model can read, including the guidance the service sent with it and the reliability signal on every insight.
Parameters:
- r: a result an operation returned; it must not be nil.
It returns the text.
Example
package main import ( "fmt" "github.com/memcoai/memcoai/go/memcoai" ) func main() { fmt.Println(memcoai.Render(memcoai.WriteResult{OperationID: "create-hpc08-1"})) }
Output:
accepted as operation create-hpc08-1
func SetLevel
func SetLevel(level string) error
SetLevel sets the level of the SDK's own logger, for the whole process. A client given Options.Logger is unaffected.
Parameters:
- level: critical, error, warning, info or debug, or none to silence the logger; case and surrounding space are ignored.
Errors: *ConfigError when level names none of these.
Example
package main import ( "log" "github.com/memcoai/memcoai/go/memcoai" ) func main() { if err := memcoai.SetLevel("debug"); err != nil { log.Fatal(err) } }
Types
type APIError
type APIError struct { // Code is the gRPC status code. Code codes.Code // Detail is the service's explanation, or the SDK's for a local refusal. Detail string // contains filtered or unexported fields }
APIError is a failure the service reported, or a request the SDK refused on the service's behalf. Every other API error type embeds it.
func (*APIError) Error
func (e *APIError) Error() string
Error returns the protocol's name for the code, then the detail, as in "INVALID_ARGUMENT: query must not be empty".
func (*APIError) Unwrap
func (e *APIError) Unwrap() error
Unwrap returns the context error that ended the call, if a context did.
type AddMemberParams
type AddMemberParams struct { // Force moves a user already placed in another network of the same // memory domain. Off, such a user is refused, so a move is never the // accidental outcome. Force bool }
AddMemberParams qualify NetworkOperations.AddMember.
type AlreadyExistsError
type AlreadyExistsError struct{ APIError }
AlreadyExistsError reports that what the call would create already exists, such as a network name or an external user id already taken. Retrying will not help: use what exists, or create it under another name.
func (*AlreadyExistsError) Unwrap
func (e *AlreadyExistsError) Unwrap() error
Unwrap returns the embedded APIError.
type AnthropicTool
type AnthropicTool struct { // Name is the tool's name. Name string `json:"name"` // Description is the tool's description. Description string `json:"description"` // InputSchema describes the tool's arguments. InputSchema ToolParameters `json:"input_schema"` }
AnthropicTool is a tool definition in the Claude Messages API's shape.
type AuthenticationError
type AuthenticationError struct{ APIError }
AuthenticationError reports a rejected credential. Retrying will not help.
func (*AuthenticationError) Unwrap
func (e *AuthenticationError) Unwrap() error
Unwrap returns the embedded APIError.
type Client
type Client struct { // Memory holds the memory service's operations. Memory *MemoryOperations // Networks holds the network administration. It needs an API client's // credentials; see [Options.ClientID]. Networks *NetworkOperations // Users holds the external-user administration. It needs an API client's // credentials; see [Options.ClientID]. Users *UserOperations // contains filtered or unexported fields }
Client is a connection to Memco Shared Memory. It is safe for concurrent use, and one client serves any number of calls at once.
func NewClient
func NewClient(opts Options) (*Client, error)
NewClient resolves the options and prepares a connection, without sending anything; Client.Connect proves the connection works.
Parameters:
- opts: the credential, endpoint, timeout and logging, each falling back to the environment and then to a default; see Options.
It returns a client that must be closed with Client.Close.
Errors: *ConfigError when no credential is found, a setting is blank or malformed, the timeout is negative, or the log level is not one.
Example
package main import ( "context" "fmt" "log" "github.com/memcoai/memcoai/go/memcoai" ) // These examples are compiled, not run: each needs a credential and the // service. They share the placeholders below, which a real program gets from // NewClient and StartSession, as ExampleNewClient shows. var ctx = context.Background() func main() { client, err := memcoai.NewClient(memcoai.Options{}) // reads MEMCO_API_TOKEN if err != nil { log.Fatal(err) } defer func() { if err := client.Close(ctx); err != nil { log.Print(err) } }() if err := client.Connect(ctx); err != nil { log.Fatal(err) } session, err := client.Memory.StartSession(ctx, "coding") if err != nil { log.Fatal(err) } fmt.Println(session.ID) }
func (*Client) Close
func (c *Client) Close(ctx context.Context) error
Close refuses new calls, waits for the calls in flight, ends the keys of impersonated sessions left open, then closes the connection. Closing again, or concurrently, is safe. A key that cannot be ended is not an error: a warning names the keys left, which expire on their own. After Close, closing a session does nothing.
Parameters:
- ctx: bounds the wait. When it ends first, the connection is closed anyway and the calls still in flight fail. It does not bound ending the keys, which together get Options.Timeout, so no key is left live because a caller gave up.
Errors: *TimeoutError or *InternalError when ctx ended before the calls in flight finished; either matches ctx's error with errors.Is. *InternalError when closing the connection fails.
Example
package main import ( "context" "log" "time" "github.com/memcoai/memcoai/go/memcoai" ) // These examples are compiled, not run: each needs a credential and the // service. They share the placeholders below, which a real program gets from // NewClient and StartSession, as ExampleNewClient shows. var client *memcoai.Client func main() { // Give calls in flight ten seconds to finish. ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) defer cancel() if err := client.Close(ctx); err != nil { log.Print("closed with calls still in flight: ", err) } }
func (*Client) Connect
func (c *Client) Connect(ctx context.Context) error
Connect proves the connection works. It probes the service's health, then proves the credential: a token by listing the domains, which also teaches the client the limits the service enforces; client credentials by exchanging them for a token, calling no memory method, since an issued token has no content role of its own. It may be called again after a failure, and reuses a token that is not yet due.
Parameters:
- ctx: bounds each of the two calls; without a deadline each gets Options.Timeout.
Errors: *UnavailableError when the service cannot be reached; *UnhealthyError when it answers but is not serving; *AuthenticationError when the credential is rejected; *SunsetError when what the client uses has stopped working; *ConfigError when the client is closed.
Example
package main import ( "context" "errors" "log" "github.com/memcoai/memcoai/go/memcoai" ) // These examples are compiled, not run: each needs a credential and the // service. They share the placeholders below, which a real program gets from // NewClient and StartSession, as ExampleNewClient shows. var ( ctx = context.Background() client *memcoai.Client ) func main() { err := client.Connect(ctx) var unhealthy *memcoai.UnhealthyError var unavailable *memcoai.UnavailableError switch { case errors.As(err, &unhealthy): log.Fatal("the service is up but not serving yet: ", err) case errors.As(err, &unavailable): log.Fatal("the service cannot be reached: ", err) case err != nil: log.Fatal(err) } }
func (*Client) Provenance
func (c *Client) Provenance() (Provenance, error)
Provenance reports the contract this SDK was generated from, as ReadProvenance does.
Errors: as ReadProvenance.
Example
package main import ( "context" "fmt" "log" "github.com/memcoai/memcoai/go/memcoai" ) // These examples are compiled, not run: each needs a credential and the // service. They share the placeholders below, which a real program gets from // NewClient and StartSession, as ExampleNewClient shows. var client *memcoai.Client func main() { provenance, err := client.Provenance() if err != nil { log.Fatal(err) } fmt.Println("built from", provenance.ServerCommit) }
type ConfigError
type ConfigError struct { // Message says what is wrong. Message string }
ConfigError reports a setting, or a closed client, that stopped a call before anything was sent.
One case is the exception: this machine's clock, running so far ahead of the service's that the key MemoryOperations.StartSession minted with ExternalID had already expired by it. There the mint was sent; the key it returned is ended at once. It arises only from a service that does not say how many seconds a key has left.
func (*ConfigError) Error
func (e *ConfigError) Error() string
Error returns the message.
type CreateKeyParams
type CreateKeyParams struct { // Preset is the kind of key: "mcp_rw", "mcp_ro" or "audit". It must be // within the user's roles. Required. Preset string // Name is a name to recognise the key by. Name string // ValidUntil is when the key expires, at most three months ahead; zero is // three months. ValidUntil time.Time }
CreateKeyParams describe a new API key for an external user.
type CreateMemoryParams
type CreateMemoryParams struct { // Query is what someone would search to find the memory. Required. Query string // Title is a short title for the memory. Required. Title string // Content is the knowledge being saved. Required. Content string // Domain is the domain to save into, when the write names no session. Domain string // SessionID is the session the memory was learned during, which also // names the domain. SessionID string // Tags describe the memory. Tags []Tag // Source is who produced the content; unset is the agent. Source DataSource }
CreateMemoryParams describe a new memory.
type CreateNetworkParams
type CreateNetworkParams struct { // Name is the network's name. Required. Name string // ParentID is the network to create this one under, read as ParentIDs // holding that one network. // // Deprecated: Set ParentIDs instead, never both. ParentID string // ParentIDs are the networks to create this one under, each named once and // all in one domain, which the new network takes; empty makes a root. ParentIDs []string // Domain is a root network's memory domain; empty is your organization's // default. A child names none. Domain string // Region is where the network's data resides; empty is your // organization's default, and "global" replicates everywhere. Region string // Scope is "internal" or "customer", where your organization uses scopes. // An external user can be placed only in a customer network. Scope string // Owner is who the network's knowledge belongs to. Owner string // Description says what the network is for. Description string }
CreateNetworkParams describe a new network: a root in a memory domain, or the child of other networks, whose domain it takes.
type CreateUserParams
type CreateUserParams struct { // Roles are the content roles the user holds, from "reader", "creator" // and "auditor". At least one is required. Roles []string // Name is the user's name. Name string // Email is the user's email address. Email string }
CreateUserParams describe a new external user.
type CreatedKey
type CreatedKey struct { // Key describes the key. Key ExternalUserKey // contains filtered or unexported fields }
CreatedKey is an API key just created, with its value. The value is shown here and never again, so store it now. Read it with CreatedKey.Value: it is kept out of everything that prints, logs or encodes a CreatedKey, with fmt, slog, encoding/json or encoding/xml, whatever the verb.
func (CreatedKey) Format
func (k CreatedKey) Format(f fmt.State, verb rune)
Format prints the key with its value redacted.
func (CreatedKey) LogValue
func (k CreatedKey) LogValue() slog.Value
LogValue logs the key with its value redacted.
func (CreatedKey) Value
func (k CreatedKey) Value() string
Value returns the key itself: the credential to hand over.
type DataSource
type DataSource int32
DataSource names who produced the content of a write.
const ( DataSourceUnspecified DataSource = 0 DataSourceUser DataSource = 1 DataSourceAgent DataSource = 2 )
The sources a write may name. The zero value is sent as DataSourceAgent.
func (DataSource) String
func (s DataSource) String() string
String names the source as the contract does, without its prefix.
type DeletedNetwork
type DeletedNetwork struct { // ID is the network deleted. ID string // Removed counts what the deletion took with the network, by kind, such // as "memories" or "network_members". Removed map[string]int64 }
DeletedNetwork is what NetworkOperations.Delete removed.
type DomainEntry
type DomainEntry struct { // Slug is the value a caller passes as a domain. Slug string // Title is the domain's display name. Title string // Summary says what the domain holds. Summary string // WhenToSearch says when to draw on the domain. WhenToSearch string // WhenToSave says what belongs in it. WhenToSave string // WhatNotToSave says what does not. WhatNotToSave string // TagsDescription describes the tag vocabulary. TagsDescription string // FilterTagTypes are the tag types that narrow results rather than boost // them, so a wrong one returns nothing. FilterTagTypes []string // VersionTagTypes are the tag types that carry a version; a version on any // other type is dropped. VersionTagTypes []string // MaxTagsPerQuery is how many tags a call naming this domain keeps; the SDK // trims the rest, as the service would. Zero means no cap. MaxTagsPerQuery int }
DomainEntry describes one memory domain: what it holds, when to draw on it, what belongs in it, and the tag vocabulary it uses.
type DomainList
type DomainList struct { // Domains are the domains the credential may name. Domains []DomainEntry // Instructions is the service's guidance on choosing a domain. Instructions Instructions // Limits are the caps the service enforces, or nil when it reported none. Limits *Limits // Deprecated reports that what the caller uses is superseded. It does not // say whether that is this SDK or the API version; DeprecationMessage does. Deprecated bool // DeprecationMessage is the service's remedy, empty when not deprecated. DeprecationMessage string // SunsetDate is when what the caller uses stops working, as YYYY-MM-DD, or // empty when the service named no date. SunsetDate string // ServerCommit names the build that answered. ServerCommit string }
DomainList is what MemoryOperations.ListDomains returns.
type EnrichMemoryParams
type EnrichMemoryParams struct { // MemoryIdx is the memory to add to, or [NewMemory]. Required. MemoryIdx string // SessionID is the session whose search returned the memory. Required. SessionID string // Title is a short title for the addition. Required. Title string // Content is the knowledge being added. Required. Content string // Tags describe the addition. Tags []Tag // Sources are handles of the memories the addition draws on. Sources []string // Source is who produced the content; unset is the agent. Source DataSource }
EnrichMemoryParams describe an addition to a memory.
type Error
type Error interface { error // contains filtered or unexported methods }
Error is implemented by every error this package returns. See the package documentation for the concrete types and when each is returned.
type ExternalUser
type ExternalUser struct { // ID is Memco's handle for the user, which [NetworkOperations.AddMember] // takes. ID string // ExternalID is your own id for the user, which [UserOperations] and // [ExternalID] take. ExternalID string // Name is the user's name, or empty. Name string // Email is the user's email address, or empty. Email string // Roles are the content roles the user holds, such as "reader" and // "creator". Roles []string // Active reports whether the user may act. Active bool }
ExternalUser is one of your own users, known to Memco by your id for them. It has no sign-in of its own: it acts through API keys, or through a session opened for it with ExternalID.
type ExternalUserKey
type ExternalUserKey struct { // ID is the key's handle. ID string // Name is the name the key was created with, or empty. Name string // ValuePrefix is the start of the key's value, to recognise it by. ValuePrefix string // Roles are the content roles the key acts with. Roles []string // Scopes are what the key may reach, such as "mcp:read". Scopes []string // ValidUntil is when the key expires, in UTC, or zero if it never does. ValidUntil time.Time }
ExternalUserKey describes an API key acting as an external user. The key's value is shown only once, in the CreatedKey that created it.
type ExternalUserList
type ExternalUserList struct { // ExternalUsers are the users on this page. ExternalUsers []ExternalUser // TotalCount is how many users match in all. TotalCount int64 }
ExternalUserList is one page of external users.
type ExternalUserNeedsCustomerNetworkError
type ExternalUserNeedsCustomerNetworkError struct { PreconditionFailedError // RequiredNetworkScope is the scope a network needs to take the user, // "customer", or empty if the service did not say. RequiredNetworkScope string }
ExternalUserNeedsCustomerNetworkError reports an external user placed in a network that is not a customer network, a domain's root included. Place the user in a customer network instead. It is also a *PreconditionFailedError.
func (*ExternalUserNeedsCustomerNetworkError) Unwrap
func (e *ExternalUserNeedsCustomerNetworkError) Unwrap() error
Unwrap returns the embedded PreconditionFailedError.
type FeedbackEntry
type FeedbackEntry struct { // Idx is the rated result's handle. Idx string // Relevant is the relevance recorded. Relevant bool // Correct is the correctness recorded, or nil when the rating left it out. Correct *bool // Advice is the suggestion this rating earned, or empty. Advice string }
FeedbackEntry is one rating the service recorded.
type FeedbackRating
type FeedbackRating struct { // Idx is the result's handle, copied from a search. A memory's idx rates // every insight under it. Required. Idx string // Relevant reports whether the result was a good match for the query. Relevant bool // Correct reports whether its content was accurate; nil leaves it out, // for when that cannot be judged. Correct *bool // Comment is an optional note about the result. Comment string }
FeedbackRating is one rating given to a search result.
type FeedbackResult
type FeedbackResult struct { // SessionID is the session the ratings were recorded under. SessionID string // Entries are the recorded ratings. Entries []FeedbackEntry // Instructions is the service's guidance on the ratings. Instructions Instructions }
FeedbackResult is what a rating call returned.
type Group
type Group struct { // ID is the group's handle. ID string // Name is the group's name. Name string // MemoryNetworkID is the network the group is assigned to, or empty. MemoryNetworkID string // MemberCount is how many users the group holds. MemberCount int64 }
Group is an identity-provider group, which places its members in networks. Groups are available to enterprise organizations only.
type GroupList
type GroupList struct { // Groups are the groups on this page. Groups []Group // TotalCount is how many groups match in all. TotalCount int64 }
GroupList is one page of groups.
type ImportMemoriesParams
type ImportMemoriesParams struct { // Domain is the domain to import into, when the import names no session. Domain string // SessionID records the import under an open session, which also names // the domain. SessionID string }
ImportMemoriesParams scope an import.
type ImportOutcome
type ImportOutcome struct { // Index is the memory's position in the batch the caller passed. Index int // Status is what became of it. Status ImportStatus // Errors say what was wrong with a memory that was not queued. Errors []string }
ImportOutcome is what became of one imported memory.
type ImportResult
type ImportResult struct { // Results hold one outcome per memory, in the order they were passed. Results []ImportOutcome // Instructions is the service's guidance on the import. Instructions Instructions }
ImportResult is what MemoryOperations.ImportMemories returned.
type ImportStatus
type ImportStatus int32
ImportStatus is what became of one memory of an import.
const ( ImportStatusUnspecified ImportStatus = 0 // ImportStatusQueued: accepted and queued for writing. ImportStatusQueued ImportStatus = 1 // ImportStatusRejected: the memory was not usable; its Errors say why. ImportStatusRejected ImportStatus = 2 // ImportStatusError: usable but not queued; sending it again is safe. ImportStatusError ImportStatus = 3 // ImportStatusDuplicate: already in memory, so nothing was written. ImportStatusDuplicate ImportStatus = 4 )
The statuses an imported memory reports.
func (ImportStatus) String
func (s ImportStatus) String() string
String names the status as the contract does, without its prefix.
type ImportedInsight
type ImportedInsight struct { // Title is the insight's title. Required. Title string // Content is what the insight says. Required. Content string }
ImportedInsight is one insight of a memory to import.
type ImportedMemory
type ImportedMemory struct { // Queries are what someone would search to find the memory; at least one. Queries []string // Insights are what the memory holds; at least one. Insights []ImportedInsight // Tags describe the memory. Tags []Tag }
ImportedMemory is one memory to import.
type Insight
type Insight struct { // Idx is the insight's handle; rating it rates this insight alone. Idx string // Title is the insight's title. Title string // Content is what the insight says. Content string // Updated is the day the insight was last written, as YYYY-MM-DD, or empty. Updated string // TimesServed counts deliveries, not correctness. TimesServed int64 // Endorsed counts ratings that found the insight correct. Endorsed int64 // Disputed counts ratings that found it wrong. Disputed int64 }
Insight is one insight held under a memory.
type Instructions
type Instructions struct { // Content states what the result is, or what happened. Content string // Policy explains how a policy result outranks the rest. Policy string // Adding says how to contribute back to what came back. Adding string // Rating says how to rate what came back. Rating string // Next names the follow-up call the result enables. Next string }
Instructions is the service's guidance accompanying a result, already written for its domain. A part with nothing to say is empty.
type InternalError
type InternalError struct{ APIError }
InternalError reports anything else, including a call cancelled through its context.
func (*InternalError) Unwrap
func (e *InternalError) Unwrap() error
Unwrap returns the embedded APIError.
type InvalidRequestError
type InvalidRequestError struct{ APIError }
InvalidRequestError reports a malformed request. The SDK raises many itself, before anything is sent.
func (*InvalidRequestError) Unwrap
func (e *InvalidRequestError) Unwrap() error
Unwrap returns the embedded APIError.
type JSONSchema
type JSONSchema = map[string]any
JSONSchema is one JSON Schema fragment, as a framework takes it.
type Limits
type Limits struct { // MaxQueryCharacters bounds a search or memory query, in characters. MaxQueryCharacters int // MaxTextCharacters bounds a title and its content together. MaxTextCharacters int // MaxIdxCharacters bounds every handle: idx, memory idx, source, operation id. MaxIdxCharacters int // MaxSources is how many sources an enrichment keeps; the SDK trims the rest. MaxSources int // MaxFeedbackEntries bounds the ratings in one call. MaxFeedbackEntries int // MaxImportMemories is how many memories one import call carries; the SDK // splits a larger batch into several calls. MaxImportMemories int // MaxImportQueriesPerMemory bounds one imported memory's queries. MaxImportQueriesPerMemory int // MaxImportInsightsPerMemory bounds one imported memory's insights. MaxImportInsightsPerMemory int // MaxImportTagsPerMemory bounds one imported memory's tags. MaxImportTagsPerMemory int }
Limits are the caps the service enforces, reported by MemoryOperations.ListDomains. Once they are known, the SDK refuses a call that would exceed one before sending it. Zero means the service reported no cap.
type ListGroupsParams
type ListGroupsParams struct { // Name keeps groups with this name, matched case-insensitively. Name string // NetworkID keeps groups assigned to this network. NetworkID string // IDs keeps only these groups. The service bounds how many one call may // name. IDs []string // Page is the page to return, counting from 1; zero is the first. Page int32 // PageSize is how many groups a page holds; zero is the service's // default. PageSize int32 }
ListGroupsParams narrow NetworkOperations.ListGroups. Every field is optional, and those given must all match.
type ListMembersParams
type ListMembersParams struct { // Search keeps members matching this text. Search string // Page is the page to return, counting from 1; zero is the first. Page int32 // PageSize is how many members a page holds; zero is the service's // default. PageSize int32 }
ListMembersParams narrow NetworkOperations.ListMembers.
type ListNetworksParams
type ListNetworksParams struct { // Name keeps networks with this name, matched case-insensitively. Name string // Scope keeps networks of this scope: "internal", "customer", or "none" // for networks without one. Scope string // Owner keeps networks with this owner, matched case-insensitively. Owner string // Domain keeps networks of this memory domain. Domain string // ParentID keeps the children of this network; "root" keeps the root // networks, one per memory domain. ParentID string // IDs keeps only these networks. The service bounds how many one call may // name. IDs []string // Page is the page to return, counting from 1; zero is the first. Page int32 // PageSize is how many networks a page holds; zero is the service's // default. PageSize int32 }
ListNetworksParams narrow NetworkOperations.List. Every field is optional, and those given must all match.
type ListUsersParams
type ListUsersParams struct { // Search keeps users whose external id, name or email matches this text, // case-insensitively. Search string // Page is the page to return, counting from 1; zero is the first. Page int32 // PageSize is how many users a page holds; zero is the service's default. PageSize int32 }
ListUsersParams narrow UserOperations.List.
type Member
type Member struct { // UserID is the user's handle: for an external user, [ExternalUser.ID]. UserID string // Email is the user's email address, or empty. Email string // Name is the user's name, or empty. Name string }
Member is a user placed in a network or a group.
type MemberList
type MemberList struct { // Members are the members on this page. Members []Member // TotalCount is how many members match in all. TotalCount int64 }
MemberList is one page of a network's members.
type MemberPlacement
type MemberPlacement struct { // NetworkID is the network the user is now in. NetworkID string // UserID is the user placed. UserID string // MovedFrom is the network the user was moved out of, or empty when the // placement moved nobody. MovedFrom string }
MemberPlacement is where NetworkOperations.AddMember placed a user.
type Memory
type Memory struct { // Idx is the memory's handle. Idx string // Kind is the memory's kind, such as "policy", or empty. Kind string // TimesServed counts deliveries, this one included. TimesServed int64 // Intents are the questions the memory has been retrieved by, oldest first. Intents []string // Insights are what the memory holds. Empty when Reference is set. Insights []Insight // Reference names the idx an earlier search in this session returned the // memory under, when it was returned there; [Session.GetMemory] fetches it // again. Reference string // contains filtered or unexported fields }
Memory is one memory a search or a fetch returned.
func (Memory) Feedback
func (m Memory) Feedback(ctx context.Context, feedback MemoryFeedback) (*FeedbackEntry, error)
Feedback rates this memory under the session that returned it, and returns the rating the service recorded.
Parameters:
- ctx: bounds the call; see the package documentation on contexts.
- feedback: the rating to give.
It returns the recorded rating, with any advice it earned.
Errors: *InvalidRequestError when the memory came from no session — one built by hand, or fetched with MemoryOperations.GetMemory; use Session.GetMemory instead. *InternalError when the service recorded no rating. Otherwise as MemoryOperations.ShareFeedback.
Example
package main import ( "context" "fmt" "log" "github.com/memcoai/memcoai/go/memcoai" ) // These examples are compiled, not run: each needs a credential and the // service. They share the placeholders below, which a real program gets from // NewClient and StartSession, as ExampleNewClient shows. var ( ctx = context.Background() client *memcoai.Client ) func main() { result, err := client.Memory.Search(ctx, "how are dates reported", memcoai.SearchParams{Domain: "coding"}) if err != nil { log.Fatal(err) } correct := true for _, memory := range result.Memories { entry, err := memory.Feedback(ctx, memcoai.MemoryFeedback{Relevant: true, Correct: &correct}) if err != nil { log.Fatal(err) } fmt.Println(entry.Advice) } }
type MemoryFeedback
type MemoryFeedback struct { // Relevant reports whether the memory was a good match for the query. Relevant bool // Correct reports whether its content was accurate; nil leaves it out, // for when that cannot be judged. Correct *bool // Comment is an optional note about the memory. Comment string }
MemoryFeedback is one rating of a memory, given through Memory.Feedback.
type MemoryOperations
type MemoryOperations struct { // contains filtered or unexported fields }
MemoryOperations are the memory service's operations, reached as Client.Memory. Most calls are easier through a Session, which supplies the session and the domain.
func (*MemoryOperations) CreateMemory
func (m *MemoryOperations) CreateMemory(ctx context.Context, p CreateMemoryParams) (*WriteResult, error)
CreateMemory saves new knowledge. The write is processed asynchronously, so the result names the operation rather than the memory it becomes, and the memory is not searchable straight away.
Parameters:
- ctx: bounds the call. Without a deadline, Options.Timeout applies; if ctx has already ended, nothing is sent.
- p: what to save and where. Query, Title and Content are required, and Domain or SessionID names the domain; a Source left unset is the agent.
It returns the operation's id, which MemoryOperations.RevertMemory undoes, or an empty id when the service could not mint one.
Errors: *InvalidRequestError when a required field is blank, the scope is missing, or the text is longer than the service allows (nothing is sent); *PermissionError when the credential may not write there; *ResourceExhaustedError; *ConfigError when the client is closed.
Example
package main import ( "context" "fmt" "log" "github.com/memcoai/memcoai/go/memcoai" ) // These examples are compiled, not run: each needs a credential and the // service. They share the placeholders below, which a real program gets from // NewClient and StartSession, as ExampleNewClient shows. var ( ctx = context.Background() client *memcoai.Client ) func main() { written, err := client.Memory.CreateMemory(ctx, memcoai.CreateMemoryParams{ Domain: "coding", Query: "why does the Go SDK dial with the dns scheme", Title: "A host named after a gRPC scheme is dialled as that scheme", Content: "grpc.NewClient reads unix:443 as a unix socket unless the target names dns:///.", Tags: []memcoai.Tag{{Type: "language", Value: "go"}}, }) if err != nil { log.Fatal(err) } fmt.Println("undo with", written.OperationID) }
func (*MemoryOperations) EnrichMemory
func (m *MemoryOperations) EnrichMemory(ctx context.Context, p EnrichMemoryParams) (*WriteResult, error)
EnrichMemory adds to a memory a search returned, or opens a new one.
Parameters:
- ctx: bounds the call. Without a deadline, Options.Timeout applies; if ctx has already ended, nothing is sent.
- p: what to add. MemoryIdx is a handle from a search in SessionID, or NewMemory; SessionID, Title and Content are required. Sources beyond the service's cap are dropped, as the service would.
It returns the operation's id, as MemoryOperations.CreateMemory does.
Errors: *InvalidRequestError when a required field or a source is blank, or a handle or the text is longer than the service allows (nothing is sent); *NotFoundError when the memory is not one the session returned; *PermissionError; *ResourceExhaustedError; *ConfigError when the client is closed.
Example
package main import ( "context" "fmt" "log" "github.com/memcoai/memcoai/go/memcoai" ) // These examples are compiled, not run: each needs a credential and the // service. They share the placeholders below, which a real program gets from // NewClient and StartSession, as ExampleNewClient shows. var ( ctx = context.Background() client *memcoai.Client ) func main() { written, err := client.Memory.EnrichMemory(ctx, memcoai.EnrichMemoryParams{ MemoryIdx: memcoai.NewMemory, SessionID: "session-hpc08", Title: "Retries cover reads only", Content: "The SDK retries ListDomains, GetMemory and ListTools, never a write.", }) if err != nil { log.Fatal(err) } fmt.Println(written.OperationID) }
func (*MemoryOperations) GetMemory
func (m *MemoryOperations) GetMemory(ctx context.Context, idx string) (*Memory, error)
GetMemory fetches the memory behind a handle a search returned, including one returned only as a reference. A memory fetched this way belongs to no session, so Memory.Feedback refuses it; fetch through Session.GetMemory to rate it.
Parameters:
- ctx: bounds the call. Without a deadline, Options.Timeout applies; if ctx has already ended, nothing is sent.
- idx: a memory's or an insight's handle, copied from a search; an insight's handle fetches the memory holding it.
It returns the memory.
Errors: *InvalidRequestError when idx is blank or longer than the service allows (nothing is sent); *NotFoundError when idx resolves to nothing; *ConfigError when the client is closed.
Example
package main import ( "context" "errors" "fmt" "log" "github.com/memcoai/memcoai/go/memcoai" ) // These examples are compiled, not run: each needs a credential and the // service. They share the placeholders below, which a real program gets from // NewClient and StartSession, as ExampleNewClient shows. var ( ctx = context.Background() client *memcoai.Client ) func main() { memory, err := client.Memory.GetMemory(ctx, "memory-hpc08-1") var notFound *memcoai.NotFoundError if errors.As(err, ¬Found) { fmt.Println("gone:", notFound.Detail) return } if err != nil { log.Fatal(err) } fmt.Println(memcoai.Render(memory)) }
func (*MemoryOperations) ImportMemories
func (m *MemoryOperations) ImportMemories(ctx context.Context, memories []ImportedMemory, p ImportMemoriesParams) (*ImportResult, error)
ImportMemories contributes many memories at once. Each is judged on its own, so a refused memory does not stop the others. A batch larger than the service's cap is sent as several calls, one after another, each group checked just before it is sent; an import has no operation id and cannot be undone.
Parameters:
- ctx: bounds the import. With a deadline, it bounds every call; without one, each call gets Options.Timeout. Once ctx ends, no further group is sent.
- memories: the memories to import, each with at least one query and one insight.
- p: Domain or SessionID names the domain every memory is imported into.
It returns one outcome per memory, indexed by its position in memories.
Errors: *InvalidRequestError when the scope is missing, memories is empty, or a memory is incomplete or larger than the service allows, naming the memory by position (groups before it have already been sent); *PermissionError; *ResourceExhaustedError; *TimeoutError or *InternalError when ctx ended between groups; *ConfigError when the client is closed.
Example
package main import ( "context" "fmt" "log" "github.com/memcoai/memcoai/go/memcoai" ) // These examples are compiled, not run: each needs a credential and the // service. They share the placeholders below, which a real program gets from // NewClient and StartSession, as ExampleNewClient shows. var ( ctx = context.Background() client *memcoai.Client ) func main() { imported, err := client.Memory.ImportMemories(ctx, []memcoai.ImportedMemory{{ Queries: []string{"how are Go SDK releases tagged"}, Insights: []memcoai.ImportedInsight{{Title: "go/vX.Y.Z", Content: "A module in go/ is tagged go/vX.Y.Z."}}, }}, memcoai.ImportMemoriesParams{Domain: "coding"}) if err != nil { log.Fatal(err) } for _, outcome := range imported.Results { fmt.Println(outcome.Index, outcome.Status, outcome.Errors) } }
func (*MemoryOperations) ListDomains
func (m *MemoryOperations) ListDomains(ctx context.Context) (*DomainList, error)
ListDomains lists the memory domains the credential may name, with the limits the service enforces. The client remembers those limits and checks later calls against them before sending, and surfaces a deprecation notice the first time the service reports one. Reads are retried when the service is briefly unavailable.
Parameters:
- ctx: bounds the call. Without a deadline, Options.Timeout applies; if ctx has already ended, nothing is sent.
It returns the domains, what each holds and the tags it uses, the limits, and any deprecation notice.
Errors: *AuthenticationError when the credential is rejected; *SunsetError when what the client uses has stopped working; *UnavailableError when the service cannot be reached; *ConfigError when the client is closed.
Example
package main import ( "context" "fmt" "log" "github.com/memcoai/memcoai/go/memcoai" ) // These examples are compiled, not run: each needs a credential and the // service. They share the placeholders below, which a real program gets from // NewClient and StartSession, as ExampleNewClient shows. var ( ctx = context.Background() client *memcoai.Client ) func main() { listed, err := client.Memory.ListDomains(ctx) if err != nil { log.Fatal(err) } for _, domain := range listed.Domains { fmt.Println(domain.Slug, "-", domain.Summary) } }
func (*MemoryOperations) ListTools
func (m *MemoryOperations) ListTools(ctx context.Context) ([]ToolDescriptor, error)
ListTools lists every method the service declares, and which the credential's role permits. MemoryOperations.StartSession fetches this for Session.Tools already.
Parameters:
- ctx: bounds the call. Without a deadline, Options.Timeout applies; if ctx has already ended, nothing is sent.
It returns one descriptor per method.
Errors: *AuthenticationError when the credential is rejected; *UnavailableError when the service cannot be reached; *ConfigError when the client is closed.
Example
package main import ( "context" "fmt" "log" "github.com/memcoai/memcoai/go/memcoai" ) // These examples are compiled, not run: each needs a credential and the // service. They share the placeholders below, which a real program gets from // NewClient and StartSession, as ExampleNewClient shows. var ( ctx = context.Background() client *memcoai.Client ) func main() { tools, err := client.Memory.ListTools(ctx) if err != nil { log.Fatal(err) } for _, tool := range tools { fmt.Println(tool.Name, tool.Available) } }
func (*MemoryOperations) RevertMemory
func (m *MemoryOperations) RevertMemory(ctx context.Context, operationID string) (*RevertResult, error)
RevertMemory undoes the caller's own write. A write not yet processed, too old, or under moderation is reported in the result's Outcome, not as an error.
Parameters:
- ctx: bounds the call. Without a deadline, Options.Timeout applies; if ctx has already ended, nothing is sent.
- operationID: the id MemoryOperations.CreateMemory or MemoryOperations.EnrichMemory returned.
It returns what the revert removed.
Errors: *InvalidRequestError when operationID is blank or longer than the service allows (nothing is sent); *PermissionError; *ConfigError when the client is closed.
Example
package main import ( "context" "fmt" "log" "github.com/memcoai/memcoai/go/memcoai" ) // These examples are compiled, not run: each needs a credential and the // service. They share the placeholders below, which a real program gets from // NewClient and StartSession, as ExampleNewClient shows. var ( ctx = context.Background() client *memcoai.Client ) func main() { reverted, err := client.Memory.RevertMemory(ctx, "create-hpc08-1") if err != nil { log.Fatal(err) } if reverted.Outcome == memcoai.RevertOutcomeNotFound { fmt.Println("not processed yet, or never written") } }
func (*MemoryOperations) Search
func (m *MemoryOperations) Search(ctx context.Context, query string, p SearchParams) (*SearchResult, error)
Search retrieves memories for a task-based query. It is not retried: an unscoped search opens a session, and a replayed one would open another.
Parameters:
- ctx: bounds the call. Without a deadline, Options.Timeout applies; if ctx has already ended, nothing is sent.
- query: what to find, such as a question or a task description.
- p: where to search and how to narrow it. Domain or SessionID is required; tags beyond the domain's cap are dropped, as the service would.
It returns the memories selected, and the session the search was recorded under: p.SessionID, or a new session when only p.Domain was given. Rate the results with Memory.Feedback or MemoryOperations.ShareFeedback.
Errors: *InvalidRequestError when query is blank or longer than the service allows, when p names no domain and no session, or when a tag is blank (nothing is sent); *PermissionError; *ResourceExhaustedError when a rate limit or quota is spent; *ConfigError when the client is closed.
Example
package main import ( "context" "fmt" "log" "github.com/memcoai/memcoai/go/memcoai" ) // These examples are compiled, not run: each needs a credential and the // service. They share the placeholders below, which a real program gets from // NewClient and StartSession, as ExampleNewClient shows. var ( ctx = context.Background() client *memcoai.Client ) func main() { result, err := client.Memory.Search(ctx, "how should a client authenticate", memcoai.SearchParams{ Domain: "coding", Tags: []memcoai.Tag{{Type: "language", Value: "go"}}, }) if err != nil { log.Fatal(err) } for _, memory := range result.Memories { for _, insight := range memory.Insights { fmt.Println(insight.Title, insight.Updated) } } }
func (*MemoryOperations) ShareFeedback
func (m *MemoryOperations) ShareFeedback(ctx context.Context, sessionID string, feedback []FeedbackRating) (*FeedbackResult, error)
ShareFeedback rates the results of a search. Ratings are what move the reliability signal on an insight.
Parameters:
- ctx: bounds the call. Without a deadline, Options.Timeout applies; if ctx has already ended, nothing is sent.
- sessionID: the session the rated search was recorded under.
- feedback: one rating per result; at least one, with a handle copied from the search.
It returns the ratings the service recorded, with any advice they earned.
Errors: *InvalidRequestError when sessionID or a handle is blank, feedback is empty, or it holds more ratings than the service allows (nothing is sent); *NotFoundError when a handle is not one the session returned; *ConfigError when the client is closed.
func (*MemoryOperations) StartSession
func (m *MemoryOperations) StartSession(ctx context.Context, domain string, opts ...SessionOption) (*Session, error)
StartSession opens a session in a domain. Every call made through the session is recorded under it, which is what relates the searches of one task and lets their results be rated.
Parameters:
- ctx: bounds the call. Without a deadline, Options.Timeout applies; if ctx has already ended, nothing is sent. The session and the tool catalog are fetched concurrently, and neither call outlives this one.
- domain: the slug of a domain MemoryOperations.ListDomains listed.
- opts: ExternalID to open the session acting as one of your own users, which mints a key for them first, lists the domains under it, and then starts the session under it. Such a session must be closed with Session.Close.
It returns the open session. When the tool catalog cannot be fetched, the session still opens and Session.Tools offers every tool; a warning is logged.
Errors: *InvalidRequestError when domain or the external id is blank (nothing is sent); *PermissionError when the credential may not use the domain, or may not act for users; *NotFoundError when there is no such domain or user; *ConfigError when the client is closed. With ExternalID, a failure after the key was minted ends the key. From a service that does not yet say how many seconds a key has left, a *ConfigError naming the clock says this machine's clock runs so far ahead of the service's that the key minted had already expired by it.
Example
package main import ( "context" "fmt" "log" "github.com/memcoai/memcoai/go/memcoai" ) // These examples are compiled, not run: each needs a credential and the // service. They share the placeholders below, which a real program gets from // NewClient and StartSession, as ExampleNewClient shows. var ( ctx = context.Background() client *memcoai.Client ) func main() { session, err := client.Memory.StartSession(ctx, "coding") if err != nil { log.Fatal(err) } fmt.Println(session.ID, session.Instructions.Content) }
type Network
type Network struct { // ID is the network's handle. ID string // Name is the network's name. Name string // ParentID is the first of ParentIDs, or empty for a root. // // Deprecated: Read ParentIDs; a network may have several parents. ParentID string // ParentIDs are the networks this one hangs under, empty for a root. ParentIDs []string // Domain is the memory domain the network belongs to. Domain string // Region is where the network's data resides. Region string // Scope is "internal" or "customer", or empty where the organization // uses no scopes. Scope string // Owner is who the network's knowledge belongs to, or empty. Owner string // Description says what the network is for, or is empty. Description string }
Network is a memory network: where an organization places its people, and so what knowledge each of them can find. A root network sits in a memory domain; every other network hangs under one or more parents and takes their domain.
type NetworkList
type NetworkList struct { // Networks are the networks on this page. Networks []Network // TotalCount is how many networks match in all. TotalCount int64 }
NetworkList is one page of networks.
type NetworkOperations
type NetworkOperations struct { // contains filtered or unexported fields }
NetworkOperations manage your organization's memory networks, their members and their identity-provider groups, reached as Client.Networks. Every call is made under the token the client is issued for an API client's credentials (Options.ClientID), and is bounded by the scopes that API client was granted.
func (*NetworkOperations) AddGroup
func (n *NetworkOperations) AddGroup(ctx context.Context, networkID, groupID string) error
AddGroup assigns an identity-provider group to a network, placing its members there. A group holds one network per memory domain, so this replaces the group's network in this network's domain.
Parameters:
- ctx: bounds the call. Without a deadline, Options.Timeout applies; if ctx has already ended, nothing is sent.
- networkID: the network to assign the group to.
- groupID: the group to assign.
Errors: *InvalidRequestError when networkID or groupID is blank (nothing is sent); *PermissionError outside an enterprise organization; *NotFoundError; *ConfigError when the client is closed.
Example
package main import ( "context" "log" "github.com/memcoai/memcoai/go/memcoai" ) // These examples are compiled, not run: each needs a credential and the // service. They share the placeholders below, which a real program gets from // NewClient and StartSession, as ExampleNewClient shows. var ( ctx = context.Background() client *memcoai.Client ) func main() { if err := client.Networks.AddGroup(ctx, "network-support", "group-support"); err != nil { log.Fatal(err) } }
func (*NetworkOperations) AddMember
func (n *NetworkOperations) AddMember(ctx context.Context, networkID, userID string, p AddMemberParams) (*MemberPlacement, error)
AddMember places a user in a network. A user holds one network per memory domain: one already placed in another network of the same domain is refused, naming that network, unless p.Force moves them. An external user can be placed only in a customer network.
Parameters:
- ctx: bounds the call. Without a deadline, Options.Timeout applies; if ctx has already ended, nothing is sent.
- networkID: the network to place the user in.
- userID: the user to place; for an external user, ExternalUser.ID, not your own id for them.
- p: whether to move a user placed elsewhere.
It returns where the user was placed, and the network they were moved out of, if any.
Errors: *InvalidRequestError when networkID or userID is blank (nothing is sent); *UserAlreadyAssignedNetworkError when the user is in another network of the domain and p.Force is off; *ExternalUserNeedsCustomerNetworkError when an external user meets a network that is not a customer one; *NotFoundError; *ConfigError when the client is closed.
Example
package main import ( "context" "errors" "fmt" "log" "github.com/memcoai/memcoai/go/memcoai" ) // These examples are compiled, not run: each needs a credential and the // service. They share the placeholders below, which a real program gets from // NewClient and StartSession, as ExampleNewClient shows. var ( ctx = context.Background() client *memcoai.Client ) func main() { user, err := client.Users.Get(ctx, "customer-42") if err != nil { log.Fatal(err) } _, err = client.Networks.AddMember(ctx, "network-acme", user.ID, memcoai.AddMemberParams{}) var assigned *memcoai.UserAlreadyAssignedNetworkError if errors.As(err, &assigned) { // Placed elsewhere in this domain: moving them has to be asked for. fmt.Println("moving them out of", assigned.CurrentNetworkName) _, err = client.Networks.AddMember(ctx, "network-acme", user.ID, memcoai.AddMemberParams{Force: true}) } if err != nil { log.Fatal(err) } }
func (*NetworkOperations) Create
func (n *NetworkOperations) Create(ctx context.Context, p CreateNetworkParams) (*Network, error)
Create creates a memory network.
Parameters:
- ctx: bounds the call. Without a deadline, Options.Timeout applies; if ctx has already ended, nothing is sent.
- p: the network to create. Name is required; ParentIDs place it under other networks, and Scope "customer" lets it take external users.
It returns the network as created.
Errors: *AlreadyExistsError when the name is already taken; *InvalidRequestError when the service refuses a field; *PermissionError; *ConfigError when the client is closed.
Example
package main import ( "context" "fmt" "log" "github.com/memcoai/memcoai/go/memcoai" ) // These examples are compiled, not run: each needs a credential and the // service. They share the placeholders below, which a real program gets from // NewClient and StartSession, as ExampleNewClient shows. var ( ctx = context.Background() client *memcoai.Client ) func main() { acme, err := client.Networks.Create(ctx, memcoai.CreateNetworkParams{ Name: "Acme", ParentIDs: []string{"network-root"}, Scope: "customer", }) if err != nil { log.Fatal(err) } fmt.Println(acme.ID, acme.Domain) // the domain is taken from the parent }
func (*NetworkOperations) Delete
func (n *NetworkOperations) Delete(ctx context.Context, networkID string) (*DeletedNetwork, error)
Delete deletes a network, and everything that hangs off it. It cannot be undone.
Parameters:
- ctx: bounds the call. Without a deadline, Options.Timeout applies; if ctx has already ended, nothing is sent.
- networkID: the network to delete.
It returns the network deleted, and how much the deletion took with it.
Errors: *InvalidRequestError when networkID is blank (nothing is sent); *NotFoundError; *ConfigError when the client is closed.
Example
package main import ( "context" "fmt" "log" "github.com/memcoai/memcoai/go/memcoai" ) // These examples are compiled, not run: each needs a credential and the // service. They share the placeholders below, which a real program gets from // NewClient and StartSession, as ExampleNewClient shows. var ( ctx = context.Background() client *memcoai.Client ) func main() { deleted, err := client.Networks.Delete(ctx, "network-acme") if err != nil { log.Fatal(err) } fmt.Println(deleted.Removed["memories"], "memories went with it") }
func (*NetworkOperations) List
func (n *NetworkOperations) List(ctx context.Context, p ListNetworksParams) (*NetworkList, error)
List lists one page of your organization's memory networks, narrowed by the filters given.
Parameters:
- ctx: bounds the call. Without a deadline, Options.Timeout applies; if ctx has already ended, nothing is sent.
- p: the filters and the page; the zero value lists the first page of every network.
It returns the page of networks, and how many match in all.
Errors: *PermissionError when the credential may not manage networks; *ConfigError when the client is closed. See Error for the rest.
Example
package main import ( "context" "fmt" "log" "github.com/memcoai/memcoai/go/memcoai" ) // These examples are compiled, not run: each needs a credential and the // service. They share the placeholders below, which a real program gets from // NewClient and StartSession, as ExampleNewClient shows. var ( ctx = context.Background() client *memcoai.Client ) func main() { roots, err := client.Networks.List(ctx, memcoai.ListNetworksParams{ParentID: "root", Domain: "coding"}) if err != nil { log.Fatal(err) } for _, network := range roots.Networks { fmt.Println(network.ID, network.Name) } }
func (*NetworkOperations) ListGroupMembers
func (n *NetworkOperations) ListGroupMembers(ctx context.Context, groupID string) ([]Member, error)
ListGroupMembers lists the users in an identity-provider group. The identity provider decides who is in a group; this only reads it.
Parameters:
- ctx: bounds the call. Without a deadline, Options.Timeout applies; if ctx has already ended, nothing is sent.
- groupID: the group whose members to list.
It returns the group's members.
Errors: *InvalidRequestError when groupID is blank (nothing is sent); *PermissionError outside an enterprise organization; *NotFoundError; *ConfigError when the client is closed.
Example
package main import ( "context" "fmt" "log" "github.com/memcoai/memcoai/go/memcoai" ) // These examples are compiled, not run: each needs a credential and the // service. They share the placeholders below, which a real program gets from // NewClient and StartSession, as ExampleNewClient shows. var ( ctx = context.Background() client *memcoai.Client ) func main() { members, err := client.Networks.ListGroupMembers(ctx, "group-support") if err != nil { log.Fatal(err) } for _, member := range members { fmt.Println(member.Email) } }
func (*NetworkOperations) ListGroups
func (n *NetworkOperations) ListGroups(ctx context.Context, p ListGroupsParams) (*GroupList, error)
ListGroups lists one page of your organization's identity-provider groups. Groups are available to enterprise organizations only; the service refuses the call for any other.
Parameters:
- ctx: bounds the call. Without a deadline, Options.Timeout applies; if ctx has already ended, nothing is sent.
- p: the filters and the page; the zero value lists the first page of every group.
It returns the page of groups, and how many match in all.
Errors: *PermissionError outside an enterprise organization; *ConfigError when the client is closed. See Error for the rest.
Example
package main import ( "context" "errors" "fmt" "log" "github.com/memcoai/memcoai/go/memcoai" ) // These examples are compiled, not run: each needs a credential and the // service. They share the placeholders below, which a real program gets from // NewClient and StartSession, as ExampleNewClient shows. var ( ctx = context.Background() client *memcoai.Client ) func main() { page, err := client.Networks.ListGroups(ctx, memcoai.ListGroupsParams{Name: "Support"}) var denied *memcoai.PermissionError if errors.As(err, &denied) { log.Fatal("groups are for enterprise organizations: ", err) } if err != nil { log.Fatal(err) } for _, group := range page.Groups { fmt.Println(group.ID, group.MemberCount) } }
func (*NetworkOperations) ListMembers
func (n *NetworkOperations) ListMembers(ctx context.Context, networkID string, p ListMembersParams) (*MemberList, error)
ListMembers lists one page of the users placed in a network.
Parameters:
- ctx: bounds the call. Without a deadline, Options.Timeout applies; if ctx has already ended, nothing is sent.
- networkID: the network whose members to list.
- p: a search and the page; the zero value lists the first page.
It returns the page of members, and how many match in all.
Errors: *InvalidRequestError when networkID is blank (nothing is sent); *NotFoundError; *ConfigError when the client is closed.
Example
package main import ( "context" "fmt" "log" "github.com/memcoai/memcoai/go/memcoai" ) // These examples are compiled, not run: each needs a credential and the // service. They share the placeholders below, which a real program gets from // NewClient and StartSession, as ExampleNewClient shows. var ( ctx = context.Background() client *memcoai.Client ) func main() { page, err := client.Networks.ListMembers(ctx, "network-acme", memcoai.ListMembersParams{Search: "ada"}) if err != nil { log.Fatal(err) } for _, member := range page.Members { fmt.Println(member.UserID, member.Email) } }
func (*NetworkOperations) RemoveGroup
func (n *NetworkOperations) RemoveGroup(ctx context.Context, networkID, groupID string) error
RemoveGroup takes an identity-provider group out of a network. The group's networks in other memory domains are unaffected.
Parameters:
- ctx: bounds the call. Without a deadline, Options.Timeout applies; if ctx has already ended, nothing is sent.
- networkID: the network to take the group out of.
- groupID: the group to take out.
Errors: *InvalidRequestError when networkID or groupID is blank (nothing is sent); *PermissionError outside an enterprise organization; *NotFoundError; *ConfigError when the client is closed.
Example
package main import ( "context" "log" "github.com/memcoai/memcoai/go/memcoai" ) // These examples are compiled, not run: each needs a credential and the // service. They share the placeholders below, which a real program gets from // NewClient and StartSession, as ExampleNewClient shows. var ( ctx = context.Background() client *memcoai.Client ) func main() { if err := client.Networks.RemoveGroup(ctx, "network-support", "group-support"); err != nil { log.Fatal(err) } }
func (*NetworkOperations) RemoveMember
func (n *NetworkOperations) RemoveMember(ctx context.Context, networkID, userID string) error
RemoveMember takes a user out of a network.
Parameters:
- ctx: bounds the call. Without a deadline, Options.Timeout applies; if ctx has already ended, nothing is sent.
- networkID: the network to take the user out of.
- userID: the user to take out.
Errors: *InvalidRequestError when networkID or userID is blank (nothing is sent); *NotFoundError; *ConfigError when the client is closed.
Example
package main import ( "context" "log" "github.com/memcoai/memcoai/go/memcoai" ) // These examples are compiled, not run: each needs a credential and the // service. They share the placeholders below, which a real program gets from // NewClient and StartSession, as ExampleNewClient shows. var ( ctx = context.Background() client *memcoai.Client ) func main() { if err := client.Networks.RemoveMember(ctx, "network-acme", "user-a"); err != nil { log.Fatal(err) } }
func (*NetworkOperations) Update
func (n *NetworkOperations) Update(ctx context.Context, networkID string, p UpdateNetworkParams) (*Network, error)
Update changes a network's name, parent, scope, owner or description. Only the fields given change.
Parameters:
- ctx: bounds the call. Without a deadline, Options.Timeout applies; if ctx has already ended, nothing is sent.
- networkID: the network to change.
- p: the changes; a nil field is left as it is, and a pointer to "" clears the field. A pointer to an empty ParentIDs makes the network a root.
It returns the network as it now is.
Errors: *InvalidRequestError when networkID is blank (nothing is sent); *PreconditionFailedError when the change is not allowed as things stand, such as making a network holding external users internal; *NotFoundError; *ConfigError when the client is closed.
Example
package main import ( "context" "log" "github.com/memcoai/memcoai/go/memcoai" ) // These examples are compiled, not run: each needs a credential and the // service. They share the placeholders below, which a real program gets from // NewClient and StartSession, as ExampleNewClient shows. var ( ctx = context.Background() client *memcoai.Client ) func main() { name, description := "Acme Corp", "" // an empty description clears it if _, err := client.Networks.Update(ctx, "network-acme", memcoai.UpdateNetworkParams{ Name: &name, Description: &description, }); err != nil { log.Fatal(err) } }
type NotFoundError
type NotFoundError struct{ APIError }
NotFoundError reports a handle that resolves to nothing.
func (*NotFoundError) Unwrap
func (e *NotFoundError) Unwrap() error
Unwrap returns the embedded APIError.
type OpenAIFunction
type OpenAIFunction struct { // Name is the tool's name. Name string `json:"name"` // Description is the tool's description. Description string `json:"description"` // Parameters describes the tool's arguments. Parameters ToolParameters `json:"parameters"` }
OpenAIFunction is the function an OpenAITool describes.
type OpenAITool
type OpenAITool struct { // Type is always "function". Type string `json:"type"` // Function describes the tool. Function OpenAIFunction `json:"function"` }
OpenAITool is a tool definition in the OpenAI Chat Completions API's shape.
type Options
type Options struct { // Token is the credential: an API key or a session token. Empty reads // the environment: a complete MEMCO_CLIENT_ID and MEMCO_CLIENT_SECRET pair // if both are set, else MEMCO_API_TOKEN, then the deprecated MEMCO_API_KEY. // A token of only whitespace is refused, and so is a token beside // ClientID or ClientSecret. Token string // ClientID is an API client's id, set with ClientSecret instead of a // Token. The client exchanges the pair for a token, renews it before it // expires, and calls no memory method to connect: an issued token has no // content role of its own. [Client.Networks] and [Client.Users] need one, // as does a session opened with [ExternalID]. ClientID string // ClientSecret is the API client's secret, set with ClientID. It is sent // only to exchange for a token, and never logged or printed. ClientSecret string // TokenLifetime is the lifetime to ask for on each token issued for the // client credentials, in whole seconds. Zero takes the service's default; // the service owns the maximum, and refuses a longer one. Only valid with // client credentials. TokenLifetime time.Duration // Host is the endpoint, as host, host:port, [ipv6]:port or a bare IPv6 // address. Empty reads MEMCO_API_HOST, then uses [DefaultHost]; a host of // only whitespace is refused. Without a port, [DefaultPort] is used. Host string // TLS says whether to dial over TLS, with the system's trust store. Nil // leaves it to MEMCO_API_TLS: "false" turns TLS off, and "true" or unset // keeps it on. A pointer to true keeps TLS on whatever the environment // says; a pointer to false turns it off, only for a local endpoint such as // a development server. A client without TLS logs a warning as it is // built, since its credentials cross the wire readable. TLS *bool // Plaintext dials without TLS when true, as it did before [Options.TLS] // existed. False leaves the choice to TLS. Setting it beside TLS true is // refused. // // Deprecated: Set TLS to a pointer to false instead. Plaintext bool // Timeout bounds a call whose context has no deadline, from its start: // waiting for a credential, if one must be renewed first, and the request // share it. Zero uses [DefaultTimeout]; a negative timeout is refused. Timeout time.Duration // LogLevel sets the SDK logger's level before anything else, as // [SetLevel] does, for the whole process. Empty leaves it alone. LogLevel string // Logger receives this client's log records instead of the SDK's own // logger. Its handler decides which levels it keeps. Logger *slog.Logger }
Options configures a Client. The zero value of every field means unset, so Options{} reads everything from the environment.
Printing, logging or encoding Options, with fmt, slog, encoding/json or encoding/xml, redacts Token and ClientSecret. A verb fmt cannot apply, such as %w, prints the fields raw instead; go vet reports that misuse.
func (Options) Format
func (o Options) Format(f fmt.State, verb rune)
Format prints the options with any token or secret redacted, whatever the verb.
func (Options) LogValue
func (o Options) LogValue() slog.Value
LogValue logs the options with any token or secret redacted.
func (Options) MarshalJSON
func (o Options) MarshalJSON() ([]byte, error)
MarshalJSON encodes the options with any token or secret redacted.
func (Options) MarshalXML
func (o Options) MarshalXML(e *xml.Encoder, start xml.StartElement) error
MarshalXML encodes the options with any token or secret redacted.
type PermissionError
type PermissionError struct{ APIError }
PermissionError reports a credential not allowed to do what was asked.
func (*PermissionError) Unwrap
func (e *PermissionError) Unwrap() error
Unwrap returns the embedded APIError.
type PreconditionFailedError
type PreconditionFailedError struct { APIError // Reason is the name the service gave the refusal, such as // "USER_ALREADY_ASSIGNED_NETWORK", or empty when it gave none. Reason string // Metadata is the detail the service attached to the refusal, key to // value, such as the network a user is already in; nil when it attached // none. A key this SDK does not name is kept too. Metadata map[string]string }
PreconditionFailedError reports an account or request in a state that does not allow the call, such as disabled billing. Retrying will not help until something outside the request changes. The refusals the service names by a reason this SDK knows are subtypes: *SunsetError, *UserAlreadyAssignedNetworkError and *ExternalUserNeedsCustomerNetworkError.
func (*PreconditionFailedError) Unwrap
func (e *PreconditionFailedError) Unwrap() error
Unwrap returns the embedded APIError.
type ProtoRecord
type ProtoRecord struct { // Path is the file's path in the contract. Path string // SHA256 is the file's checksum. SHA256 string }
ProtoRecord is one contract file this SDK was generated from.
type Provenance
type Provenance struct { // ServerCommit is the service build the contract was exported from. ServerCommit string // Protos are the contract files. Protos []ProtoRecord }
Provenance names the contract this SDK was generated from, for a bug report.
func ReadProvenance
func ReadProvenance() (Provenance, error)
ReadProvenance reports the contract this SDK was generated from, for a bug report. It needs no client and sends nothing.
It returns the service build and the contract files, with their checksums.
Errors: *ConfigError when the record built into the SDK cannot be read, which means the module is broken.
Example
package main import ( "fmt" "log" "github.com/memcoai/memcoai/go/memcoai" ) func main() { provenance, err := memcoai.ReadProvenance() if err != nil { log.Fatal(err) } for _, proto := range provenance.Protos { fmt.Println(proto.Path, proto.SHA256) } }
type Rendered
type Rendered interface { // contains filtered or unexported methods }
Rendered is a result Render can turn into text: a SearchResult, Memory, WriteResult, FeedbackResult or RevertResult, or a pointer to one.
type ResourceExhaustedError
type ResourceExhaustedError struct { APIError // Kind says which allowance ran out. Kind ResourceExhaustedKind }
ResourceExhaustedError reports a spent rate limit or quota. The SDK does not retry it.
func (*ResourceExhaustedError) Unwrap
func (e *ResourceExhaustedError) Unwrap() error
Unwrap returns the embedded APIError.
type ResourceExhaustedKind
type ResourceExhaustedKind string
ResourceExhaustedKind says which allowance ran out.
const ( // ResourceExhaustedRateLimit: a short window; retrying after a pause helps. ResourceExhaustedRateLimit ResourceExhaustedKind = "rate_limit" // ResourceExhaustedQuota: a daily, weekly or monthly allowance; retrying // will not help until it resets. ResourceExhaustedQuota ResourceExhaustedKind = "quota" // ResourceExhaustedUnknown: the wording named neither; treat it as a rate // limit. ResourceExhaustedUnknown ResourceExhaustedKind = "unknown" )
The kinds of exhaustion, read from the service's wording.
type RevertOutcome
type RevertOutcome int32
RevertOutcome reports what a revert removed. Every outcome is a successful call: not found, expired and refused describe a state, not a failure.
const ( RevertOutcomeUnspecified RevertOutcome = 0 // RevertOutcomeMemoryRemoved: the insight was its memory's last, so the // memory went with it. RevertOutcomeMemoryRemoved RevertOutcome = 1 // RevertOutcomeAdditionRemoved: only the caller's insight was removed. RevertOutcomeAdditionRemoved RevertOutcome = 2 // RevertOutcomeEntryRemoved: the insight was removed, and no memory was // involved. RevertOutcomeEntryRemoved RevertOutcome = 3 // RevertOutcomeMerged: the write had been folded into an existing insight; // the duplicate was removed. RevertOutcomeMerged RevertOutcome = 4 // RevertOutcomeNotFound: no write carries the id, or it is still being // processed. RevertOutcomeNotFound RevertOutcome = 5 // RevertOutcomeExpired: the write is older than the revert window. RevertOutcomeExpired RevertOutcome = 6 // RevertOutcomeRefused: the content is under moderation. RevertOutcomeRefused RevertOutcome = 7 )
The outcomes a revert reports.
func (RevertOutcome) String
func (o RevertOutcome) String() string
String names the outcome as the contract does, without its prefix.
type RevertResult
type RevertResult struct { // OperationID is the operation that was reverted. OperationID string // Outcome is what the revert removed, or why it removed nothing. Outcome RevertOutcome // Instructions is the service's guidance on the revert. Instructions Instructions }
RevertResult is what MemoryOperations.RevertMemory returned.
type ScopedCreateMemoryParams
type ScopedCreateMemoryParams struct { // Query is what someone would search to find the memory. Required. Query string // Title is a short title for the memory. Required. Title string // Content is the knowledge being saved. Required. Content string // Tags describe the memory. Tags []Tag // Source is who produced the content; unset is the agent. Source DataSource }
ScopedCreateMemoryParams describe a memory created in a session.
type ScopedEnrichMemoryParams
type ScopedEnrichMemoryParams struct { // MemoryIdx is the memory to add to, or [NewMemory]. Required. MemoryIdx string // Title is a short title for the addition. Required. Title string // Content is the knowledge being added. Required. Content string // Tags describe the addition. Tags []Tag // Sources are handles of the memories the addition draws on. Sources []string // Source is who produced the content; unset is the agent. Source DataSource }
ScopedEnrichMemoryParams describe an addition made in a session.
type ScopedSearchParams
type ScopedSearchParams struct { // Tags narrow or boost the results. Tags []Tag }
ScopedSearchParams narrow a search made in a session.
type SearchParams
type SearchParams struct { // Domain is the domain to search, when the search names no session. Domain string // SessionID records the search under an open session, which also names // the domain. SessionID string // Tags narrow or boost the results. Tags []Tag }
SearchParams scope and narrow a search.
type SearchResult
type SearchResult struct { // SessionID is the session the search was recorded under: the one named, // or a new one when the search named only a domain. SessionID string // Memories are what the search selected, in rendered order. Memories []Memory // Notice is a remark about the query itself, or empty. Notice string // Instructions is the service's guidance on the results. Instructions Instructions }
SearchResult is what a search returned.
type Session
type Session struct { // ID is the session's handle. ID string // Instructions is what the service said when the session opened. Instructions Instructions // contains filtered or unexported fields }
Session is an open session in one domain. Every call made through it is recorded under it, and supplies its domain. Open one with MemoryOperations.StartSession. A session opened with ExternalID acts for one of your users under a key of its own, which Session.Close ends; any other session holds nothing, and stays usable. A Session is safe for concurrent use.
func (*Session) Close
func (s *Session) Close(ctx context.Context)
Close closes the session, ending the key it holds if it acts for one of your users. Only a session opened with ExternalID holds anything: its key, which is revoked here rather than left live until it expires. Every later call through the session, its tools, or a memory it returned is then refused locally with a *ConfigError. A call still in flight keeps the key until it finishes, and the key is ended then.
Ending the key is best effort, so Close returns nothing: if the service cannot end it, a warning naming the key's id is logged, closing the client tries again, and the key expires on its own regardless. After the client is closed, Close does nothing.
A session opened with ExternalID and dropped without Close still has its key ended eventually: once the session, its tools and the memories it returned are all unreachable, the client's next call ends the key. Close ends it at once, which is what keeps the user under the service's cap on live keys.
A session opened without ExternalID holds nothing, so closing it changes nothing and it stays usable. Closing more than once is safe.
Parameters:
- ctx: carries values to the call that ends the key. Its cancellation does not stop that call, which gets Options.Timeout instead: a key left live counts against its user's cap.
Example
package main import ( "context" "log" "github.com/memcoai/memcoai/go/memcoai" ) // These examples are compiled, not run: each needs a credential and the // service. They share the placeholders below, which a real program gets from // NewClient and StartSession, as ExampleNewClient shows. var ( ctx = context.Background() client *memcoai.Client ) func main() { // One session per request a user makes, closed as the request ends, so // the user never holds more keys than requests in flight. answer := func(ctx context.Context, user, question string) (*memcoai.SearchResult, error) { session, err := client.Memory.StartSession(ctx, "coding", memcoai.ExternalID(user)) if err != nil { return nil, err } defer session.Close(ctx) return session.Search(ctx, question, memcoai.ScopedSearchParams{}) } if _, err := answer(ctx, "customer-42", "how do I rotate an API key"); err != nil { log.Fatal(err) } }
func (*Session) CreateMemory
func (s *Session) CreateMemory(ctx context.Context, p ScopedCreateMemoryParams) (*WriteResult, error)
CreateMemory saves new knowledge learned during this session, into its domain.
Parameters:
- ctx: bounds the call. Without a deadline, Options.Timeout applies; if ctx has already ended, nothing is sent.
- p: what to save. Query, Title and Content are required; a Source left unset is the agent.
It returns the operation's id, which Session.RevertMemory undoes, or an empty id when the service could not mint one.
Errors: as MemoryOperations.CreateMemory.
Example
package main import ( "context" "fmt" "log" "github.com/memcoai/memcoai/go/memcoai" ) // These examples are compiled, not run: each needs a credential and the // service. They share the placeholders below, which a real program gets from // NewClient and StartSession, as ExampleNewClient shows. var ( ctx = context.Background() session *memcoai.Session ) func main() { written, err := session.CreateMemory(ctx, memcoai.ScopedCreateMemoryParams{ Query: "what does a Go SDK error unwrap to", Title: "Errors unwrap to their parent type", Content: "errors.As finds *PreconditionFailedError in a *SunsetError.", }) if err != nil { log.Fatal(err) } fmt.Println(written.OperationID) }
func (*Session) EnrichMemory
func (s *Session) EnrichMemory(ctx context.Context, p ScopedEnrichMemoryParams) (*WriteResult, error)
EnrichMemory adds to a memory this session's searches returned, or opens a new one.
Parameters:
- ctx: bounds the call. Without a deadline, Options.Timeout applies; if ctx has already ended, nothing is sent.
- p: what to add. MemoryIdx is a handle from this session's searches, or NewMemory; Title and Content are required.
It returns the operation's id.
Errors: as MemoryOperations.EnrichMemory.
Example
package main import ( "context" "log" "github.com/memcoai/memcoai/go/memcoai" ) // These examples are compiled, not run: each needs a credential and the // service. They share the placeholders below, which a real program gets from // NewClient and StartSession, as ExampleNewClient shows. var ( ctx = context.Background() session *memcoai.Session ) func main() { result, err := session.Search(ctx, "how does the Go SDK close", memcoai.ScopedSearchParams{}) if err != nil || len(result.Memories) == 0 { log.Fatal("nothing to enrich: ", err) } _, err = session.EnrichMemory(ctx, memcoai.ScopedEnrichMemoryParams{ MemoryIdx: result.Memories[0].Idx, Title: "Close takes a context", Content: "Close waits for calls in flight until its context ends, then closes regardless.", }) if err != nil { log.Fatal(err) } }
func (*Session) GetMemory
func (s *Session) GetMemory(ctx context.Context, idx string) (*Memory, error)
GetMemory fetches the memory behind a handle a search returned, bound to this session so Memory.Feedback can rate it.
Parameters:
- ctx: bounds the call. Without a deadline, Options.Timeout applies; if ctx has already ended, nothing is sent.
- idx: a memory's or an insight's handle, copied from a search.
It returns the memory.
Errors: as MemoryOperations.GetMemory.
Example
package main import ( "context" "log" "github.com/memcoai/memcoai/go/memcoai" ) // These examples are compiled, not run: each needs a credential and the // service. They share the placeholders below, which a real program gets from // NewClient and StartSession, as ExampleNewClient shows. var ( ctx = context.Background() session *memcoai.Session ) func main() { memory, err := session.GetMemory(ctx, "memory-hpc08-1") if err != nil { log.Fatal(err) } correct := true if _, err := memory.Feedback(ctx, memcoai.MemoryFeedback{Relevant: true, Correct: &correct}); err != nil { log.Fatal(err) } }
func (*Session) ImportMemories
func (s *Session) ImportMemories(ctx context.Context, memories []ImportedMemory) (*ImportResult, error)
ImportMemories contributes many memories into this session's domain, recorded under the session.
Parameters:
- ctx: bounds the import; see MemoryOperations.ImportMemories.
- memories: the memories to import, each with at least one query and one insight.
It returns one outcome per memory, indexed by its position in memories.
Errors: as MemoryOperations.ImportMemories.
Example
package main import ( "context" "fmt" "log" "github.com/memcoai/memcoai/go/memcoai" ) // These examples are compiled, not run: each needs a credential and the // service. They share the placeholders below, which a real program gets from // NewClient and StartSession, as ExampleNewClient shows. var ( ctx = context.Background() session *memcoai.Session ) func main() { imported, err := session.ImportMemories(ctx, []memcoai.ImportedMemory{{ Queries: []string{"which Go versions does the SDK support"}, Insights: []memcoai.ImportedInsight{{Title: "Go 1.25 and later", Content: "go.mod declares go 1.25.0."}}, }}) if err != nil { log.Fatal(err) } fmt.Println(len(imported.Results)) }
func (*Session) RevertMemory
func (s *Session) RevertMemory(ctx context.Context, operationID string) (*RevertResult, error)
RevertMemory undoes the caller's own write. The session plays no part: an operation id names its write on its own.
Parameters:
- ctx: bounds the call. Without a deadline, Options.Timeout applies; if ctx has already ended, nothing is sent.
- operationID: the id a write returned.
It returns what the revert removed.
Errors: as MemoryOperations.RevertMemory.
Example
package main import ( "context" "fmt" "log" "github.com/memcoai/memcoai/go/memcoai" ) // These examples are compiled, not run: each needs a credential and the // service. They share the placeholders below, which a real program gets from // NewClient and StartSession, as ExampleNewClient shows. var ( ctx = context.Background() session *memcoai.Session ) func main() { written, err := session.CreateMemory(ctx, memcoai.ScopedCreateMemoryParams{Query: "q", Title: "t", Content: "c"}) if err != nil { log.Fatal(err) } reverted, err := session.RevertMemory(ctx, written.OperationID) if err != nil { log.Fatal(err) } fmt.Println(reverted.Outcome) }
func (*Session) Search
func (s *Session) Search(ctx context.Context, query string, p ScopedSearchParams) (*SearchResult, error)
Search retrieves memories for a task-based query, recorded under this session.
Parameters:
- ctx: bounds the call. Without a deadline, Options.Timeout applies; if ctx has already ended, nothing is sent.
- query: what to find, such as a question or a task description.
- p: tags that narrow or boost the results.
It returns the memories selected. Their Memory.Feedback rates them under this session.
Errors: as MemoryOperations.Search.
Example
package main import ( "context" "fmt" "log" "github.com/memcoai/memcoai/go/memcoai" ) // These examples are compiled, not run: each needs a credential and the // service. They share the placeholders below, which a real program gets from // NewClient and StartSession, as ExampleNewClient shows. var ( ctx = context.Background() session *memcoai.Session ) func main() { result, err := session.Search(ctx, "how does the service count characters", memcoai.ScopedSearchParams{}) if err != nil { log.Fatal(err) } fmt.Println(memcoai.Render(result)) }
func (*Session) ShareFeedback
func (s *Session) ShareFeedback(ctx context.Context, feedback []FeedbackRating) (*FeedbackResult, error)
ShareFeedback rates the results of this session's searches.
Parameters:
- ctx: bounds the call. Without a deadline, Options.Timeout applies; if ctx has already ended, nothing is sent.
- feedback: one rating per result; at least one.
It returns the ratings recorded, with any advice they earned.
Errors: as MemoryOperations.ShareFeedback.
func (*Session) Tools
func (s *Session) Tools() *Toolset
Tools offers this session's operations to a model: search, get_memory, create_memory, enrich_memory, share_feedback and revert_memory, each named with a "memco_" prefix and limited to those the credential's role permits. When the session could not learn the role's permissions, every tool is offered.
It returns a fresh toolset; it sends nothing.
Example
package main import ( "context" "fmt" "github.com/memcoai/memcoai/go/memcoai" ) // These examples are compiled, not run: each needs a credential and the // service. They share the placeholders below, which a real program gets from // NewClient and StartSession, as ExampleNewClient shows. var session *memcoai.Session func main() { for _, tool := range session.Tools().Tools { fmt.Println(tool.Name, tool.Parameters.Required) } }
type SessionOption
type SessionOption func(*sessionOptions)
SessionOption configures a session MemoryOperations.StartSession opens.
func ExternalID
func ExternalID(externalID string) SessionOption
ExternalID opens the session acting as one of your own users, by your id for them, as created with UserOperations.Create. The client's credential mints a short-lived key acting as that user, and the session and every call through it carry that key, which renews itself before it expires: what the session finds and writes is that user's, bounded by the network they are in. The session first lists the domains under the key, learning the limits and any deprecation notice as that user. Close the session with Session.Close when done, which ends the key.
Parameters:
- externalID: your id for the user to act as.
Example
package main import ( "context" "fmt" "log" "github.com/memcoai/memcoai/go/memcoai" ) // These examples are compiled, not run: each needs a credential and the // service. They share the placeholders below, which a real program gets from // NewClient and StartSession, as ExampleNewClient shows. var ( ctx = context.Background() client *memcoai.Client ) func main() { // A client holding an API client's credentials, from MEMCO_CLIENT_ID and // MEMCO_CLIENT_SECRET, acts for one of your users by your id for them. session, err := client.Memory.StartSession(ctx, "coding", memcoai.ExternalID("customer-42")) if err != nil { log.Fatal(err) } defer session.Close(ctx) // ends the key the session holds result, err := session.Search(ctx, "how do I rotate an API key", memcoai.ScopedSearchParams{}) if err != nil { log.Fatal(err) } fmt.Println(len(result.Memories), "memories this user can see") }
type SunsetError
type SunsetError struct { PreconditionFailedError // Kind says what is past its sunset. Kind SunsetKind }
SunsetError reports that what the caller uses has stopped working. Detail is the service's remedy. It is also a *PreconditionFailedError.
func (*SunsetError) Unwrap
func (e *SunsetError) Unwrap() error
Unwrap returns the embedded PreconditionFailedError.
type SunsetKind
type SunsetKind string
SunsetKind says what is past its sunset date.
const ( // SunsetClientVersion: this SDK release no longer works; upgrade it. SunsetClientVersion SunsetKind = "client_version" // SunsetAPIVersion: the API version no longer works; migrate to the // current one. SunsetAPIVersion SunsetKind = "api_version" )
The kinds of sunset.
type Tag
type Tag struct { // Type is the tag's category, such as "language". Required. Type string // Value is the value within that category, such as "go". Required. Value string // Version is the version of the thing named, where its type carries one. // Empty sends no version, which is the common case. Version string }
Tag is one selector on a search or a write. The service lowercases each field and folds hyphens to underscores, so "Go" and "go" name the same tag. Which tag types a domain uses, and which of them narrow results rather than boost them, is in its DomainEntry.
type TimeoutError
type TimeoutError struct{ APIError }
TimeoutError reports a call that ran out of time. It is not retried: a write may have happened.
func (*TimeoutError) Unwrap
func (e *TimeoutError) Unwrap() error
Unwrap returns the embedded APIError.
type Tool
type Tool struct { // Name is what a model calls the tool, such as "memco_search". Name string // Description is the service's own description of the operation. Description string // Parameters describe the arguments. The session, the domain and the // content's source are the caller's, so no tool offers them. Parameters ToolParameters // contains filtered or unexported fields }
Tool is one memory operation offered to a model, bound to a Session.
func (Tool) Call
func (t Tool) Call(ctx context.Context, args json.RawMessage) (string, error)
Call runs the tool with the arguments a model sent, and renders the result as text for the model.
Parameters:
- ctx: bounds the call, as for the operation the tool runs.
- args: the model's arguments, as the JSON object it sent.
It returns the rendered result. A mistake the model can correct — malformed or missing arguments, a request the service refused as invalid, a handle that resolves to nothing — also comes back as text, beginning "invalid request:" or "nothing found:", with a nil error.
Errors: every other failure of the operation, such as *AuthenticationError, *ResourceExhaustedError or a context that ended; no wording would help a model with those. IsAgentRecoverable tells the two apart.
Example
package main import ( "context" "encoding/json" "fmt" "log" "github.com/memcoai/memcoai/go/memcoai" ) // These examples are compiled, not run: each needs a credential and the // service. They share the placeholders below, which a real program gets from // NewClient and StartSession, as ExampleNewClient shows. var ( ctx = context.Background() session *memcoai.Session ) func main() { search := session.Tools().Tools[0] text, err := search.Call(ctx, json.RawMessage(`{"query": "how are retries decided"}`)) if err != nil { log.Fatal(err) } fmt.Println(text) }
type ToolDescriptor
type ToolDescriptor struct { // Name is the operation's snake_case name, such as "create_memory". Name string // Description is the service's description of the method. Description string // Available reports whether the role permits the method. A permitted method // can still be refused for another reason. Available bool }
ToolDescriptor is one method the contract declares, and whether the credential's role permits it.
type ToolParameters
type ToolParameters struct { // Type is always "object". Type string `json:"type"` // Properties describe each argument, keyed by its snake_case name. Properties map[string]JSONSchema `json:"properties"` // Required names the arguments a call cannot go without. Never nil. Required []string `json:"required"` }
ToolParameters is a JSON Schema object describing one tool's arguments. Each Session.Tools call builds it afresh, so a framework may change it in place.
type Toolset
type Toolset struct { // Tools are the offered tools, in the order a task uses them. Tools []Tool }
Toolset is every operation a Session offers to a model.
func (*Toolset) Call
func (s *Toolset) Call(ctx context.Context, name string, args json.RawMessage) (string, error)
Call runs the tool a model named, as Tool.Call does.
Parameters:
- ctx: bounds the call.
- name: the tool name the model used.
- args: the model's arguments, as the JSON object it sent. OpenAI's function arguments string can be passed as is.
It returns the rendered result, or text telling the model what it got wrong, including a name that is not a tool.
Errors: as Tool.Call.
Example
package main import ( "context" "encoding/json" "fmt" "log" "github.com/memcoai/memcoai/go/memcoai" ) // These examples are compiled, not run: each needs a credential and the // service. They share the placeholders below, which a real program gets from // NewClient and StartSession, as ExampleNewClient shows. var ( ctx = context.Background() session *memcoai.Session ) func main() { // A model's tool call, as the provider delivered it. name, arguments := "memco_search", json.RawMessage(`{"query": "how does the SDK log"}`) text, err := session.Tools().Call(ctx, name, arguments) if err != nil { log.Fatal(err) // not something a model could fix } fmt.Println(text) // the result, or what the model got wrong }
func (*Toolset) ToAnthropic
func (s *Toolset) ToAnthropic() []AnthropicTool
ToAnthropic returns the tools as Claude Messages API tool definitions, ready to marshal into a request's tools. Run the model's tool_use blocks with Toolset.Call.
It returns one definition per tool, sharing each tool's Parameters.
Example
package main import ( "context" "encoding/json" "fmt" "log" "github.com/memcoai/memcoai/go/memcoai" ) // These examples are compiled, not run: each needs a credential and the // service. They share the placeholders below, which a real program gets from // NewClient and StartSession, as ExampleNewClient shows. var session *memcoai.Session func main() { tools, err := json.Marshal(session.Tools().ToAnthropic()) if err != nil { log.Fatal(err) } fmt.Println(string(tools)) // the "tools" of a Messages API request }
func (*Toolset) ToOpenAI
func (s *Toolset) ToOpenAI() []OpenAITool
ToOpenAI returns the tools as OpenAI Chat Completions function tools. Run the model's tool calls with Toolset.Call.
It returns one definition per tool, sharing each tool's Parameters.
Example
package main import ( "context" "encoding/json" "log" "os" "github.com/memcoai/memcoai/go/memcoai" ) // These examples are compiled, not run: each needs a credential and the // service. They share the placeholders below, which a real program gets from // NewClient and StartSession, as ExampleNewClient shows. var session *memcoai.Session func main() { encoder := json.NewEncoder(os.Stdout) if err := encoder.Encode(session.Tools().ToOpenAI()); err != nil { log.Fatal(err) } }
type UnavailableError
type UnavailableError struct{ APIError }
UnavailableError reports a service that could not be reached. Reads have already been retried; backing off and retrying is the right answer.
func (*UnavailableError) Unwrap
func (e *UnavailableError) Unwrap() error
Unwrap returns the embedded APIError.
type UnhealthyError
type UnhealthyError struct{ UnavailableError }
UnhealthyError reports a service that answered Client.Connect's probe but is not serving. It is also an *UnavailableError.
func (*UnhealthyError) Unwrap
func (e *UnhealthyError) Unwrap() error
Unwrap returns the embedded UnavailableError.
type UpdateNetworkParams
type UpdateNetworkParams struct { // Name is the new name. Name *string // ParentID is the network to move this one under, replacing every other // parent; a pointer to "" makes a root. // // Deprecated: Set ParentIDs instead, never both. ParentID *string // ParentIDs replaces the network's whole parent set; a pointer to an empty // or nil slice makes a root. ParentIDs *[]string // Scope is the new scope, "internal" or "customer". Scope *string // Owner is the new owner. Owner *string // Description is the new description. Description *string }
UpdateNetworkParams change a network. A nil field is left as it is; a pointer to "" is sent, and clears the field where the service allows it.
type UpdateUserParams
type UpdateUserParams struct { // Name is the new name; a pointer to "" clears it. Name *string // Email is the new email address; a pointer to "" clears it. Email *string // Roles replace the user's roles. Nil leaves them; a non-nil slice must // name at least one. Roles []string }
UpdateUserParams change an external user. A nil field is left as it is.
type UserAlreadyAssignedNetworkError
type UserAlreadyAssignedNetworkError struct { PreconditionFailedError // CurrentNetworkID is the network the user is in, or empty if the service // did not say. CurrentNetworkID string // CurrentNetworkName is that network's name, or empty if the service did // not say. CurrentNetworkName string }
UserAlreadyAssignedNetworkError reports a user already placed in another network of the same memory domain. A user holds one network per domain, so NetworkOperations.AddMember refuses a second placement rather than moving them silently; pass AddMemberParams.Force to move them. It is also a *PreconditionFailedError.
func (*UserAlreadyAssignedNetworkError) Unwrap
func (e *UserAlreadyAssignedNetworkError) Unwrap() error
Unwrap returns the embedded PreconditionFailedError.
type UserOperations
type UserOperations struct { // contains filtered or unexported fields }
UserOperations manage your external users and their API keys, reached as Client.Users. Every method names a user by your own id for them, the external id they were created with. Calls need an API client's credentials, as NetworkOperations do.
func (*UserOperations) Create
func (u *UserOperations) Create(ctx context.Context, externalID string, p CreateUserParams) (*ExternalUser, error)
Create creates an external user: one of your own users, known to Memco by your id for them. The user has no sign-in of its own and never holds admin. It starts in no network: place it in a customer network with NetworkOperations.AddMember, passing the created user's ID.
Parameters:
- ctx: bounds the call. Without a deadline, Options.Timeout applies; if ctx has already ended, nothing is sent.
- externalID: your id for the user, unique within your organization. It cannot be changed later.
- p: the user's roles, at least one, and optionally a name and an email.
It returns the user as created.
Errors: *InvalidRequestError when externalID is blank or p.Roles is empty (nothing is sent), or when the service refuses a role; *AlreadyExistsError when you already have a user with that id; *ConfigError when the client is closed.
Example
package main import ( "context" "errors" "fmt" "log" "github.com/memcoai/memcoai/go/memcoai" ) // These examples are compiled, not run: each needs a credential and the // service. They share the placeholders below, which a real program gets from // NewClient and StartSession, as ExampleNewClient shows. var ( ctx = context.Background() client *memcoai.Client ) func main() { user, err := client.Users.Create(ctx, "customer-42", memcoai.CreateUserParams{ Roles: []string{"creator"}, Name: "Ada", }) var taken *memcoai.AlreadyExistsError if errors.As(err, &taken) { user, err = client.Users.Get(ctx, "customer-42") } if err != nil { log.Fatal(err) } fmt.Println(user.ID, user.Roles) // a creator reads too }
func (*UserOperations) CreateKey
func (u *UserOperations) CreateKey(ctx context.Context, externalID string, p CreateKeyParams) (*CreatedKey, error)
CreateKey creates an API key acting as an external user, such as one for that user's own agent to reach Memco over MCP. The key's value is returned here and never again.
Parameters:
- ctx: bounds the call. Without a deadline, Options.Timeout applies; if ctx has already ended, nothing is sent.
- externalID: your id for the user the key acts as.
- p: the kind of key, and optionally a name and an expiry.
It returns the key's description, and its value.
Errors: *InvalidRequestError when externalID is blank (nothing is sent), or when the preset is beyond the user's roles; *InternalError when the service returns a value without the key it belongs to; *NotFoundError; *ConfigError when the client is closed.
Example
package main import ( "context" "fmt" "log" "time" "github.com/memcoai/memcoai/go/memcoai" ) // These examples are compiled, not run: each needs a credential and the // service. They share the placeholders below, which a real program gets from // NewClient and StartSession, as ExampleNewClient shows. var ( ctx = context.Background() client *memcoai.Client ) func main() { created, err := client.Users.CreateKey(ctx, "customer-42", memcoai.CreateKeyParams{ Preset: "mcp_ro", Name: "agent", ValidUntil: time.Now().AddDate(0, 1, 0), }) if err != nil { log.Fatal(err) } fmt.Println(created) // the value is left out of anything printed handOver(created.Value()) // shown only this once } // handOver stands for giving a key's value to whoever will use it. func handOver(string) {}
func (*UserOperations) Delete
func (u *UserOperations) Delete(ctx context.Context, externalID string) error
Delete deletes an external user, and every API key it holds.
Parameters:
- ctx: bounds the call. Without a deadline, Options.Timeout applies; if ctx has already ended, nothing is sent.
- externalID: your id for the user to delete.
Errors: *InvalidRequestError when externalID is blank (nothing is sent); *NotFoundError; *ConfigError when the client is closed.
Example
package main import ( "context" "log" "github.com/memcoai/memcoai/go/memcoai" ) // These examples are compiled, not run: each needs a credential and the // service. They share the placeholders below, which a real program gets from // NewClient and StartSession, as ExampleNewClient shows. var ( ctx = context.Background() client *memcoai.Client ) func main() { if err := client.Users.Delete(ctx, "customer-42"); err != nil { log.Fatal(err) } }
func (*UserOperations) DeleteKey
func (u *UserOperations) DeleteKey(ctx context.Context, externalID, keyID string) error
DeleteKey revokes one of an external user's API keys.
Parameters:
- ctx: bounds the call. Without a deadline, Options.Timeout applies; if ctx has already ended, nothing is sent.
- externalID: your id for the user the key belongs to.
- keyID: the key to revoke, as ExternalUserKey.ID gives it.
Errors: *InvalidRequestError when externalID or keyID is blank (nothing is sent); *NotFoundError when the user holds no such key; *ConfigError when the client is closed.
Example
package main import ( "context" "log" "github.com/memcoai/memcoai/go/memcoai" ) // These examples are compiled, not run: each needs a credential and the // service. They share the placeholders below, which a real program gets from // NewClient and StartSession, as ExampleNewClient shows. var ( ctx = context.Background() client *memcoai.Client ) func main() { if err := client.Users.DeleteKey(ctx, "customer-42", "apikey-a"); err != nil { log.Fatal(err) } }
func (*UserOperations) Get
func (u *UserOperations) Get(ctx context.Context, externalID string) (*ExternalUser, error)
Get fetches one external user, by your own id for them.
Parameters:
- ctx: bounds the call. Without a deadline, Options.Timeout applies; if ctx has already ended, nothing is sent.
- externalID: your id for the user.
It returns the user.
Errors: *InvalidRequestError when externalID is blank (nothing is sent); *NotFoundError when you have no user with that id; *ConfigError when the client is closed.
Example
package main import ( "context" "errors" "fmt" "log" "github.com/memcoai/memcoai/go/memcoai" ) // These examples are compiled, not run: each needs a credential and the // service. They share the placeholders below, which a real program gets from // NewClient and StartSession, as ExampleNewClient shows. var ( ctx = context.Background() client *memcoai.Client ) func main() { user, err := client.Users.Get(ctx, "customer-42") var missing *memcoai.NotFoundError if errors.As(err, &missing) { log.Fatal("no such user: ", err) } if err != nil { log.Fatal(err) } fmt.Println(user.ID, user.Roles) }
func (*UserOperations) List
func (u *UserOperations) List(ctx context.Context, p ListUsersParams) (*ExternalUserList, error)
List lists one page of your organization's external users.
Parameters:
- ctx: bounds the call. Without a deadline, Options.Timeout applies; if ctx has already ended, nothing is sent.
- p: a search and the page; the zero value lists the first page.
It returns the page of users, and how many match in all.
Errors: *PermissionError when the credential may not manage users; *ConfigError when the client is closed. See Error for the rest.
Example
package main import ( "context" "fmt" "log" "github.com/memcoai/memcoai/go/memcoai" ) // These examples are compiled, not run: each needs a credential and the // service. They share the placeholders below, which a real program gets from // NewClient and StartSession, as ExampleNewClient shows. var ( ctx = context.Background() client *memcoai.Client ) func main() { page, err := client.Users.List(ctx, memcoai.ListUsersParams{Search: "acme"}) if err != nil { log.Fatal(err) } for _, user := range page.ExternalUsers { fmt.Println(user.ExternalID, user.Roles) } }
func (*UserOperations) ListKeys
func (u *UserOperations) ListKeys(ctx context.Context, externalID string) ([]ExternalUserKey, error)
ListKeys lists an external user's API keys, without their values.
Parameters:
- ctx: bounds the call. Without a deadline, Options.Timeout applies; if ctx has already ended, nothing is sent.
- externalID: your id for the user whose keys to list.
It returns the user's keys.
Errors: *InvalidRequestError when externalID is blank (nothing is sent); *NotFoundError; *ConfigError when the client is closed.
Example
package main import ( "context" "fmt" "log" "github.com/memcoai/memcoai/go/memcoai" ) // These examples are compiled, not run: each needs a credential and the // service. They share the placeholders below, which a real program gets from // NewClient and StartSession, as ExampleNewClient shows. var ( ctx = context.Background() client *memcoai.Client ) func main() { keys, err := client.Users.ListKeys(ctx, "customer-42") if err != nil { log.Fatal(err) } for _, key := range keys { fmt.Println(key.Name, key.ValuePrefix, key.ValidUntil) } }
func (*UserOperations) Update
func (u *UserOperations) Update(ctx context.Context, externalID string, p UpdateUserParams) (*ExternalUser, error)
Update changes an external user's name, email or roles. Only the fields given change; the external id itself cannot.
Parameters:
- ctx: bounds the call. Without a deadline, Options.Timeout applies; if ctx has already ended, nothing is sent.
- externalID: your id for the user to change.
- p: the changes; see UpdateUserParams.
It returns the user as it now is.
Errors: *InvalidRequestError when externalID is blank or p.Roles is given but empty (nothing is sent); *NotFoundError; *ConfigError when the client is closed.
Example
package main import ( "context" "log" "github.com/memcoai/memcoai/go/memcoai" ) // These examples are compiled, not run: each needs a credential and the // service. They share the placeholders below, which a real program gets from // NewClient and StartSession, as ExampleNewClient shows. var ( ctx = context.Background() client *memcoai.Client ) func main() { if _, err := client.Users.Update(ctx, "customer-42", memcoai.UpdateUserParams{ Roles: []string{"reader"}, }); err != nil { log.Fatal(err) } }
type WriteResult
type WriteResult struct { // OperationID undoes the write through [MemoryOperations.RevertMemory], or // is empty when the service could not mint one. OperationID string // Instructions is the service's guidance on the write. Instructions Instructions }
WriteResult is what an accepted write returned. The write is processed asynchronously, so the memory is not searchable straight away.