232 Commits

Author SHA1 Message Date
Alexander Nalobin 95afeb6e4e examples: fix typo in openai-chat-example.go of maximum tokens per generation, old: 104 tokens, fix: 1024 tokens (#1392)
examples: change maximum tokens from 104 to 1024 in openai_chat_example.go as it says in README.md of the example

Fixing a typo of llms.WithMaxtokens(104) to llms.WithMaxtokens(1024)
2025-09-15 04:17:23 +02:00
Travis Cline 450c02a722 examples: update to v0.1.14-pre.4 (#1401)
chore: update all examples to use v0.1.14-pre.4

- Remove replace directives from 5 examples that had local path references
- Update all 75 example go.mod files to use the latest pre-release version
- Ensures examples work correctly for users who clone the repository
2025-09-14 20:54:54 +02:00
Travis Cline dff679c481 docs: complete the incomplete basic chat app tutorial (#1399)
docs: complete basic chat application tutorial with progressive examples

Completely rewrite the basic chat application tutorial with a structured, step-by-step approach:

**Tutorial Documentation**:
- Restructure tutorial into 6 clear progressive steps
- Add proper setup instructions and prerequisites
- Include code examples for each step with explanations
- Improve clarity and flow from basic to advanced concepts

**Complete Working Example**:
- Add `examples/tutorial-basic-chat-app/` with full implementation
- Include separate files for each tutorial step (step3-step6)
- Add comprehensive README with usage instructions
- Support multiple execution modes via command-line arguments

**Progressive Implementation Steps**:
- Step 3: Basic single-shot LLM interaction
- Step 4: Interactive chat loop without memory
- Step 5: Chat with manual conversation memory management
- Step 6: Advanced chat using chains with automatic memory

**Features Added**:
- Go module setup with proper dependencies
- Error handling and graceful exit functionality
- Multiple chat implementations demonstrating different approaches
- Clear documentation linking tutorial to working code
- Support for running individual steps or complete implementation

The tutorial now provides a complete learning path from basic LLM usage to sophisticated conversation management using LangChainGo's chains and memory systems.
2025-09-14 20:20:59 +02:00
Travis Cline 91fc754372 llms: add prompt caching and reasoning token support (#1394)
* llms: add prompt caching and reasoning token support

Add comprehensive infrastructure for prompt caching and reasoning/thinking tokens:

- Add ReasoningModel interface for models supporting extended reasoning
- Add CacheControl and CachedContent types for prompt caching
- Add ThinkingConfig with modes (none, low, medium, high, auto)
- Add token budget calculation and usage tracking for thinking tokens
- Add WithPromptCaching, WithThinking, and related call options
- Add model detection for reasoning-capable models (OpenAI o1/o3, Claude 3.7+, DeepSeek)
- Update options documentation for better provider compatibility notes
- Remove testify imports tracking file

Supports provider-specific implementations while maintaining consistent API.

* testing: add comprehensive LLM testing framework

Add standardized testing infrastructure for all LLM providers following Go's testing/fstest design philosophy:

- Add llmtest package with automatic capability discovery and parallel testing
- Add TestLLM function that probes and tests all supported LLM features
- Add provider-specific test files for all LLM implementations (anthropic, bedrock, cloudflare, cohere, ernie, fake, googleai, huggingface, llamafile, local, maritaca, mistral, ollama, openai, watsonx)
- Add comprehensive tests for prompt caching, reasoning tokens, and token utilization
- Add MockLLM implementation for testing without API calls
- Add ValidateLLM function for basic model validation
- Support automatic detection of streaming, tool calls, reasoning, and caching capabilities

The framework provides a simple API (TestLLM) that automatically discovers and tests all supported capabilities, enabling consistent testing across all provider implementations.

* llms: implement provider-specific prompt caching and reasoning support

Add comprehensive provider-specific implementations for prompt caching and reasoning tokens:

**Anthropic (Claude)**:
- Add prompt caching with ephemeral cache controls and beta headers
- Add extended thinking support for Claude 3.7+ with budget token configuration
- Add interleaved thinking for tool calls and 128K output support
- Add thinking content extraction from <thinking> tags
- Add cache token tracking (creation/read input tokens)

**Google AI (Gemini)**:
- Add CachingHelper for pre-created cached content management
- Add reasoning detection for Gemini 2.0+ models
- Add cached content support via metadata
- Add standardized token usage reporting with cache information

**Ollama**:
- Add ContextCache for in-memory conversation context caching
- Add reasoning support detection for DeepSeek R1, QwQ, and thinking models
- Add Think parameter support for reasoning-capable models
- Add cache statistics and hit/miss tracking

**OpenAI**:
- Add reasoning support detection for o1/o3 series and future GPT-5
- Add system message handling for models without system support (o1/o3)
- Add thinking content extraction and standardized token reporting
- Add metadata filtering to prevent internal fields from reaching API
- Add ReasoningEffort parameter preparation for future models

**Cross-provider features**:
- Implement ReasoningModel interface across all providers
- Add standardized GenerationInfo fields (ThinkingContent, ThinkingTokens, etc.)
- Add provider-specific options (WithPromptCaching, WithExtendedOutput, etc.)
- Add comprehensive test coverage for caching and reasoning features
- Add model capability detection and validation

All providers now support the unified prompt caching and reasoning interfaces while maintaining their specific implementation details and capabilities.

* examples: add comprehensive prompt caching and reasoning examples

Add practical examples demonstrating prompt caching and reasoning token features across multiple LLM providers:

**Anthropic Examples**:
- Add anthropic-extended-capabilities example showing combined extended thinking + 128K output
- Add anthropic-interleaved-thinking example demonstrating thinking between tool calls
- Show token budget management and thinking content extraction
- Include comprehensive README documentation for each example

**Multi-Provider Examples**:
- Add googleai-reasoning-caching example with Gemini 2.0+ reasoning and cached content
- Add ollama-reasoning-caching example with DeepSeek R1/QwQ models and context caching
- Add prompt-caching example showing Anthropic's 90% cost reduction on cached tokens
- Add reasoning-tokens example comparing o1-mini, Claude 3.7, and standard models

**Key Features Demonstrated**:
- Prompt caching for cost optimization and faster responses
- Reasoning/thinking tokens for improved response quality
- Token usage analysis and cache hit/miss tracking
- Provider-specific capabilities and configuration options
- Real-world use cases like data analysis, Q&A systems, and multi-step reasoning

All examples include detailed documentation, error handling, and clear output formatting to help developers understand and implement these advanced LLM features.

* gofmt: fix formatting in messages.go
2025-09-08 18:44:38 +02:00
Travis Cline 7cbb9b05f7 examples/groq: fixup groq example (#1385) 2025-08-29 15:48:02 +02:00
Travis Cline f1213d92d8 examples/groq: fix max_tokens compatibility issue (#1382)
examples/groq: add temporary replace directive

Add replace directive to use local langchaingo module. This ensures the example
works with the current codebase that includes the metadata filtering fix from
PR #1376.

The replace directive should be removed after the next release.
2025-08-29 15:39:07 +02:00
Travis Cline 827a36f321 examples: update examples to v0.1.14-pre.3
Update all example project go.mod files to reference v0.1.14-pre.3
instead of v0.1.14-pre.2. This ensures examples use the latest pre-release
version with recent fixes and improvements.
2025-08-23 19:17:47 +02:00
Travis Cline 6d75f33614 examples: update examples to v0.1.14-pre.2 (#1373)
Update all example project go.mod files to reference v0.1.14-pre.2
instead of v0.1.14-pre.1. This ensures examples use the latest pre-release
version with recent fixes and improvements.
2025-08-19 20:36:29 +02:00
Travis Cline 99951bca92 httprr: improve test recording stability and add utilities (#1368)
* build: add examples-updater tool and update examples to v0.1.14-pre.1

Add a new tool to automate updating langchaingo version references in example
projects and use it to update all examples to v0.1.14-pre.1. The tool also
removes temporary replace directives that are no longer needed.

- Add update-examples Makefile target that runs the new tool
- Create internal/devtools/examples-updater implementation
- Update all example go.mod files to reference v0.1.14-pre.1
- Remove replace directives in googleai and vertex examples
- Update dependencies in main go.mod/go.sum

* httprr: improve header normalization and test container setup

Add header normalization to make HTTP recordings more stable:
- Add normalizeGoogleAPIClientHeader and normalizeVersionHeader functions
- Normalize User-Agent, x-goog-api-client and other version headers
- Remove OpenAI-Project header for consistency
- Preserve body for both replay lookup and recording
- Add comprehensive tests for header normalization

Improve testcontainer environment detection:
- Better handling of non-standard Docker socket paths
- Disable Ryuk reaper by default for resource efficiency
- Add verbose logging option via environment variable

* httputil: add ApiKeyTransport for query parameter API keys

Add a reusable ApiKeyTransport that adds API keys to URL query parameters:
- Create ApiKeyTransport implementation in httputil package
- Add comprehensive tests for the new transport
- Refactor googleai_test.go to use the shared transport
- Update chains/llm_test.go to use ApiKeyTransport with proper key scrubbing

This improves how API keys are handled with client libraries that don't
properly set keys when using custom HTTP clients, particularly useful
with httprr for testing Google API integrations.

* openai: remove duplicate MaxTokens field assignment

Remove redundant assignment where both MaxTokens and MaxCompletionTokens
were being set to the same value. MaxCompletionTokens is the preferred
field name that reflects OpenAI's API changes, while MaxTokens was
previously kept for backward compatibility.

* vectorstores/maridadb: add test infrastructure for MariaDB vectorstore

Add TestMain function for MariaDB vectorstore tests that ensures the proper
test environment is set up using the testctr package. This enables consistent
test container setup and teardown for MariaDB integration tests.

* all: normalize all httprr recordings for consistency

Update test recordings across all packages to use normalized headers:
- Standardize User-Agent to 'langchaingo-httprr'
- Normalize version information in x-goog-api-client headers
- Remove OpenAI-Project headers for consistency
- Fix deprecated Anthropic completion API tests
- Update HuggingFace test recordings with valid responses

These changes make test recordings stable across dependency updates
and different environments, preventing test failures from version changes.

* devtools: add utility tool for normalizing httprr test recordings

Add a command-line tool that standardizes version information in httprr recordings:
- Normalizes x-goog-api-client headers to use placeholder versions
- Standardizes x-amz-user-agent headers for consistency
- Replaces Go version strings with generic placeholders
- Supports dry-run mode to preview changes without modifying files
- Includes verbose output option for detailed change reporting

This tool helps maintain consistent test recordings across different environments
and dependency versions, preventing test failures from version changes.

* llms/openai: update OpenAI embedding test to use text-embedding-3-small model

Update the embedding test to use the current text-embedding-3-small model:
- Change model from text-embedding-ada-002 to text-embedding-3-small
- Adjust dimensions parameter from 1234 to 256 to match model capabilities
- Update test recording with appropriate response data

This change ensures tests remain compatible with OpenAI's current embedding
models and prevents test failures from API version changes.
2025-08-18 19:41:52 +02:00
Dreamans 76ce69b128 llms/bedrock: add modelProvider option and Nova model support (#1346)
- Add WithModelProvider option to explicitly set provider for edge cases
- Improve provider detection to handle Nova models and inference profiles
- Add comprehensive unit tests for Nova provider detection
- Add bedrock-provider-example demonstrating usage
- Fix CreateCompletion to accept optional provider parameter

This allows users to specify the provider explicitly when automatic
detection doesn't work correctly (e.g., custom inference endpoints),
and adds full support for Amazon Nova models.

Fixes: #1345

Co-authored-by: Travis Cline <travis.cline@gmail.com>
2025-08-18 14:03:37 +02:00
Travis Cline 380aec7d37 llms: fix memory and goroutine leaks in GoogleAI/Vertex and OpenAI streaming (#1364)
* llms: fix memory leaks by adding Close methods and improving goroutine handling

Add Close methods to GoogleAI and Vertex clients to properly clean up resources
and prevent memory leaks from underlying gRPC connections. Update examples to
demonstrate proper client cleanup with defer statements.

Improve goroutine management in OpenAI streaming response handling with proper
context cancellation and non-blocking channel operations to prevent goroutine
leaks in error scenarios.

* examples: add replace directives for testing memory leak fixes

Add temporary replace directives to GoogleAI and Vertex example go.mod files
to test the Close() method changes from the previous commit. These directives
allow the examples to use the local version of the library with the memory
leak fixes before they're included in the next release.
2025-08-16 20:53:01 +02:00
Travis Cline 57a517b279 examples: update to use v0.1.14-pre.0 (#1353) 2025-08-08 22:27:43 +02:00
Travis Cline a646e448bc llms/openai: add OpenRouter support with streaming fix (#1350)
This commit adds full support for OpenRouter, fixing streaming response parsing
errors that occurred when providers send non-JSON prefixes in their SSE streams.

Fixes #1172, Fixes #942
2025-08-08 19:17:20 +02:00
Travis Cline efaf02537b prompts: Prompt template improvements and docs expansion (#1348)
* prompts: add secure template rendering with filesystem support
* prompts: add comprehensive tests and examples

- Add security effectiveness tests for all attack vectors
- Add template rendering tests with all formats
- Add filesystem template tests with MapFS
- Add prompt template examples demonstrating all features
- Improve error handling and add local package references

* docs: add comprehensive prompt template documentation

- Add prompt template user guide with security section
- Add detailed API documentation for new functions
- Update partial values documentation
- Add template-related terms to style guide
- Document migration patterns and security considerations

* prompts: split template implementations by engine type

- Move Go template implementation to templates_go.go
- Move Jinja2 template implementation to templates_jinja2.go
- Clean up imports in templates.go
- Maintain all existing functionality with better code organization

* prompts: move security tests to dedicated file with expanded coverage

- Create new security_test.go file for all template security tests
- Expand test coverage for path traversal attacks in Jinja2 templates
- Add tests for migration patterns from vulnerable to secure implementations
- Remove redundant security tests from templates_test.go
- Improve organization of test code for better maintainability
2025-08-08 18:32:06 +02:00
Travis Cline 080815432a deps: update dependencies (#1319)
* deps: update base go and docs dependencies
* googleai: update test to match text-embedding-005 model name
2025-06-28 22:40:45 +02:00
Travis Cline 77504b877f all: expand test coverage (#1312)
* scripts: cleanup test scripts
* lint: add test pattern and architectural linting
* internal/httprr: expand httprr testing
* test: add comprehensive unit test coverage
* docs: add comprehensive testing guide to CONTRIBUTING.md
* examples: standardize module versions and cleanup dependencies
* all: re-record several httprr recordings
2025-06-16 18:14:02 +02:00
Travis Cline c544fb77bd all: add broad httprr coverage, update dependencies, organize go.mod file, bump to 1.23 (#1299)
* all: add broad httprr coverage, update dependencies, organize go.mod file, bump to 1.23

update go version to 1.23
add lots of test coverage via httprr recordings
update dependencies and organize go.mod
add testutil/testctr which helps work around a testcontainers-go+colima bug
expand the huggingface implementation and tests
expand capabilities of the ollama package
2025-06-04 11:41:45 -07:00
Travis Cline 94f289e427 httprr: add httprr package (#1296)
* httprr: add HTTP record/replay framework with default API key scrubbing

- Add httprr package for deterministic HTTP testing
- Implement default scrubbing for common API key headers

* httputil: reorganize transport layer and add logging infrastructure

- Replace debug transports with structured logging via slog
- Add comprehensive user agent handling with version info
- Improve transport layer organization and documentation
- Maintain backward compatibility with deprecated types
- Add JSON debug transport with color output support
2025-06-04 08:35:32 -07:00
Travis Cline 6c81282073 examples: Fix examples and complete linting upgrade (#1288)
* examples: update examples, clean up module declarations

- Fix and relax lint rules (for now)
- Clean up and fix module declarations
- Add .gitattributes to mark go.sum as binary

* ci: separate and enhance CI workflows

- Split example builds into dedicated workflow
- Add comprehensive test coverage reporting
- Improve CI structure with matrix testing
- Add race condition testing
- Add automated PR coverage comments

* test: improve test reliability and agent message handling

- Simplify MRKL agent test to use basic math calculation
- Update OpenAI functions agent to use ToolChatMessage
- Add proper environment checks for Zep integration tests

* agents: fix issue in tool call handling for openai function agent
2025-06-03 07:52:03 -07:00
Averi Kitsch 77b2d7bf3a memory: add interfaces for Google AlloyDB and Cloud SQL (#1205)
* memory: add interfaces for Google AlloyDB and Cloud SQL
2025-04-17 14:01:24 -07:00
Averi Kitsch 017409785d vectorstore: Add interfaces for Google AlloyDB and Cloud SQL (#1204)
* feat(google): Add Google AlloyDB and Cloud SQL vectorstore and chat history

* vectorstore: Add interfaces for Google AlloyDB and Cloud SQL
2025-04-17 13:03:52 -07:00
Manuel de la Peña 8d4c17fc73 ci: migrate linting golangci-lint to v2.0.2 (#1217)
* chore: use slices and maps packages

* chore: skip embedded type

* chore: use fmt.Fprint instead

* chore: use switch

* chore: reorder imports

* chore: add white lines

* chore: use t.Setenv

* chore: excplicitly omit non used param

* chore: use t.TempDir

* chore: use maps package

* chore: migrate golangci-lint config file

Run: "golangci-lint migrate -c .golangci.yaml --skip-validation"

* chore: bump golangci-lint action to v7
2025-04-12 01:54:50 -07:00
douglarek d3e43b6321 feat: implement StreamingReasoningFunc for reasoning models (#1125)
* feat: implement StreamingReasoningFunc for resoning models

* Using deepseek example for streaming reasoning content
2025-02-12 20:46:59 -08:00
Jérôme Schaeffer 96d0b285c9 anthropic: Add support for multi content part and images content in human messages. (#1141)
* anthropic: Add support for multi content part  in human messages.

* examples: Add Anthropic Vision example

* fix: move base64 encoding in the lib
2025-02-12 20:44:54 -08:00
Travis Cline fce56ba86e examples: Update to v0.1.13-pre.1 (#1140) 2025-02-09 04:15:07 -08:00
semioz 1bea9fbb7c fix example code 2025-01-31 17:40:53 +03:00
semioz 4aaace909e extra field 2025-01-31 17:36:11 +03:00
semioz a9663cb599 initial commit for deepseek reasoning 2025-01-31 17:21:05 +03:00
Preston Vasquez d686479379 Merge branch 'main' into GODRIVER-3336 2025-01-29 10:09:40 -07:00
Aksel d7270c03a7 Merge pull request #1099 from lifejwang11/main
add image and text content example to openai
2025-01-28 22:49:52 +05:30
Aksel a4e1e5a836 Merge pull request #1086 from mathiasb/feature-mistral-embedding-pgvector
llms/mistral: Implementing embeddings.EmbedderClient for Mistral and an example with PGVector
2025-01-28 16:53:44 +05:30
Preston Vasquez 29e0652977 Update field path 2025-01-13 14:05:20 -07:00
lifejwang11 e1c161d893 add image and text content example to openai 2025-01-08 11:18:11 +08:00
lifejwang11 38f9cf9827 missing file 2025-01-08 11:06:43 +08:00
lifejwang11 76e205135d add json structured example 2025-01-07 15:03:47 +08:00
Mathias Bergqvist 315def00b9 Example is using the new local copy of the Mistral Model which implements CreateEmbedding and the embeddings.EmbedderClient interface 2024-12-28 11:05:06 +01:00
Mathias Bergqvist f5ce2417e1 updated package name in go.mod files and go mod tidy to be ready for PR 2024-12-28 09:38:17 +01:00
Mathias Bergqvist 81ac143ea4 Embedding for Mistral and an example with Mistral Embed and PGVector 2024-12-09 22:09:07 +01:00
Preston Vasquez 70f5232532 Remove return 2024-11-08 15:41:09 -07:00
Preston Vasquez 0fd1352737 Update search index lookup 2024-11-08 15:03:58 -07:00
Preston Vasquez fb5770a955 Clean up enumeration 2024-11-08 11:55:28 -07:00
Preston Vasquez 17fccc9ce7 Add README.md and example 2024-11-08 11:44:35 -07:00
Travis Cline 179400979a Update examples to v0.1.13-pre.0 (#1021)
* examples: Point examples to v0.1.13-pre.0

* examples: fix typo in o1
2024-09-12 22:05:12 -07:00
Travis Cline 54f31943b8 examples: improve o1 readme (#1020) 2024-09-12 22:02:35 -07:00
elnoro 71160f9212 examples: replaced compose v1 with compose v2 in readme for pgvector example (#969)
replaced compose v1 with compose v2 in readme
2024-09-12 17:55:54 -07:00
Pierre Lafievre 71f5789911 examples: replace deprecated agents.Initialize (#1009) 2024-09-12 17:27:40 -07:00
Martin Heck 39a5ac9339 googleai: add support for JSONMode and ResponseMIMEType (#984)
* googleai: add support for JSONMode and ResponseMIMEType

* llms: update comments to match linting rules
2024-09-12 17:17:27 -07:00
Simon Klinkert 50827625b2 Add perplexity completion example (#977) 2024-09-12 17:14:28 -07:00
Travis Cline f01a52c6f7 examples: Add openai o1-preview example (#1017)
examples: add openai-o1-example
2024-09-13 00:09:02 +00:00
Eli Bendersky b508f9b08f examples: update go.mod to point to latest release (#937) 2024-06-27 07:12:54 -07:00