gemini

    Thin Gemini API client for MoonBit built on gaato/mttp_core: generation (buffered and streaming), embeddings, token counting, files and context caching.

    Download zip
    Author
    Version
    0.2.0
    License
    Apache-2.0
    Last updated
    13 days ago
    Downloads
    61

    #gaato/gemini

    A client for Google's native Gemini API in MoonBit: text and multimodal generation, streaming, embeddings, token counting, file uploads and context caching, with typed request and response models in gaato/gemini/gen.

    For plain chat, gaato/openai also works with Gemini's OpenAI-compatible endpoint. Use this module when you need what only the native API has: uploaded files, cached content, safety settings, thought signatures, grounding metadata and typed media parts.

    Unofficial, and not affiliated with Google. A minor release can change the API; the changelog lists each change.

    #Install

    moon add gaato/gemini moon add gaato/mttp

    Import gaato/gemini and gaato/gemini/gen. gaato/mttp supplies the network and the clock. Also add gaato/mttp_core if you pass an existing gaato/mttp_core/client.Client to Gemini::from_client, or if you write a library that takes the backend from its caller.

    #Generate text

    ///|
    fn print_text(reply : @gen.GenerateContentResponse) -> Unit {
    for candidate in reply.candidates.unwrap_or([]) {
    if candidate.content is Some(content) {
    for part in content.parts.unwrap_or([]) {
    if part is Text(piece) {
    println(piece.text)
    }
    }
    }
    }
    }

    ///|
    pub async fn generate(
    gemini : @gemini.Gemini,
    model_id : String,
    prompt : String,
    ) -> Result[Unit, @gemini.Failure] {
    let request = @gen.GenerateContentRequest::new(contents=[
    @gen.Content::new(role="user", parts=[Text(@gen.PartText::new(text=prompt))]),
    ])
    match gemini.generate_content(model=model_id, request) {
    Ok(reply) => Ok(print_text(reply))
    Err(failure) => Err(failure)
    }
    }

    A command-line program builds the client from mttp's backend and clock, and closes the backend when it is done. Import gaato/mttp, moonbitlang/core/env and moonbitlang/core/debug in its moon.pkg:

    ///|
    fn main {
    @mttp.run(async fn() {
    guard @env.get_env_var("GEMINI_API_KEY") is Some(key) else {
    println("Set GEMINI_API_KEY")
    return
    }
    guard @env.get_env_var("GEMINI_MODEL") is Some(model) else {
    println("Set GEMINI_MODEL to a model your account can use")
    return
    }
    let backend = @mttp.backend()
    defer backend.close()
    let gemini = @gemini.Gemini::new(
    backend,
    @mttp.clock(),
    auth=ApiKey(key),
    timer=@mttp.timer(),
    total_timeout_ms=120_000,
    )
    match generate(gemini, model, "Describe a quiet morning.") {
    Ok(_) => ()
    Err(failure) => println(@debug.to_string(failure))
    }
    })
    }

    model= takes a bare ID or a resource name starting with models/. A successful response can have no text: when a prompt is blocked, there are no candidates. Check prompt_feedback and each candidate's finish reason before expecting text.

    auth= takes ApiKey(key) (sent in a header), ApiKeyInQuery(key) (in the URL, so it can appear in logs) or OAuthToken(token). Obtaining an OAuth token is up to the application. The SDK marks its credential headers even with from_client. Redirects that change host, port or scheme strip them, except for a same-host HTTP port 80 to HTTPS port 443 upgrade, and HTTPS to HTTP is refused by default. A key in the query string stays in the URL.

    #Stream model output

    ///|
    pub async fn stream(
    gemini : @gemini.Gemini,
    model_id : String,
    request : @gen.GenerateContentRequest,
    ) -> Result[Unit, @gemini.Failure] {
    gemini.stream_generate_content(model=model_id, request, reply => {
    print_text(reply)
    })
    }

    The callback receives a decoded response for each event. An optional stop predicate closes the stream before delivering the event it matches. An interrupted stream is not resumed. When you pass model output into a later turn, keep each part's thought signature and other metadata, which Gemini needs back.

    list_models, list_models_pages and get_model list the models your key can use and describe one.

    #Media, files and cached context

    • Small media: an InlineData part, with the bytes as their base64 wire string.
    • Larger files: upload_file(bytes, mime_type=..., display_name=...), then a FileData part with the returned file URI. The upload holds the whole input in memory and does not resume an interrupted session. A new file can still be processing, so check it with get_file before generating. list_files_pages and delete_file manage files.
    • Reusable context: create_cached_content, then pass its full resource name as cached_content in the request. get_, list_, update_ and delete_cached_content manage caches.

    File and cache methods accept the names they return (files/abc, cachedContents/abc) or the bare ID.

    #Retries, deadlines and errors

    SettingDefault with Gemini::newNotes
    RetriesUp to 4, on HTTP 503 and on transport failures known to be unsent429 and failures after sending are not retried. Retry-After is honoured; a server that asks for more than 60 s is not retried.
    timeout_ms, total_timeout_msnoneSet them, with timer=, to bound calls.
    Buffered bodythe runtime's defaultmax_body_bytes=

    Gemini::from_client keeps the supplied client's policies instead.

    Failures are values of Failure. Match with a wildcard arm:

    • Http(...): the status, headers, diagnostic bytes, and Google's typed error when present.
    • Transport(...): the network failed or a deadline expired.
    • Decode(...): the response did not match the model.
    • Validation(operation~, parameter~, message~): invalid input, caught before sending.

    An exception raised in a streaming callback reaches the caller unchanged.

    #Not included

    The Live API, Interactions, tuning, batch jobs and file-search stores.

    #License

    Apache-2.0

    Auth

    pub(all) enum Auth {
    Anonymous
    ApiKey(String)
    ApiKeyInQuery(String)
    OAuthToken(String)
    }

    Credentials selected at construction; Debug deliberately redacts values.

    Auth::to_repr

    ErrorBody

    pub(all) enum ErrorBody {
    GoogleError(GoogleError)
    } derive(
    Debug
    )

    ErrorBody::to_repr

    automatically derived

    Failure

    pub(all) enum Failure {
    Http(HttpFailure)
    Transport(
    TransportError
    )
    Decode(
    ResponseFailure
    )
    Validation(operation~ : String, parameter~ : String, message~ : String)
    } derive(
    Debug
    )

    Transport failures retain their kind and phase. Unknown callback errors propagate.

    Failure::to_repr

    automatically derived

    Gemini

    pub struct Gemini {
    // private fields
    }

    Transport-independent client. Sharing a runtime Client also shares its retry budget.

    Gemini::batch_embed_contents

    Calls models_batch_embed_contents.

    Gemini::call

    Sends the request and applies the matching generated decoder to a consumed body.

    Gemini::count_tokens

    Calls models_count_tokens.

    Gemini::create_cached_content

    Calls cached_contents_create.

    Gemini::create_file_metadata

    Calls media_upload.

    Gemini::delete_cached_content

    async fn Gemini::delete_cached_content(self : Gemini, name~ : String) -> Result[Unit, Failure]

    Calls cached_contents_delete.

    Gemini::delete_file

    async fn Gemini::delete_file(self : Gemini, name~ : String) -> Result[Unit, Failure]

    Calls files_delete.

    Gemini::embed_content

    Calls models_embed_content.

    Gemini::from_client

    fn Gemini::from_client(client :
    Client
    , auth? : Auth, base_url? : String, server_urls? : Map[String, String]) -> Gemini

    Wraps the caller's Client; its policies and retry budget apply. From mttp_core 0.3.0, SDK credential headers are marked on each request. They are stripped when the host, port or scheme changes, except on a same-host HTTP port 80 to HTTPS port 443 upgrade. HTTPS to HTTP is refused by default. Query credentials appear in redirect history and observer URLs.

    Gemini::generate_content

    Calls models_generate_content.

    Gemini::get_cached_content

    async fn Gemini::get_cached_content(self : Gemini, name~ : String) -> Result[
    CachedContent
    , Failure]

    Calls cached_contents_get.

    Gemini::get_file

    async fn Gemini::get_file(self : Gemini, name~ : String) -> Result[
    File
    , Failure]

    Calls files_get.

    Gemini::get_model

    async fn Gemini::get_model(self : Gemini, name~ : String) -> Result[
    Model
    , Failure]

    Calls models_get.

    Gemini::list_cached_contents

    async fn Gemini::list_cached_contents(self : Gemini, page_size? : Int, page_token? : String) -> Result[
    ListCachedContentsResponse
    , Failure]

    Calls cached_contents_list.

    Gemini::list_cached_contents_pages

    fn Gemini::list_cached_contents_pages(self : Gemini, page_size? : Int, page_token? : String) ->
    Paginator
    [
    CachedContent
    , Failure]

    Pages cached_contents_list, building the first request from the operation parameters.

    Gemini::list_files

    async fn Gemini::list_files(self : Gemini, page_size? : Int, page_token? : String) -> Result[
    ListFilesResponse
    , Failure]

    Calls files_list.

    Gemini::list_files_pages

    fn Gemini::list_files_pages(self : Gemini, page_size? : Int, page_token? : String) ->
    Paginator
    [
    File
    , Failure]

    Pages files_list, building the first request from the operation parameters.

    Gemini::list_models

    async fn Gemini::list_models(self : Gemini, page_size? : Int, page_token? : String) -> Result[
    ListModelsResponse
    , Failure]

    Calls models_list.

    Gemini::list_models_pages

    fn Gemini::list_models_pages(self : Gemini, page_size? : Int, page_token? : String) ->
    Paginator
    [
    Model
    , Failure]

    Pages models_list, building the first request from the operation parameters.

    Gemini::new

    fn Gemini::new(backend : &
    Backend
    , clock : &
    Clock
    , auth? : Auth, base_url? : String, server_urls? : Map[String, String], retry? :
    RetryPolicy
    , timer? : &
    Timer
    , timeout_ms? : Int, total_timeout_ms? : Int, max_body_bytes? : Int) -> Gemini

    Constructs a client using the caller's backend and clock. Retries are conservative unless configured in the ledger. No per-attempt timeout is set by default. No total timeout is set by default. Backend SendOptions enforce attempts; a supplied timer also bounds runtime waits. Query credentials appear in redirect history and observer URLs. server_urls maps spec server URLs to replacement URLs, independently of base_url.

    Gemini::paginate

    fn[T :
    FromJson
    ] Gemini::paginate(self : Gemini, first :
    Request
    , kind~ : PageKind, items~ : String, next~ : String, operation? : String) ->
    Paginator
    [T, Failure]

    Paginates JSON arrays by cursor query parameter or next URL. Offset pagination is not supported. A page advances only after successful decoding.

    Gemini::send

    async fn Gemini::send(self : Gemini, request :
    Request
    , operation? : String) -> Result[
    Reply
    [Bytes], Failure]

    Buffers and consumes a response; HTTP failures retain status, headers and body.

    Gemini::stream

    async fn Gemini::stream(self : Gemini, request :
    Request
    , receive : async (
    SseEvent
    ) -> Unit, stop? : (
    SseEvent
    ) -> Bool, operation? : String) -> Result[Unit, Failure]

    Consumes SSE events; stop finishes at a protocol sentinel and closes the body. Callback errors propagate. Streaming bodies are never replayed after consumption.

    Gemini::stream_generate_content

    Streams models_stream_generate_content as typed SSE JSON events; alt=sse is always set.

    Gemini::to_repr

    Gemini::update_cached_content

    async fn Gemini::update_cached_content(self : Gemini, name~ : String, body :
    CachedContent
    , update_mask? : String) -> Result[
    CachedContent
    , Failure]

    Calls cached_contents_patch.

    Gemini::upload_file

    async fn Gemini::upload_file(self : Gemini, bytes : Bytes, mime_type~ : String, display_name? : String) -> Result[
    CreateFileResponse
    , Failure]

    Uploads buffered bytes in a resumable session (start, then upload/finalize). The session must be on this client's origin. Interrupted transfers are not resumed. Handwritten because Discovery describes media endpoints but cannot express the session URL returned in a header or the upload/finalize command sequence.

    GoogleError

    pub(all) struct GoogleError {
    error : GoogleErrorStatus
    } derive(Eq,
    Debug
    )

    Generated representation of GoogleError.

    GoogleError::equal

    fn GoogleError::equal(GoogleError, GoogleError) -> Bool
    automatically derived

    GoogleError::new

    Creates a GoogleError with omitted optional fields absent.

    GoogleError::not_equal

    fn GoogleError::not_equal(x : GoogleError, y : GoogleError) -> Bool
    automatically derived

    GoogleError::to_json

    Encodes this value as JSON.

    GoogleError::to_repr

    automatically derived

    GoogleErrorStatus

    pub(all) struct GoogleErrorStatus {
    code : Int
    message : String
    status : String
    details : Array[
    Json
    ]?
    } derive(Eq,
    Debug
    )

    Generated representation of GoogleErrorStatus.

    GoogleErrorStatus::equal

    automatically derived

    GoogleErrorStatus::new

    fn GoogleErrorStatus::new(code~ : Int, message~ : String, status~ : String, details? : Array[
    Json
    ]) -> GoogleErrorStatus

    Creates a GoogleErrorStatus with omitted optional fields absent.

    GoogleErrorStatus::not_equal

    fn GoogleErrorStatus::not_equal(x : GoogleErrorStatus, y : GoogleErrorStatus) -> Bool
    automatically derived

    GoogleErrorStatus::to_json

    Encodes this value as JSON.

    GoogleErrorStatus::to_repr

    automatically derived

    HttpFailure

    pub(all) struct HttpFailure {
    operation : String
    head :
    ResponseHead

    body : Bytes
    typed : ErrorBody?
    } derive(
    Debug
    )

    HTTP failure with exact response bytes and an optional typed interpretation.

    HttpFailure::to_repr

    automatically derived

    PageKind

    pub(all) enum PageKind {
    Cursor(String)
    NextUrl
    }

    How the following page is addressed; cursor names come from the API contract.

    default_retry

    SDK retry default; a Refused failure means not processed.