View Source ExOpenAi.Parser (ex_open_ai v0.1.9)

Parses the response from the OpenAI API.

Link to this section Summary

Functions

Parse a response expected to contain a resource. If you pass in a module as the first argument, the JSON will be parsed into that module's __struct__.

Link to this section Types

@type error() :: {:error, map(), http_status_code()}
@type http_status_code() :: number()
@type key() :: String.t()
@type metadata() :: map()
@type parsed_response() :: success() | error()
@type success() :: {:ok, map()}
@type success_delete() :: :ok

Link to this section Functions

Link to this function

parse(response, map, simple)

View Source
@spec parse(HTTPoison.Response.t() | String.t(), module(), boolean() | nil) ::
  success() | error()

Parse a response expected to contain a resource. If you pass in a module as the first argument, the JSON will be parsed into that module's __struct__.

examples

Examples

Given you have a module named Resource, defined like this:

defmodule Resource do
  defstruct sid: nil
end

You can parse JSON into that module's struct like so:

iex> response = %{body: "{ \"id\": \"cmpl-uqkvlQyYK7bGYrRHQ0eXlWi7\" }", status_code: 200}
...> ExOpenAi.Parser.parse(response, Resource, nil)
{:ok, %Resource{id: "cmpl-uqkvlQyYK7bGYrRHQ0eXlWi7"}}

You can also parse into a regular map if you want.

iex> response = %{body: "{ \"id\": \"cmpl-uqkvlQyYK7bGYrRHQ0eXlWi7\" }", status_code: 200}
...> ExOpenAi.Parser.parse(response, %{}, nil)
{:ok, %{"id" => "cmpl-uqkvlQyYK7bGYrRHQ0eXlWi7"}}