mirror of
https://github.com/vxcontrol/langchaingo.git
synced 2026-08-24 21:31:28 -04:00
064f09155c
- Raised the `go` directive from 1.24.1 to 1.26.5 to satisfy pgx/v5 and ollama's minimum Go version requirements and to pick up 15 patched standard library CVEs. - Updated `pgx/v5`, `otel`/`otel/sdk`/`otlptracehttp`, `x/net`, and the AWS `eventstream` protocol package to their latest requested versions. - Remediated govulncheck-flagged CVEs in `grpc`, `x/text`, `x/crypto`, `antchfx/xpath`, AWS SDK `bedrock*`/`s3` services, `etcd/server`, and `mongo-driver` v1/v2. - Fixed ollama's `MainGPU` API type change (`int` -> `*int`) in `llms/ollama/options.go` without breaking the public `WithRunnerMainGPU` signature.
Google AI Structured Output Example
This example shows how to get schema-constrained structured output from a
Google Gemini model with the langchaingo library. Instead of parsing free-form
text, you pass a JSON Schema and get back a JSON value that matches it.
What This Example Does
- Sets up a Google AI (Gemini) client using your API key.
- Defines a JSON Schema describing the shape it wants back (a Moon landing:
mission,year, and anastronautsarray). - Calls
GenerateContentwithllms.WithStructuredOutput(...), passing that schema. - Unmarshals the response straight into a typed Go struct and prints it.
How It Works
llms.WithStructuredOutput(llms.StructuredOutputConfig{...})is the provider-neutral way to request structured output. It carries a raw JSON Schema (Draft 2020-12); the SDK sends it to Gemini viaresponseJsonSchemaand sets the response MIME type toapplication/json.- On a normal completion the SDK validates the response against your original
schema before returning it. So
resp.Choices[0].Contentis guaranteed to be a single JSON value matching the schema and unmarshals directly into a struct — no prompt engineering or manual cleanup. - If the model returns something that does not match, you get a typed
*llms.ErrStructuredOutputValidationinstead of a silent bad result.
The same WithStructuredOutput option works across providers (OpenAI, Anthropic,
Amazon Bedrock, Vertex, Ollama) — only the model and API key change.
Running the Example
-
Set your Google AI API key:
export GOOGLE_API_KEY=your_api_key_here -
Run the program:
go run googleai-structured-output-example.go -
Expected output (values come from the model):
Mission: Apollo 11 Year: 1969 Astronauts: [Neil Armstrong Buzz Aldrin Michael Collins]