Movatterモバイル変換


[0]ホーム

URL:


aisdk

packagemodule
v0.0.8Latest Latest
Warning

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

Go to latest
Published: Apr 29, 2025 License:MITImports:14Imported by:0

Details

Repository

github.com/kylecarbs/aisdk-go

Links

README

aisdk-go

GitHub ReleaseGoDocCI Status

[!WARNING]
This library is super new and may change a lot.

A Go implementation of Vercel's AI SDKData Stream Protocol.

  • Supports OpenAI, Google, and Anthropic (with Bedrock support)
  • Examples for integratinguseChat
  • Chain tool usage in Go, just likemaxSteps
// frontend.tsxconst { messages } = useChat({    // Points to our Go backend!    api: "/api/chat",})
// backend.go// Accept the POST request...var req *aisdk.Chatmessages, err := aisdk.MessagesToOpenAI(req.Messages)if err != nil {    http.Error(w, err.Error(), http.StatusInternalServerError)    return}// Convert the http.ResponseWriter to a Data Stream.dataStream := aisdk.NewDataStream(w)stream := openaiClient.Chat.Completions.NewStreaming(...)aisdk.PipeOpenAIToDataStream(stream, dataStream)

Development

Run tests withgo test. Start theuseChat demo with:

# any or all of these can be setexport OPENAI_API_KEY=<api-key>export ANTHROPIC_API_KEY=<api-key>export GOOGLE_API_KEY=<api-key>cd demobun ibun dev

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

funcMessagesToAnthropic

func MessagesToAnthropic(messages []Message) ([]anthropic.MessageParam, []anthropic.TextBlockParam,error)

MessagesToAnthropic converts internal message format to Anthropic's API format.It extracts system messages into a separate slice of TextBlockParams and groupsconsecutive user/tool and assistant messages according to Anthropic's rules.It handles the case where a single assistant message part contains both thetool call and its result, splitting them into the required assistant tool_useand user tool_result blocks.

funcMessagesToGoogle

func MessagesToGoogle(messages []Message) ([]*genai.Content,error)

MessagesToGoogle converts internal message format to Google's genai.Content slice.System messages are ignored.

funcMessagesToOpenAI

func MessagesToOpenAI(messages []Message) ([]openai.ChatCompletionMessageParamUnion,error)

MessagesToOpenAI converts internal message format to OpenAI's API format.

funcToolsToAnthropicadded inv0.0.2

func ToolsToAnthropic(tools []Tool) []anthropic.ToolUnionParam

ToolsToAnthropic converts the tool format to Anthropic's API format.

funcToolsToGoogleadded inv0.0.2

func ToolsToGoogle(tools []Tool) ([]*genai.Tool,error)

funcToolsToOpenAIadded inv0.0.2

func ToolsToOpenAI(tools []Tool) []openai.ChatCompletionToolParam

ToolsToOpenAI converts the tool format to OpenAI's API format.

funcWriteDataStreamHeadersadded inv0.0.3

func WriteDataStreamHeaders(whttp.ResponseWriter)

Types

typeAttachmentadded inv0.0.3

type Attachment struct {Namestring `json:"name,omitempty"`ContentTypestring `json:"contentType,omitempty"`URLstring `json:"url"`}

typeChat

type Chat struct {IDstring    `json:"id"`Messages []Message `json:"messages"`}

Chat is the structure sent from `useChat` to the server.This can be extended if you'd like to send additional data with `body`.

typeDataStream

type DataStreamiter.Seq2[DataStreamPart,error]

DataStream is a stream of DataStreamParts.

funcAnthropicToDataStreamadded inv0.0.3

func AnthropicToDataStream(stream *ssestream.Stream[anthropic.MessageStreamEventUnion])DataStream

AnthropicToDataStream pipes an Anthropic stream to a DataStream.

funcGoogleToDataStreamadded inv0.0.3

func GoogleToDataStream(streamiter.Seq2[*genai.GenerateContentResponse,error])DataStream

GoogleToDataStream pipes a Google AI stream to a DataStream.

funcOpenAIToDataStreamadded inv0.0.3

func OpenAIToDataStream(stream *ssestream.Stream[openai.ChatCompletionChunk])DataStream

OpenAIToDataStream pipes an OpenAI stream to a DataStream.

func (DataStream)Pipeadded inv0.0.3

func (sDataStream) Pipe(wio.Writer)error

Pipe iterates over the DataStream and writes the parts to the writer.

func (DataStream)WithAccumulatoradded inv0.0.3

func (sDataStream) WithAccumulator(accumulator *DataStreamAccumulator)DataStream

WithAccumulator passes parts to the accumulator which aggregates them into a single message.

func (DataStream)WithToolCallingadded inv0.0.3

func (sDataStream) WithToolCalling(handleToolCall func(toolCallToolCall)ToolCallResult)DataStream

WithToolCalling passes tool calls to the handleToolCall function.

typeDataStreamAccumulatoradded inv0.0.3

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

DataStreamAccumulator accumulates DataStreamParts into Messages.

func (*DataStreamAccumulator)FinishReasonadded inv0.0.3

func (a *DataStreamAccumulator) FinishReason()FinishReason

func (*DataStreamAccumulator)Messagesadded inv0.0.3

func (a *DataStreamAccumulator) Messages() []Message

func (*DataStreamAccumulator)Pushadded inv0.0.3

func (*DataStreamAccumulator)Usageadded inv0.0.3

func (a *DataStreamAccumulator) Usage()Usage

typeDataStreamDataPart

type DataStreamDataPart struct {Content []any}

DataStreamDataPart corresponds to TYPE_ID '2'.

func (DataStreamDataPart)Format

func (pDataStreamDataPart) Format() (string,error)

func (DataStreamDataPart)TypeID

func (pDataStreamDataPart) TypeID()byte

typeDataStreamPart

type DataStreamPart interface {Format() (string,error)TypeID()byte}

DataStreamPart represents a part of the Vercel AI SDK data stream.

typeErrorStreamPart

type ErrorStreamPart struct {Contentstring}

ErrorStreamPart corresponds to TYPE_ID '3'.

func (ErrorStreamPart)Format

func (pErrorStreamPart) Format() (string,error)

func (ErrorStreamPart)TypeID

func (pErrorStreamPart) TypeID()byte

typeFileStreamPart

type FileStreamPart struct {Data     []byte `json:"data"`MimeTypestring `json:"mimeType"`}

FileStreamPart corresponds to TYPE_ID 'k'.

func (FileStreamPart)Format

func (pFileStreamPart) Format() (string,error)

func (FileStreamPart)TypeID

func (pFileStreamPart) TypeID()byte

typeFinishMessageStreamPart

type FinishMessageStreamPart struct {FinishReasonFinishReason `json:"finishReason"`UsageUsage        `json:"usage"`}

FinishMessageStreamPart corresponds to TYPE_ID 'd'.

func (FinishMessageStreamPart)Format

func (FinishMessageStreamPart)TypeID

typeFinishReason

type FinishReasonstring

FinishReason defines the possible reasons for finishing a step or message.

const (FinishReasonStopFinishReason = "stop"FinishReasonLengthFinishReason = "length"FinishReasonContentFilterFinishReason = "content-filter"FinishReasonToolCallsFinishReason = "tool-calls"FinishReasonErrorFinishReason = "error"FinishReasonOtherFinishReason = "other"FinishReasonUnknownFinishReason = "unknown")

typeFinishStepStreamPart

type FinishStepStreamPart struct {FinishReasonFinishReason `json:"finishReason"`UsageUsage        `json:"usage"`IsContinuedbool         `json:"isContinued"`}

FinishStepStreamPart corresponds to TYPE_ID 'e'.

func (FinishStepStreamPart)Format

func (pFinishStepStreamPart) Format() (string,error)

func (FinishStepStreamPart)TypeID

func (pFinishStepStreamPart) TypeID()byte

typeGoogleStreamIterator

type GoogleStreamIterator interface {Next() (*genai.GenerateContentResponse,error)}

GoogleStreamIterator defines the interface for iterating over Google AI stream responses.This allows for mocking in tests.

typeMessage

type Message struct {IDstring           `json:"id"`CreatedAt   *json.RawMessage `json:"createdAt,omitempty"`Contentstring           `json:"content"`Rolestring           `json:"role"`Parts       []Part           `json:"parts,omitempty"`Annotations []any            `json:"annotations,omitempty"`Attachments []Attachment     `json:"experimental_attachments,omitempty"`}

typeMessageAnnotationStreamPart

type MessageAnnotationStreamPart struct {Content []any}

MessageAnnotationStreamPart corresponds to TYPE_ID '8'.

func (MessageAnnotationStreamPart)Format

func (MessageAnnotationStreamPart)TypeID

typePartadded inv0.0.3

type Part struct {TypePartType `json:"type"`// Type: "text"Textstring `json:"text,omitempty"`// Type: "reasoning"Reasoningstring            `json:"reasoning,omitempty"`Details   []ReasoningDetail `json:"details,omitempty"`// Type: "tool-invocation"ToolInvocation *ToolInvocation `json:"toolInvocation,omitempty"`// Type: "source"Source *SourceInfo `json:"source,omitempty"`// Type: "file"MimeTypestring `json:"mimeType,omitempty"`Data     []byte `json:"data,omitempty"`// contains filtered or unexported fields}

typePartTypeadded inv0.0.3

type PartTypestring
const (PartTypeTextPartType = "text"PartTypeReasoningPartType = "reasoning"PartTypeToolInvocationPartType = "tool-invocation"PartTypeSourcePartType = "source"PartTypeFilePartType = "file"PartTypeStepStartPartType = "step-start")

typeReasoningDetailadded inv0.0.3

type ReasoningDetail struct {Typestring `json:"type"`Textstring `json:"text,omitempty"`Signaturestring `json:"signature,omitempty"`Datastring `json:"data,omitempty"`}

typeReasoningSignatureStreamPart

type ReasoningSignatureStreamPart struct {Signaturestring `json:"signature"`}

ReasoningSignatureStreamPart corresponds to TYPE_ID 'j'.

func (ReasoningSignatureStreamPart)Format

func (ReasoningSignatureStreamPart)TypeID

typeReasoningStreamPart

type ReasoningStreamPart struct {Contentstring}

ReasoningStreamPart corresponds to TYPE_ID 'g'.

func (ReasoningStreamPart)Format

func (pReasoningStreamPart) Format() (string,error)

func (ReasoningStreamPart)TypeID

func (pReasoningStreamPart) TypeID()byte

typeRedactedReasoningStreamPart

type RedactedReasoningStreamPart struct {Datastring `json:"data"`}

RedactedReasoningStreamPart corresponds to TYPE_ID 'i'.

func (RedactedReasoningStreamPart)Format

func (RedactedReasoningStreamPart)TypeID

typeSchemaadded inv0.0.3

type Schema struct {Required   []string       `json:"required"`Properties map[string]any `json:"properties"`}

typeSourceInfoadded inv0.0.3

type SourceInfo struct {URIstring         `json:"uri,omitempty"`ContentTypestring         `json:"contentType,omitempty"`Datastring         `json:"data,omitempty"`Metadata    map[string]any `json:"metadata,omitempty"`}

typeSourceStreamPart

type SourceStreamPart struct {SourceTypestring `json:"sourceType"`IDstring `json:"id"`URLstring `json:"url"`Titlestring `json:"title"`}

SourceStreamPart corresponds to TYPE_ID 'h'.

func (SourceStreamPart)Format

func (pSourceStreamPart) Format() (string,error)

func (SourceStreamPart)TypeID

func (pSourceStreamPart) TypeID()byte

typeStartStepStreamPart

type StartStepStreamPart struct {MessageIDstring `json:"messageId"`}

StartStepStreamPart corresponds to TYPE_ID 'f'.

func (StartStepStreamPart)Format

func (pStartStepStreamPart) Format() (string,error)

func (StartStepStreamPart)TypeID

func (pStartStepStreamPart) TypeID()byte

typeTextStreamPart

type TextStreamPart struct {Contentstring}

TextStreamPart corresponds to TYPE_ID '0'.

func (TextStreamPart)Format

func (pTextStreamPart) Format() (string,error)

func (TextStreamPart)TypeID

func (pTextStreamPart) TypeID()byte

typeTooladded inv0.0.2

type Tool struct {Namestring `json:"name"`Descriptionstring `json:"description"`SchemaSchema `json:"parameters"`}

typeToolCall

type ToolCall struct {IDstring         `json:"id"`Namestring         `json:"name"`Args map[string]any `json:"args"`}

ToolCall represents a tool call *request*.

typeToolCallDeltaStreamPart

type ToolCallDeltaStreamPart struct {ToolCallIDstring `json:"toolCallId"`ArgsTextDeltastring `json:"argsTextDelta"`}

ToolCallDeltaStreamPart corresponds to TYPE_ID 'c'.

func (ToolCallDeltaStreamPart)Format

func (ToolCallDeltaStreamPart)TypeID

typeToolCallResultadded inv0.0.7

type ToolCallResult interface {Part | []Part |any}

typeToolCallStartStreamPart

type ToolCallStartStreamPart struct {ToolCallIDstring `json:"toolCallId"`ToolNamestring `json:"toolName"`}

ToolCallStartStreamPart corresponds to TYPE_ID 'b'.

func (ToolCallStartStreamPart)Format

func (ToolCallStartStreamPart)TypeID

typeToolCallStreamPart

type ToolCallStreamPart struct {ToolCallIDstring         `json:"toolCallId"`ToolNamestring         `json:"toolName"`Args       map[string]any `json:"args"`}

ToolCallStreamPart corresponds to TYPE_ID '9'.

func (ToolCallStreamPart)Format

func (pToolCallStreamPart) Format() (string,error)

func (ToolCallStreamPart)TypeID

func (pToolCallStreamPart) TypeID()byte

typeToolInvocation

type ToolInvocation struct {StateToolInvocationState `json:"state"`Step       *int                `json:"step,omitempty"`ToolCallIDstring              `json:"toolCallId"`ToolNamestring              `json:"toolName"`Argsany                 `json:"args"`ResultToolCallResult      `json:"result,omitempty"`}

typeToolInvocationState

type ToolInvocationStatestring
const (ToolInvocationStateCallToolInvocationState = "call"ToolInvocationStatePartialCallToolInvocationState = "partial-call"ToolInvocationStateResultToolInvocationState = "result")

typeToolResultStreamPart

type ToolResultStreamPart struct {ToolCallIDstring         `json:"toolCallId"`ResultToolCallResult `json:"result"`}

ToolResultStreamPart corresponds to TYPE_ID 'a'.

func (ToolResultStreamPart)Format

func (pToolResultStreamPart) Format() (string,error)

func (ToolResultStreamPart)TypeID

func (pToolResultStreamPart) TypeID()byte

typeUsage

type Usage struct {PromptTokens     *int64 `json:"promptTokens"`CompletionTokens *int64 `json:"completionTokens"`}

Usage details the token usage.

Source Files

View all Source files

Directories

PathSynopsis

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f orF : Jump to
y orY : Canonical URL
go.dev uses cookies from Google to deliver and enhance the quality of its services and to analyze traffic.Learn more.

[8]ページ先頭

©2009-2025 Movatter.jp