wolframllm

package module
v0.0.0-...-3894e63 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Apr 3, 2025 License: MIT Imports: 9 Imported by: 2

README

go-wolfram-llm

Go Reference Go Report Card

A Go client library for the Wolfram Alpha LLM API. This library provides a simple and idiomatic Go interface to interact with the Wolfram Alpha API optimized for Large Language Models (LLMs).

Features

  • Simple, idiomatic Go API
  • Full support for Wolfram Alpha LLM API
  • Flexible configuration via functional options pattern
  • Clear error handling with detailed information
  • Context-aware API requests
  • Fully typed request and response structures
  • Support for both URL parameter and Bearer Token authentication methods

Installation

go get github.com/cnosuke/go-wolfram-llm

Quick Start

package main

import (
	"context"
	"fmt"
	"log"

	wolframllm "github.com/cnosuke/go-wolfram-llm"
)

func main() {
	// Create a client with your Wolfram Alpha AppID
	client, err := wolframllm.NewClient("YOUR_APP_ID_HERE")
	if err != nil {
		log.Fatalf("Failed to create client: %v", err)
	}

	// Create a context
	ctx := context.Background()

	// Execute a query
	response, err := client.Query(ctx, "10 densest elemental metals")
	if err != nil {
		log.Fatalf("Query execution failed: %v", err)
	}

	// Display the results
	fmt.Printf("Result:\n%s\n", response.Result)
}

Advanced Usage

With Options
package main

import (
	"context"
	"fmt"
	"log"

	wolframllm "github.com/cnosuke/go-wolfram-llm"
)

func main() {
	// Create a client with options
	client, err := wolframllm.NewClient(
		"YOUR_APP_ID_HERE",
		wolframllm.WithTimeout(60),           // Timeout in seconds
		wolframllm.WithBearer(true),          // Use Bearer Token authentication
		wolframllm.WithDefaultMaxChars(1000), // Set default maximum characters
		wolframllm.WithRetries(3),            // Set maximum retry count
	)
	if err != nil {
		log.Fatalf("Failed to create client: %v", err)
	}

	// Create a context
	ctx := context.Background()

	// Create query parameters
	params := &wolframllm.QueryParams{
		MaxChars:   2000,          // Max characters for this request
		Assumption: "DateOrder_**", // Specify date interpretation
	}

	response, err := client.QueryWithParams(ctx, "integrate x^2", params)
	if err != nil {
		log.Fatalf("Query execution failed: %v", err)
	}

	// Display the result
	fmt.Printf("Result:\n%s\n", response.Result)
}
Error Handling
response, err := client.Query(ctx, "population of Earth")
if err != nil {
	switch {
	case wolframllm.IsInvalidInputError(err):
		fmt.Println("Invalid input:", err)
	case wolframllm.IsAuthError(err):
		fmt.Println("Authentication error:", err)
	case wolframllm.IsServerError(err):
		fmt.Println("Server error:", err)
	case wolframllm.IsNetworkError(err):
		fmt.Println("Network error:", err)
	default:
		fmt.Println("Error:", err)
	}
	return
}

API Reference

For detailed API documentation, see the Go Reference.

Client

Client is the main entry point for using the library:

// Create a basic client
client, err := wolframllm.NewClient("APP_ID")

// Create a client with options
client, err := wolframllm.NewClient(
	"APP_ID",
	wolframllm.WithTimeout(30),
	wolframllm.WithUserAgent("MyApp/1.0"),
)
Query Execution
// Basic query
response, err := client.Query(ctx, "calculate pi to 100 digits")

// Query with parameters
params := &wolframllm.QueryParams{
	MaxChars:    1000,
	Assumption:  "DateOrder_**",
	Units:       "metric",
	CountryCode: "JP",
}
response, err := client.QueryWithParams(ctx, "query", params)
Response Structure
type LLMResponse struct {
	Result           string             // Computation result
}

Configuration Options

The library supports several configuration options through the functional options pattern:

client, err := wolframllm.NewClient(
	"APP_ID",
	wolframllm.WithTimeout(30),           // Request timeout in seconds
	wolframllm.WithRetries(2),            // Number of retries on transient errors
	wolframllm.WithUserAgent("MyApp/1.0"), // Custom User-Agent
	wolframllm.WithBearer(true),          // Use Bearer Token authentication
	wolframllm.WithDefaultMaxChars(1000), // Default maximum character count
	wolframllm.WithHTTPClient(customClient), // Custom HTTP client
	wolframllm.WithBaseURL("https://custom-url.com"), // Custom base URL
)

Supported Parameters

The library supports all parameters mentioned in the official Wolfram Alpha LLM API documentation, including:

  • maxchars: Maximum character count in response
  • assumption: Assumption parameter
  • ip: Client IP address
  • latlong: Latitude/longitude
  • timezone: Timezone
  • location: Location information
  • units: Unit system ("metric" or "nonmetric")
  • currency: Currency
  • countrycode: Country code
  • languagecode: Language code
  • And many others

Development Status

This library is actively under development. While it is functional, we are continuously improving it. Feedback and contributions are welcome!

License

MIT License

Acknowledgments

  • This library is not officially provided or endorsed by Wolfram Research, Inc.
  • Thanks to Wolfram Research for providing the excellent LLM API.

Author

cnosuke ( x.com/cnosuke )

Documentation

Index

Constants

View Source
const (
	// DefaultBaseURL is the default endpoint URL for Wolfram Alpha LLM API
	DefaultBaseURL = "https://www.wolframalpha.com/api/v1/llm-api"

	// DefaultUserAgent is the default User-Agent used for API requests
	DefaultUserAgent = "go-wolfram-llm/1.0"

	// DefaultTimeout is the default timeout duration for API requests (in seconds)
	DefaultTimeout = 30 * time.Second

	// DefaultMaxRetries is the default number of retries for API request failures
	DefaultMaxRetries = 3

	// DefaultMaxChars is the default value for maximum character count in responses
	DefaultMaxChars = 6800
)

API-related constants

View Source
const Version = "0.1.0"

Version is the library version

Variables

View Source
var (
	// ErrMissingAppID is returned when AppID is not specified
	ErrMissingAppID = errors.New("missing AppID")

	// ErrInvalidAppID is returned when AppID is invalid
	ErrInvalidAppID = errors.New("invalid AppID")

	// ErrEmptyInput is returned when the input query is empty
	ErrEmptyInput = errors.New("input query cannot be empty")

	// ErrInputTooLong is returned when the input query is too long
	ErrInputTooLong = errors.New("input query too long")

	// ErrInvalidMaxChars is returned when the maxchars parameter is invalid
	ErrInvalidMaxChars = errors.New("invalid maxchars parameter: must be a positive integer")

	// ErrInvalidInput is returned when the input is invalid (HTTP 501)
	ErrInvalidInput = errors.New("invalid input: input cannot be interpreted")

	// ErrMissingInputParam is returned when the input parameter is missing (HTTP 400)
	ErrMissingInputParam = errors.New("missing input parameter")

	// ErrUnauthorized is returned when an authentication error occurs (HTTP 403)
	ErrUnauthorized = errors.New("unauthorized: invalid or missing AppID")

	// ErrServerError is returned when a server error occurs (HTTP 5xx)
	ErrServerError = errors.New("server error")

	// ErrNetworkError is returned when a network error occurs
	ErrNetworkError = errors.New("network error")

	// ErrResponseParsing is returned when response parsing fails
	ErrResponseParsing = errors.New("failed to parse response")
)

Predefined errors

Functions

func GetErrorDetails

func GetErrorDetails(err error) map[string]string

GetErrorDetails extracts detailed information from an error

func IsAuthError

func IsAuthError(err error) bool

IsAuthError determines if the error is related to authentication

func IsInvalidInputError

func IsInvalidInputError(err error) bool

IsInvalidInputError determines if the error is related to invalid input

func IsNetworkError

func IsNetworkError(err error) bool

IsNetworkError determines if the error is related to the network

func IsServerError

func IsServerError(err error) bool

IsServerError determines if the error is a server error

func NewAPIError

func NewAPIError(statusCode int, message string, cause error) error

NewAPIError creates an error for when an API call fails

func NewEmptyInputError

func NewEmptyInputError() error

NewEmptyInputError creates an error for when the input query is empty

func NewInvalidAppIDError

func NewInvalidAppIDError(appID string) error

NewInvalidAppIDError creates an error for when AppID is invalid

func NewInvalidInputError

func NewInvalidInputError(message string) error

NewInvalidInputError creates an error for when the input query cannot be interpreted

func NewMissingAppIDError

func NewMissingAppIDError() error

NewMissingAppIDError creates an error for when AppID is not specified

func SimpleQuery

func SimpleQuery(ctx context.Context, appID, input string) (string, error)

SimpleQuery is the simplest query execution function. It creates a temporary client, executes the query, and returns the result.

Types

type Client

type Client struct {
	// contains filtered or unexported fields
}

Client is the Wolfram Alpha LLM API client

func NewClient

func NewClient(appID string, options ...ClientOption) (*Client, error)

NewClient creates a new Wolfram Alpha LLM API client

func (*Client) Query

func (c *Client) Query(ctx context.Context, input string) (*LLMResponse, error)

Query executes a basic query

func (*Client) QueryWithParams

func (c *Client) QueryWithParams(ctx context.Context, input string, params *QueryParams) (*LLMResponse, error)

QueryWithParams executes a query with parameters

type ClientConfig

type ClientConfig struct {
	// AppID is the application ID for Wolfram Alpha API
	AppID string

	// BaseURL is the base URL for Wolfram Alpha LLM API
	BaseURL string

	// Timeout is the HTTP request timeout duration
	Timeout time.Duration

	// MaxRetries is the maximum number of retries for temporary errors
	MaxRetries int

	// UserAgent is the User-Agent for HTTP requests
	UserAgent string

	// UseBearer determines whether to use Bearer Token authentication
	UseBearer bool

	// DefaultMaxChars is the default value for maximum character count in responses
	DefaultMaxChars int

	// HTTPClient is a custom HTTP client
	HTTPClient *http.Client
}

ClientConfig is the configuration for Wolfram Alpha LLM API client

type ClientOption

type ClientOption func(*ClientConfig) error

ClientOption is a function type for client configuration

func WithBaseURL

func WithBaseURL(baseURL string) ClientOption

WithBaseURL is an option to set custom base URL

func WithBearer

func WithBearer(useBearer bool) ClientOption

WithBearer is an option to set use of Bearer Token authentication

func WithDefaultMaxChars

func WithDefaultMaxChars(maxChars int) ClientOption

WithDefaultMaxChars is an option to set default maximum character count

func WithHTTPClient

func WithHTTPClient(client *http.Client) ClientOption

WithHTTPClient is an option to set custom HTTP client

func WithRetries

func WithRetries(retries int) ClientOption

WithRetries is an option to set maximum number of retries

func WithTimeout

func WithTimeout(seconds int) ClientOption

WithTimeout is an option to set request timeout

func WithUserAgent

func WithUserAgent(userAgent string) ClientOption

WithUserAgent is an option to set custom User-Agent

type LLMResponse

type LLMResponse struct {
	// Result is the result
	Result string
}

LLMResponse stores the response from Wolfram Alpha LLM API

type QueryParams

type QueryParams struct {
	// Input is the required search query
	Input string

	// MaxChars is the maximum character count for the response
	MaxChars int

	// Assumption is the assumption parameter
	Assumption string

	// IP is the client's IP address
	IP string

	// LatLong is the latitude and longitude
	LatLong string

	// Timezone is the timezone
	Timezone string

	// Location is the location information
	Location string

	// ScanTimeout is the scan timeout
	ScanTimeout float64

	// FormatTimeout is the format timeout
	FormatTimeout float64

	// ParseTimeout is the parse timeout
	ParseTimeout float64

	// TotalTimeout is the total timeout
	TotalTimeout float64

	// Units is the unit system ("metric" or "nonmetric")
	Units string

	// Currency is the currency
	Currency string

	// CountryCode is the country code
	CountryCode string

	// LanguageCode is the language code
	LanguageCode string

	// Width is the width
	Width int

	// MaxWidth is the maximum width
	MaxWidth int

	// PlotWidth is the plot width
	PlotWidth int

	// Mag is the magnification
	Mag float64

	// ID is the session continuation ID
	ID string
}

QueryParams are the parameters for Wolfram Alpha LLM API requests

Directories

Path Synopsis
examples
advanced command
simple command

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL
⌂ 换网址