feat: expand tax settings form, refactor settings save flow, and update docs (#159)

Expand the tax settings page with F-skatt, VAT registration, fiscal year start month, and salary payment toggles. Refactor SettingsFormWrapper to support onSuccess callbacks so local state only updates after server confirmation. Fix logo upload to use service client for storage RLS bypass. Allow empty email in settings schema. Update CLAUDE.md with comprehensive multi-tenant, auth, and engine documentation. Remove unused langchain skills.

Co-authored-by: Claude Opus 4.6 (1M context) <[email protected]>
This commit is contained in:
Jakob Wennberg
2026-04-01 21:14:05 +02:00
committed by GitHub
co-authored by Claude Opus 4.6
parent d0b3f21bde
commit 197beb1c58
13 changed files with 519 additions and 2213 deletions
-480
View File
@@ -1,480 +0,0 @@
---
name: langchain
description: Framework for building LLM-powered applications with agents, chains, and RAG. Supports multiple providers (OpenAI, Anthropic, Google), 500+ integrations, ReAct agents, tool calling, memory management, and vector store retrieval. Use for building chatbots, question-answering systems, autonomous agents, or RAG applications. Best for rapid prototyping and production deployments.
version: 1.0.0
author: Orchestra Research
license: MIT
tags: [Agents, LangChain, RAG, Tool Calling, ReAct, Memory Management, Vector Stores, LLM Applications, Chatbots, Production]
dependencies: [langchain, langchain-core, langchain-openai, langchain-anthropic]
---
# LangChain - Build LLM Applications with Agents & RAG
The most popular framework for building LLM-powered applications.
## When to use LangChain
**Use LangChain when:**
- Building agents with tool calling and reasoning (ReAct pattern)
- Implementing RAG (retrieval-augmented generation) pipelines
- Need to swap LLM providers easily (OpenAI, Anthropic, Google)
- Creating chatbots with conversation memory
- Rapid prototyping of LLM applications
- Production deployments with LangSmith observability
**Metrics**:
- **119,000+ GitHub stars**
- **272,000+ repositories** use LangChain
- **500+ integrations** (models, vector stores, tools)
- **3,800+ contributors**
**Use alternatives instead**:
- **LlamaIndex**: RAG-focused, better for document Q&A
- **LangGraph**: Complex stateful workflows, more control
- **Haystack**: Production search pipelines
- **Semantic Kernel**: Microsoft ecosystem
## Quick start
### Installation
```bash
# Core library (Python 3.10+)
pip install -U langchain
# With OpenAI
pip install langchain-openai
# With Anthropic
pip install langchain-anthropic
# Common extras
pip install langchain-community # 500+ integrations
pip install langchain-chroma # Vector store
```
### Basic LLM usage
```python
from langchain_anthropic import ChatAnthropic
# Initialize model
llm = ChatAnthropic(model="claude-sonnet-4-5-20250929")
# Simple completion
response = llm.invoke("Explain quantum computing in 2 sentences")
print(response.content)
```
### Create an agent (ReAct pattern)
```python
from langchain.agents import create_agent
from langchain_anthropic import ChatAnthropic
# Define tools
def get_weather(city: str) -> str:
"""Get current weather for a city."""
return f"It's sunny in {city}, 72°F"
def search_web(query: str) -> str:
"""Search the web for information."""
return f"Search results for: {query}"
# Create agent (<10 lines!)
agent = create_agent(
model=ChatAnthropic(model="claude-sonnet-4-5-20250929"),
tools=[get_weather, search_web],
system_prompt="You are a helpful assistant. Use tools when needed."
)
# Run agent
result = agent.invoke({"messages": [{"role": "user", "content": "What's the weather in Paris?"}]})
print(result["messages"][-1].content)
```
## Core concepts
### 1. Models - LLM abstraction
```python
from langchain_openai import ChatOpenAI
from langchain_anthropic import ChatAnthropic
from langchain_google_genai import ChatGoogleGenerativeAI
# Swap providers easily
llm = ChatOpenAI(model="gpt-4o")
llm = ChatAnthropic(model="claude-sonnet-4-5-20250929")
llm = ChatGoogleGenerativeAI(model="gemini-2.0-flash-exp")
# Streaming
for chunk in llm.stream("Write a poem"):
print(chunk.content, end="", flush=True)
```
### 2. Chains - Sequential operations
```python
from langchain.chains import LLMChain
from langchain.prompts import PromptTemplate
# Define prompt template
prompt = PromptTemplate(
input_variables=["topic"],
template="Write a 3-sentence summary about {topic}"
)
# Create chain
chain = LLMChain(llm=llm, prompt=prompt)
# Run chain
result = chain.run(topic="machine learning")
```
### 3. Agents - Tool-using reasoning
**ReAct (Reasoning + Acting) pattern:**
```python
from langchain.agents import create_tool_calling_agent, AgentExecutor
from langchain.tools import Tool
# Define custom tool
calculator = Tool(
name="Calculator",
func=lambda x: eval(x),
description="Useful for math calculations. Input: valid Python expression."
)
# Create agent with tools
agent = create_tool_calling_agent(
llm=llm,
tools=[calculator, search_web],
prompt="Answer questions using available tools"
)
# Create executor
agent_executor = AgentExecutor(agent=agent, tools=[calculator], verbose=True)
# Run with reasoning
result = agent_executor.invoke({"input": "What is 25 * 17 + 142?"})
```
### 4. Memory - Conversation history
```python
from langchain.memory import ConversationBufferMemory
from langchain.chains import ConversationChain
# Add memory to track conversation
memory = ConversationBufferMemory()
conversation = ConversationChain(
llm=llm,
memory=memory,
verbose=True
)
# Multi-turn conversation
conversation.predict(input="Hi, I'm Alice")
conversation.predict(input="What's my name?") # Remembers "Alice"
```
## RAG (Retrieval-Augmented Generation)
### Basic RAG pipeline
```python
from langchain_community.document_loaders import WebBaseLoader
from langchain.text_splitter import RecursiveCharacterTextSplitter
from langchain_openai import OpenAIEmbeddings
from langchain_chroma import Chroma
from langchain.chains import RetrievalQA
# 1. Load documents
loader = WebBaseLoader("https://docs.python.org/3/tutorial/")
docs = loader.load()
# 2. Split into chunks
text_splitter = RecursiveCharacterTextSplitter(
chunk_size=1000,
chunk_overlap=200
)
splits = text_splitter.split_documents(docs)
# 3. Create embeddings and vector store
vectorstore = Chroma.from_documents(
documents=splits,
embedding=OpenAIEmbeddings()
)
# 4. Create retriever
retriever = vectorstore.as_retriever(search_kwargs={"k": 4})
# 5. Create QA chain
qa_chain = RetrievalQA.from_chain_type(
llm=llm,
retriever=retriever,
return_source_documents=True
)
# 6. Query
result = qa_chain({"query": "What are Python decorators?"})
print(result["result"])
print(f"Sources: {result['source_documents']}")
```
### Conversational RAG with memory
```python
from langchain.chains import ConversationalRetrievalChain
# RAG with conversation memory
qa = ConversationalRetrievalChain.from_llm(
llm=llm,
retriever=retriever,
memory=ConversationBufferMemory(
memory_key="chat_history",
return_messages=True
)
)
# Multi-turn RAG
qa({"question": "What is Python used for?"})
qa({"question": "Can you elaborate on web development?"}) # Remembers context
```
## Advanced agent patterns
### Structured output
```python
from langchain_core.pydantic_v1 import BaseModel, Field
# Define schema
class WeatherReport(BaseModel):
city: str = Field(description="City name")
temperature: float = Field(description="Temperature in Fahrenheit")
condition: str = Field(description="Weather condition")
# Get structured response
structured_llm = llm.with_structured_output(WeatherReport)
result = structured_llm.invoke("What's the weather in SF? It's 65F and sunny")
print(result.city, result.temperature, result.condition)
```
### Parallel tool execution
```python
from langchain.agents import create_tool_calling_agent
# Agent automatically parallelizes independent tool calls
agent = create_tool_calling_agent(
llm=llm,
tools=[get_weather, search_web, calculator]
)
# This will call get_weather("Paris") and get_weather("London") in parallel
result = agent.invoke({
"messages": [{"role": "user", "content": "Compare weather in Paris and London"}]
})
```
### Streaming agent execution
```python
# Stream agent steps
for step in agent_executor.stream({"input": "Research AI trends"}):
if "actions" in step:
print(f"Tool: {step['actions'][0].tool}")
if "output" in step:
print(f"Output: {step['output']}")
```
## Common patterns
### Multi-document QA
```python
from langchain.chains.qa_with_sources import load_qa_with_sources_chain
# Load multiple documents
docs = [
loader.load("https://docs.python.org"),
loader.load("https://docs.numpy.org")
]
# QA with source citations
chain = load_qa_with_sources_chain(llm, chain_type="stuff")
result = chain({"input_documents": docs, "question": "How to use numpy arrays?"})
print(result["output_text"]) # Includes source citations
```
### Custom tools with error handling
```python
from langchain.tools import tool
@tool
def risky_operation(query: str) -> str:
"""Perform a risky operation that might fail."""
try:
# Your operation here
result = perform_operation(query)
return f"Success: {result}"
except Exception as e:
return f"Error: {str(e)}"
# Agent handles errors gracefully
agent = create_agent(model=llm, tools=[risky_operation])
```
### LangSmith observability
```python
import os
# Enable tracing
os.environ["LANGCHAIN_TRACING_V2"] = "true"
os.environ["LANGCHAIN_API_KEY"] = "your-api-key"
os.environ["LANGCHAIN_PROJECT"] = "my-project"
# All chains/agents automatically traced
agent = create_agent(model=llm, tools=[calculator])
result = agent.invoke({"input": "Calculate 123 * 456"})
# View traces at smith.langchain.com
```
## Vector stores
### Chroma (local)
```python
from langchain_chroma import Chroma
vectorstore = Chroma.from_documents(
documents=docs,
embedding=OpenAIEmbeddings(),
persist_directory="./chroma_db"
)
```
### Pinecone (cloud)
```python
from langchain_pinecone import PineconeVectorStore
vectorstore = PineconeVectorStore.from_documents(
documents=docs,
embedding=OpenAIEmbeddings(),
index_name="my-index"
)
```
### FAISS (similarity search)
```python
from langchain_community.vectorstores import FAISS
vectorstore = FAISS.from_documents(docs, OpenAIEmbeddings())
vectorstore.save_local("faiss_index")
# Load later
vectorstore = FAISS.load_local("faiss_index", OpenAIEmbeddings())
```
## Document loaders
```python
# Web pages
from langchain_community.document_loaders import WebBaseLoader
loader = WebBaseLoader("https://example.com")
# PDFs
from langchain_community.document_loaders import PyPDFLoader
loader = PyPDFLoader("paper.pdf")
# GitHub
from langchain_community.document_loaders import GithubFileLoader
loader = GithubFileLoader(repo="user/repo", file_filter=lambda x: x.endswith(".py"))
# CSV
from langchain_community.document_loaders import CSVLoader
loader = CSVLoader("data.csv")
```
## Text splitters
```python
# Recursive (recommended for general text)
from langchain.text_splitter import RecursiveCharacterTextSplitter
splitter = RecursiveCharacterTextSplitter(
chunk_size=1000,
chunk_overlap=200,
separators=["\n\n", "\n", " ", ""]
)
# Code-aware
from langchain.text_splitter import PythonCodeTextSplitter
splitter = PythonCodeTextSplitter(chunk_size=500)
# Semantic (by meaning)
from langchain_experimental.text_splitter import SemanticChunker
splitter = SemanticChunker(OpenAIEmbeddings())
```
## Best practices
1. **Start simple** - Use `create_agent()` for most cases
2. **Enable streaming** - Better UX for long responses
3. **Add error handling** - Tools can fail, handle gracefully
4. **Use LangSmith** - Essential for debugging agents
5. **Optimize chunk size** - 500-1000 chars for RAG
6. **Version prompts** - Track changes in production
7. **Cache embeddings** - Expensive, cache when possible
8. **Monitor costs** - Track token usage with LangSmith
## Performance benchmarks
| Operation | Latency | Notes |
|-----------|---------|-------|
| Simple LLM call | ~1-2s | Depends on provider |
| Agent with 1 tool | ~3-5s | ReAct reasoning overhead |
| RAG retrieval | ~0.5-1s | Vector search + LLM |
| Embedding 1000 docs | ~10-30s | Depends on model |
## LangChain vs LangGraph
| Feature | LangChain | LangGraph |
|---------|-----------|-----------|
| **Best for** | Quick agents, RAG | Complex workflows |
| **Abstraction level** | High | Low |
| **Code to start** | <10 lines | ~30 lines |
| **Control** | Simple | Full control |
| **Stateful workflows** | Limited | Native |
| **Cyclic graphs** | No | Yes |
| **Human-in-loop** | Basic | Advanced |
**Use LangGraph when:**
- Need stateful workflows with cycles
- Require fine-grained control
- Building multi-agent systems
- Production apps with complex logic
## References
- **[Agents Guide](references/agents.md)** - ReAct, tool calling, streaming
- **[RAG Guide](references/rag.md)** - Document loaders, retrievers, QA chains
- **[Integration Guide](references/integration.md)** - Vector stores, LangSmith, deployment
## Resources
- **GitHub**: https://github.com/langchain-ai/langchain ⭐ 119,000+
- **Docs**: https://docs.langchain.com
- **API Reference**: https://reference.langchain.com/python
- **LangSmith**: https://smith.langchain.com (observability)
- **Version**: 0.3+ (stable)
- **License**: MIT
@@ -1,499 +0,0 @@
# LangChain Agents Guide
Complete guide to building agents with ReAct, tool calling, and streaming.
## What are agents?
Agents combine language models with tools to solve complex tasks through reasoning and action:
1. **Reasoning**: LLM decides what to do
2. **Acting**: Execute tools based on reasoning
3. **Observation**: Receive tool results
4. **Loop**: Repeat until task complete
This is the **ReAct pattern** (Reasoning + Acting).
## Basic agent creation
```python
from langchain.agents import create_agent
from langchain_anthropic import ChatAnthropic
# Define tools
def calculator(expression: str) -> str:
"""Evaluate a math expression."""
return str(eval(expression))
def search(query: str) -> str:
"""Search for information."""
return f"Results for: {query}"
# Create agent
agent = create_agent(
model=ChatAnthropic(model="claude-sonnet-4-5-20250929"),
tools=[calculator, search],
system_prompt="You are a helpful assistant. Use tools when needed."
)
# Run agent
result = agent.invoke({
"messages": [{"role": "user", "content": "What is 25 * 17?"}]
})
print(result["messages"][-1].content)
```
## Agent components
### 1. Model - The reasoning engine
```python
from langchain_openai import ChatOpenAI
from langchain_anthropic import ChatAnthropic
# OpenAI
model = ChatOpenAI(model="gpt-4o", temperature=0)
# Anthropic (better for complex reasoning)
model = ChatAnthropic(model="claude-sonnet-4-5-20250929", temperature=0)
# Dynamic model selection
def select_model(task_complexity: str):
if task_complexity == "high":
return ChatAnthropic(model="claude-sonnet-4-5-20250929")
else:
return ChatOpenAI(model="gpt-4o-mini")
```
### 2. Tools - Actions the agent can take
```python
from langchain.tools import tool
# Simple function tool
@tool
def get_current_time() -> str:
"""Get the current time."""
from datetime import datetime
return datetime.now().strftime("%H:%M:%S")
# Tool with parameters
@tool
def fetch_weather(city: str, units: str = "fahrenheit") -> str:
"""Fetch weather for a city.
Args:
city: City name
units: Temperature units (fahrenheit or celsius)
"""
# Your weather API call here
return f"Weather in {city}: 72°{units[0].upper()}"
# Tool with error handling
@tool
def risky_api_call(endpoint: str) -> str:
"""Call an external API that might fail."""
try:
response = requests.get(endpoint, timeout=5)
return response.text
except Exception as e:
return f"Error calling API: {str(e)}"
```
### 3. System prompt - Agent behavior
```python
# General assistant
system_prompt = "You are a helpful assistant. Use tools when needed."
# Domain expert
system_prompt = """You are a financial analyst assistant.
- Use the calculator for precise calculations
- Search for recent financial data
- Provide data-driven recommendations
- Always cite your sources"""
# Constrained agent
system_prompt = """You are a customer support agent.
- Only use search_kb tool to find answers
- If answer not found, escalate to human
- Be concise and professional
- Never make up information"""
```
## Agent types
### 1. Tool-calling agent (recommended)
Uses native function calling for best performance:
```python
from langchain.agents import create_tool_calling_agent, AgentExecutor
from langchain.prompts import ChatPromptTemplate
# Create prompt
prompt = ChatPromptTemplate.from_messages([
("system", "You are a helpful assistant"),
("human", "{input}"),
("placeholder", "{agent_scratchpad}"),
])
# Create agent
agent = create_tool_calling_agent(
llm=model,
tools=[calculator, search],
prompt=prompt
)
# Wrap in executor
agent_executor = AgentExecutor(
agent=agent,
tools=[calculator, search],
verbose=True,
max_iterations=5,
handle_parsing_errors=True
)
# Run
result = agent_executor.invoke({"input": "What is the weather in Paris?"})
```
### 2. ReAct agent (reasoning trace)
Shows step-by-step reasoning:
```python
from langchain.agents import create_react_agent
# ReAct prompt shows thought process
react_prompt = """Answer the following questions as best you can. You have access to the following tools:
{tools}
Use the following format:
Question: the input question you must answer
Thought: you should always think about what to do
Action: the action to take, should be one of [{tool_names}]
Action Input: the input to the action
Observation: the result of the action
... (this Thought/Action/Action Input/Observation can repeat N times)
Thought: I now know the final answer
Final Answer: the final answer to the original input question
Begin!
Question: {input}
Thought: {agent_scratchpad}"""
agent = create_react_agent(
llm=model,
tools=[calculator, search],
prompt=ChatPromptTemplate.from_template(react_prompt)
)
# Run with visible reasoning
result = agent_executor.invoke({"input": "What is 25 * 17 + 142?"})
```
### 3. Conversational agent (with memory)
Remembers conversation history:
```python
from langchain.agents import create_conversational_retrieval_agent
from langchain.memory import ConversationBufferMemory
# Add memory
memory = ConversationBufferMemory(
memory_key="chat_history",
return_messages=True
)
# Conversational agent
agent_executor = AgentExecutor(
agent=agent,
tools=[calculator, search],
memory=memory,
verbose=True
)
# Multi-turn conversation
agent_executor.invoke({"input": "My name is Alice"})
agent_executor.invoke({"input": "What's my name?"}) # Remembers "Alice"
agent_executor.invoke({"input": "What is 25 * 17?"})
```
## Tool execution patterns
### Parallel tool execution
```python
# Agent automatically parallelizes independent calls
agent = create_tool_calling_agent(llm=model, tools=[get_weather, search])
# This calls get_weather("Paris") and get_weather("London") in parallel
result = agent_executor.invoke({
"input": "Compare weather in Paris and London"
})
```
### Sequential tool chaining
```python
# Agent chains tools automatically
@tool
def search_company(name: str) -> str:
"""Search for company information."""
return f"Company ID: 12345, Industry: Tech"
@tool
def get_stock_price(company_id: str) -> str:
"""Get stock price for a company."""
return f"${150.00}"
# Agent will: search_company → get_stock_price
result = agent_executor.invoke({
"input": "What is Apple's current stock price?"
})
```
### Conditional tool usage
```python
# Agent decides when to use tools
@tool
def expensive_tool(query: str) -> str:
"""Use only when necessary - costs $0.10 per call."""
return perform_expensive_operation(query)
# Agent uses tool only if needed
result = agent_executor.invoke({
"input": "What is 2+2?" # Won't use expensive_tool
})
```
## Streaming
### Stream agent steps
```python
# Stream intermediate steps
for step in agent_executor.stream({"input": "Research quantum computing"}):
if "actions" in step:
action = step["actions"][0]
print(f"Tool: {action.tool}, Input: {action.tool_input}")
if "steps" in step:
print(f"Observation: {step['steps'][0].observation}")
if "output" in step:
print(f"Final: {step['output']}")
```
### Stream LLM tokens
```python
from langchain.callbacks import StreamingStdOutCallbackHandler
# Stream model responses
agent_executor = AgentExecutor(
agent=agent,
tools=[calculator],
callbacks=[StreamingStdOutCallbackHandler()],
verbose=True
)
result = agent_executor.invoke({"input": "Explain quantum computing"})
```
## Error handling
### Tool error handling
```python
@tool
def fallible_tool(query: str) -> str:
"""A tool that might fail."""
try:
result = risky_operation(query)
return f"Success: {result}"
except Exception as e:
return f"Error: {str(e)}. Please try a different approach."
# Agent adapts to errors
agent_executor = AgentExecutor(
agent=agent,
tools=[fallible_tool],
handle_parsing_errors=True, # Handle malformed tool calls
max_iterations=5
)
```
### Timeout handling
```python
from langchain.callbacks import TimeoutCallback
# Set timeout
agent_executor = AgentExecutor(
agent=agent,
tools=[slow_tool],
callbacks=[TimeoutCallback(timeout=30)], # 30 second timeout
max_iterations=10
)
```
### Retry logic
```python
from langchain.callbacks import RetryCallback
# Retry on failure
agent_executor = AgentExecutor(
agent=agent,
tools=[unreliable_tool],
callbacks=[RetryCallback(max_retries=3)],
max_execution_time=60
)
```
## Advanced patterns
### Dynamic tool selection
```python
# Select tools based on context
def get_tools_for_user(user_role: str):
if user_role == "admin":
return [search, calculator, database_query, delete_data]
elif user_role == "analyst":
return [search, calculator, database_query]
else:
return [search, calculator]
# Create agent with role-based tools
tools = get_tools_for_user(current_user.role)
agent = create_agent(model=model, tools=tools)
```
### Multi-step reasoning
```python
# Agent plans multiple steps
system_prompt = """Break down complex tasks into steps:
1. Analyze the question
2. Determine required information
3. Use tools to gather data
4. Synthesize findings
5. Provide final answer"""
agent = create_agent(
model=model,
tools=[search, calculator, database],
system_prompt=system_prompt
)
result = agent.invoke({
"input": "Compare revenue growth of top 3 tech companies over 5 years"
})
```
### Structured output from agents
```python
from langchain_core.pydantic_v1 import BaseModel, Field
class ResearchReport(BaseModel):
summary: str = Field(description="Executive summary")
findings: list[str] = Field(description="Key findings")
sources: list[str] = Field(description="Source URLs")
# Agent returns structured output
structured_agent = agent.with_structured_output(ResearchReport)
report = structured_agent.invoke({"input": "Research AI safety"})
print(report.summary, report.findings)
```
## Middleware & customization
### Custom agent middleware
```python
from langchain.agents import AgentExecutor
def logging_middleware(agent_executor):
"""Log all agent actions."""
original_invoke = agent_executor.invoke
def wrapped_invoke(*args, **kwargs):
print(f"Agent invoked with: {args[0]}")
result = original_invoke(*args, **kwargs)
print(f"Agent result: {result}")
return result
agent_executor.invoke = wrapped_invoke
return agent_executor
# Apply middleware
agent_executor = logging_middleware(agent_executor)
```
### Custom stopping conditions
```python
from langchain.agents import EarlyStoppingMethod
# Stop early if confident
agent_executor = AgentExecutor(
agent=agent,
tools=[search],
early_stopping_method=EarlyStoppingMethod.GENERATE, # or FORCE
max_iterations=10
)
```
## Best practices
1. **Use tool-calling agents** - Fastest and most reliable
2. **Keep tool descriptions clear** - Agent needs to understand when to use each tool
3. **Add error handling** - Tools will fail, handle gracefully
4. **Set max_iterations** - Prevent infinite loops (default: 15)
5. **Enable streaming** - Better UX for long tasks
6. **Use verbose=True during dev** - See agent reasoning
7. **Test tool combinations** - Ensure tools work together
8. **Monitor with LangSmith** - Essential for production
9. **Cache tool results** - Avoid redundant API calls
10. **Version system prompts** - Track changes in behavior
## Common pitfalls
1. **Vague tool descriptions** - Agent won't know when to use tool
2. **Too many tools** - Agent gets confused (limit to 5-10)
3. **Tools without error handling** - One failure crashes agent
4. **Circular tool dependencies** - Agent gets stuck in loops
5. **Missing max_iterations** - Agent runs forever
6. **Poor system prompts** - Agent doesn't follow instructions
## Debugging agents
```python
# Enable verbose logging
agent_executor = AgentExecutor(
agent=agent,
tools=[calculator],
verbose=True, # See all steps
return_intermediate_steps=True # Get full trace
)
result = agent_executor.invoke({"input": "Calculate 25 * 17"})
# Inspect intermediate steps
for step in result["intermediate_steps"]:
print(f"Action: {step[0].tool}")
print(f"Input: {step[0].tool_input}")
print(f"Output: {step[1]}")
```
## Resources
- **ReAct Paper**: https://arxiv.org/abs/2210.03629
- **LangChain Agents Docs**: https://docs.langchain.com/oss/python/langchain/agents
- **LangSmith Debugging**: https://smith.langchain.com
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
+285 -35
View File
File diff suppressed because one or more lines are too long
@@ -25,8 +25,12 @@ export default function BookkeepingSettingsPage() {
auto_lock_period_days: autoLockValue === 'none' ? null : parseInt(autoLockValue),
accounting_method: accountingMethod,
}
updateSettings(updates as Partial<CompanySettings>)
return updates
return {
updates,
onSuccess: (data: Record<string, unknown>) => {
updateSettings(data as Partial<CompanySettings>)
},
}
}
return (
+6 -2
View File
@@ -24,8 +24,12 @@ export default function CompanySettingsPage() {
email: (formData.get('email') as string) || '',
website: (formData.get('website') as string) || '',
}
updateSettings(updates as Partial<CompanySettings>)
return updates
return {
updates,
onSuccess: (data: Record<string, unknown>) => {
updateSettings(data as Partial<CompanySettings>)
},
}
}
return (
+6 -2
View File
@@ -36,8 +36,12 @@ export default function InvoicingSettingsPage() {
invoice_default_days: parseInt(formData.get('invoice_default_days') as string) || 30,
invoice_default_notes: (formData.get('invoice_default_notes') as string) || null,
}
updateSettings(updates as Partial<CompanySettings>)
return updates
return {
updates,
onSuccess: (data: Record<string, unknown>) => {
updateSettings(data as Partial<CompanySettings>)
},
}
}
return (
+15 -3
View File
@@ -12,15 +12,27 @@ export default function TaxSettingsPage() {
if (isLoading || !settings) return <SettingsLoadingSkeleton />
function handleSave(formData: FormData) {
const vatRegistered = formData.get('vat_registered') === 'true'
const updates: Record<string, unknown> = {
f_skatt: formData.get('f_skatt') === 'true',
vat_registered: vatRegistered,
vat_number: vatRegistered ? ((formData.get('vat_number') as string) || null) : null,
moms_period: vatRegistered ? ((formData.get('moms_period') as string) || null) : null,
fiscal_year_start_month: parseInt(formData.get('fiscal_year_start_month') as string) || 1,
pays_salaries: formData.get('pays_salaries') === 'true',
preliminary_tax_monthly: parseFloat(formData.get('preliminary_tax_monthly') as string) || null,
}
updateSettings(updates as Partial<CompanySettings>)
return updates
return {
updates,
onSuccess: (data: Record<string, unknown>) => {
updateSettings(data as Partial<CompanySettings>)
},
}
}
return (
<SettingsFormWrapper onSave={handleSave} className="space-y-8">
<SettingsFormWrapper onSave={handleSave} className="space-y-0">
<TaxSettingsForm settings={settings} />
</SettingsFormWrapper>
)
+7 -5
View File
@@ -1,4 +1,4 @@
import { createClient } from '@/lib/supabase/server'
import { createClient, createServiceClient } from '@/lib/supabase/server'
import { NextResponse } from 'next/server'
import { requireCompanyId } from '@/lib/company/context'
@@ -32,8 +32,9 @@ export async function POST(request: Request) {
const ext = file.name.split('.').pop() || 'png'
const storagePath = `logos/${companyId}/logo.${ext}`
// Upload (upsert to replace existing)
const { error: uploadError } = await supabase.storage
// Upload with service client to bypass storage RLS (auth already verified above)
const serviceClient = createServiceClient()
const { error: uploadError } = await serviceClient.storage
.from('documents')
.upload(storagePath, buffer, {
contentType: file.type,
@@ -45,7 +46,7 @@ export async function POST(request: Request) {
}
// Get public URL
const { data: urlData } = supabase.storage
const { data: urlData } = serviceClient.storage
.from('documents')
.getPublicUrl(storagePath)
@@ -82,7 +83,8 @@ export async function DELETE() {
const url = new URL(settings.logo_url)
const pathMatch = url.pathname.match(/\/object\/public\/documents\/(.+)/)
if (pathMatch) {
await supabase.storage.from('documents').remove([pathMatch[1]])
const serviceClient = createServiceClient()
await serviceClient.storage.from('documents').remove([pathMatch[1]])
}
}
+12 -2
View File
@@ -5,9 +5,13 @@ import { Button } from '@/components/ui/button'
import { Loader2, Check } from 'lucide-react'
import { useToast } from '@/components/ui/use-toast'
type SaveResult =
| Record<string, unknown>
| { updates: Record<string, unknown>; onSuccess?: (data: Record<string, unknown>) => void }
interface SettingsFormWrapperProps {
children: React.ReactNode
onSave?: (formData: FormData) => Record<string, unknown>
onSave?: (formData: FormData) => SaveResult
className?: string
}
@@ -28,7 +32,12 @@ export function SettingsFormWrapper({ children, onSave, className }: SettingsFor
if (!onSave) return
const formData = new FormData(e.currentTarget)
const updates = onSave(formData)
const saveResult = onSave(formData)
// Support both plain object and { updates, onSuccess } return types
const isStructured = saveResult && 'updates' in saveResult && typeof saveResult.updates === 'object'
const updates = isStructured ? saveResult.updates : saveResult
const onSuccess = isStructured ? (saveResult as { onSuccess?: (data: Record<string, unknown>) => void }).onSuccess : undefined
if (!updates || Object.keys(updates).length === 0) return
@@ -48,6 +57,7 @@ export function SettingsFormWrapper({ children, onSave, className }: SettingsFor
throw new Error(result.error || 'Kunde inte spara inställningar')
}
onSuccess?.(result.data ?? updates)
setSaved(true)
timerRef.current = setTimeout(() => setSaved(false), 2000)
} catch (error) {
+181 -20
View File
@@ -1,7 +1,11 @@
'use client'
import { useState } from 'react'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import { Checkbox } from '@/components/ui/checkbox'
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'
import { Badge } from '@/components/ui/badge'
import type { CompanySettings } from '@/types'
interface TaxSettingsFormProps {
@@ -9,26 +13,183 @@ interface TaxSettingsFormProps {
}
export function TaxSettingsForm({ settings }: TaxSettingsFormProps) {
return (
<section className="space-y-4">
<h2 className="text-sm font-medium uppercase tracking-wider text-muted-foreground">
Preliminärskatt
</h2>
const [vatRegistered, setVatRegistered] = useState(settings.vat_registered ?? false)
const [fSkatt, setFSkatt] = useState(settings.f_skatt ?? true)
const [paysSalaries, setPaysSalaries] = useState(settings.pays_salaries ?? false)
<div className="max-w-xs space-y-2">
<Label htmlFor="preliminary_tax_monthly">
Månatlig preliminärskatt (F-skatt)
</Label>
<Input
id="preliminary_tax_monthly"
name="preliminary_tax_monthly"
type="number"
defaultValue={settings.preliminary_tax_monthly || ''}
/>
<p className="text-xs text-muted-foreground">
Belopp i SEK som betalas varje månad.
</p>
</div>
</section>
const isEnskildFirma = settings.entity_type === 'enskild_firma'
return (
<div className="space-y-8">
{/* Entity type — read-only */}
<section className="space-y-4">
<h2 className="text-sm font-medium uppercase tracking-wider text-muted-foreground">
Företagsform
</h2>
<div className="flex items-center gap-3">
<Badge variant="secondary" className="text-sm">
{settings.entity_type === 'aktiebolag' ? 'Aktiebolag' : 'Enskild firma'}
</Badge>
<p className="text-xs text-muted-foreground">
Företagsform kan inte ändras. Kontakta support vid behov.
</p>
</div>
</section>
{/* F-skatt */}
<section className="border-t border-border/8 pt-8 space-y-4">
<h2 className="text-sm font-medium uppercase tracking-wider text-muted-foreground">
Skatt & moms
</h2>
<div className="space-y-4">
<div className="flex items-start space-x-3">
<Checkbox
id="f_skatt"
checked={fSkatt}
onCheckedChange={(v) => setFSkatt(v === true)}
/>
<input type="hidden" name="f_skatt" value={fSkatt ? 'true' : 'false'} />
<div className="space-y-1">
<Label htmlFor="f_skatt" className="cursor-pointer">F-skattsedel</Label>
<p className="text-xs text-muted-foreground">
Godkänd för F-skatt (självständig näringsverksamhet).
</p>
</div>
</div>
<div className="flex items-start space-x-3">
<Checkbox
id="vat_registered"
checked={vatRegistered}
onCheckedChange={(v) => setVatRegistered(v === true)}
/>
<input type="hidden" name="vat_registered" value={vatRegistered ? 'true' : 'false'} />
<div className="space-y-1">
<Label htmlFor="vat_registered" className="cursor-pointer">Momsregistrerad</Label>
<p className="text-xs text-muted-foreground">
Obligatoriskt om omsättningen överstiger 120 000 kr per år.
</p>
</div>
</div>
{vatRegistered && (
<div className="space-y-4 pl-7">
<div className="max-w-xs space-y-2">
<Label htmlFor="vat_number">Momsregistreringsnummer</Label>
<Input
id="vat_number"
name="vat_number"
placeholder="SE123456789001"
defaultValue={settings.vat_number || ''}
/>
<p className="text-xs text-muted-foreground">
Format: SE + organisationsnummer + 01
</p>
</div>
<div className="max-w-xs space-y-2">
<Label>Momsredovisningsperiod</Label>
<Select
name="moms_period"
defaultValue={settings.moms_period || undefined}
>
<SelectTrigger>
<SelectValue placeholder="Välj period" />
</SelectTrigger>
<SelectContent>
<SelectItem value="monthly">Månad</SelectItem>
<SelectItem value="quarterly">Kvartal</SelectItem>
<SelectItem value="yearly">År</SelectItem>
</SelectContent>
</Select>
<p className="text-xs text-muted-foreground">
Enligt beslut från Skatteverket.
</p>
</div>
</div>
)}
</div>
</section>
{/* Fiscal year & salaries */}
<section className="border-t border-border/8 pt-8 space-y-4">
<h2 className="text-sm font-medium uppercase tracking-wider text-muted-foreground">
Räkenskapsår & löner
</h2>
<div className="max-w-xs space-y-2">
<Label>Räkenskapsårets startmånad</Label>
{isEnskildFirma ? (
<>
<Input value="Januari" disabled />
<input type="hidden" name="fiscal_year_start_month" value="1" />
<p className="text-xs text-muted-foreground">
Enskild firma måste använda kalenderår (BFL 3 kap.).
</p>
</>
) : (
<>
<Select
name="fiscal_year_start_month"
defaultValue={String(settings.fiscal_year_start_month || 1)}
>
<SelectTrigger>
<SelectValue />
</SelectTrigger>
<SelectContent>
{[
'Januari', 'Februari', 'Mars', 'April', 'Maj', 'Juni',
'Juli', 'Augusti', 'September', 'Oktober', 'November', 'December',
].map((month, i) => (
<SelectItem key={i + 1} value={String(i + 1)}>{month}</SelectItem>
))}
</SelectContent>
</Select>
<p className="text-xs text-muted-foreground">
Ändring påverkar framtida räkenskapsår.
</p>
</>
)}
</div>
<div className="flex items-start space-x-3">
<Checkbox
id="pays_salaries"
checked={paysSalaries}
onCheckedChange={(v) => setPaysSalaries(v === true)}
/>
<input type="hidden" name="pays_salaries" value={paysSalaries ? 'true' : 'false'} />
<div className="space-y-1">
<Label htmlFor="pays_salaries" className="cursor-pointer">Betalar löner</Label>
<p className="text-xs text-muted-foreground">
Påverkar vilka skattedeadlines som visas (arbetsgivardeklaration m.m.).
</p>
</div>
</div>
</section>
{/* Preliminary tax */}
<section className="border-t border-border/8 pt-8 space-y-4">
<h2 className="text-sm font-medium uppercase tracking-wider text-muted-foreground">
Preliminärskatt
</h2>
<div className="max-w-xs space-y-2">
<Label htmlFor="preliminary_tax_monthly">
Månatlig preliminärskatt (F-skatt)
</Label>
<Input
id="preliminary_tax_monthly"
name="preliminary_tax_monthly"
type="number"
defaultValue={settings.preliminary_tax_monthly || ''}
/>
<p className="text-xs text-muted-foreground">
Belopp i SEK som betalas varje månad.
</p>
</div>
</section>
</div>
)
}
+1 -1
View File
@@ -383,7 +383,7 @@ export const UpdateSettingsSchema = z.object({
invoice_default_days: z.number().int().positive().optional(),
invoice_default_notes: z.string().nullable().optional(),
phone: z.string().optional(),
email: z.string().email().optional(),
email: z.string().email().optional().or(z.literal('')),
website: z.string().optional().or(z.literal('')),
pays_salaries: z.boolean().optional(),
sector_slug: z.string().nullable().optional(),