Merge branch 'main' into ConnectorCode
This commit is contained in:
182
instructions/astro.instructions.md
Normal file
182
instructions/astro.instructions.md
Normal file
@@ -0,0 +1,182 @@
|
||||
---
|
||||
description: 'Astro development standards and best practices for content-driven websites'
|
||||
applyTo: '**/*.astro, **/*.ts, **/*.js, **/*.md, **/*.mdx'
|
||||
---
|
||||
|
||||
# Astro Development Instructions
|
||||
|
||||
Instructions for building high-quality Astro applications following the content-driven, server-first architecture with modern best practices.
|
||||
|
||||
## Project Context
|
||||
- Astro 5.x with Islands Architecture and Content Layer API
|
||||
- TypeScript for type safety and better DX with auto-generated types
|
||||
- Content-driven websites (blogs, marketing, e-commerce, documentation)
|
||||
- Server-first rendering with selective client-side hydration
|
||||
- Support for multiple UI frameworks (React, Vue, Svelte, Solid, etc.)
|
||||
- Static site generation (SSG) by default with optional server-side rendering (SSR)
|
||||
- Enhanced performance with modern content loading and build optimizations
|
||||
|
||||
## Development Standards
|
||||
|
||||
### Architecture
|
||||
- Embrace the Islands Architecture: server-render by default, hydrate selectively
|
||||
- Organize content with Content Collections for type-safe Markdown/MDX management
|
||||
- Structure projects by feature or content type for scalability
|
||||
- Use component-based architecture with clear separation of concerns
|
||||
- Implement progressive enhancement patterns
|
||||
- Follow Multi-Page App (MPA) approach over Single-Page App (SPA) patterns
|
||||
|
||||
### TypeScript Integration
|
||||
- Configure `tsconfig.json` with recommended v5.0 settings:
|
||||
```json
|
||||
{
|
||||
"extends": "astro/tsconfigs/base",
|
||||
"include": [".astro/types.d.ts", "**/*"],
|
||||
"exclude": ["dist"]
|
||||
}
|
||||
```
|
||||
- Types auto-generated in `.astro/types.d.ts` (replaces `src/env.d.ts`)
|
||||
- Run `astro sync` to generate/update type definitions
|
||||
- Define component props with TypeScript interfaces
|
||||
- Leverage auto-generated types for content collections and Content Layer API
|
||||
|
||||
### Component Design
|
||||
- Use `.astro` components for static, server-rendered content
|
||||
- Import framework components (React, Vue, Svelte) only when interactivity is needed
|
||||
- Follow Astro's component script structure: frontmatter at top, template below
|
||||
- Use meaningful component names following PascalCase convention
|
||||
- Keep components focused and composable
|
||||
- Implement proper prop validation and default values
|
||||
|
||||
### Content Collections
|
||||
|
||||
#### Modern Content Layer API (v5.0+)
|
||||
- Define collections in `src/content.config.ts` using the new Content Layer API
|
||||
- Use built-in loaders: `glob()` for file-based content, `file()` for single files
|
||||
- Leverage enhanced performance and scalability with the new loading system
|
||||
- Example with Content Layer API:
|
||||
```typescript
|
||||
import { defineCollection, z } from 'astro:content';
|
||||
import { glob } from 'astro/loaders';
|
||||
|
||||
const blog = defineCollection({
|
||||
loader: glob({ pattern: '**/*.md', base: './src/content/blog' }),
|
||||
schema: z.object({
|
||||
title: z.string(),
|
||||
pubDate: z.date(),
|
||||
tags: z.array(z.string()).optional()
|
||||
})
|
||||
});
|
||||
```
|
||||
|
||||
#### Legacy Collections (backward compatible)
|
||||
- Legacy `type: 'content'` collections still supported via automatic glob() implementation
|
||||
- Migrate existing collections by adding explicit `loader` configuration
|
||||
- Use type-safe queries with `getCollection()` and `getEntry()`
|
||||
- Structure content with frontmatter validation and auto-generated types
|
||||
|
||||
### View Transitions & Client-Side Routing
|
||||
- Enable with `<ClientRouter />` component in layout head (renamed from `<ViewTransitions />` in v5.0)
|
||||
- Import from `astro:transitions`: `import { ClientRouter } from 'astro:transitions'`
|
||||
- Provides SPA-like navigation without full page reloads
|
||||
- Customize transition animations with CSS and view-transition-name
|
||||
- Maintain state across page navigations with persistent islands
|
||||
- Use `transition:persist` directive to preserve component state
|
||||
|
||||
### Performance Optimization
|
||||
- Default to zero JavaScript - only add interactivity where needed
|
||||
- Use client directives strategically (`client:load`, `client:idle`, `client:visible`)
|
||||
- Implement lazy loading for images and components
|
||||
- Optimize static assets with Astro's built-in optimization
|
||||
- Leverage Content Layer API for faster content loading and builds
|
||||
- Minimize bundle size by avoiding unnecessary client-side JavaScript
|
||||
|
||||
### Styling
|
||||
- Use scoped styles in `.astro` components by default
|
||||
- Implement CSS preprocessing (Sass, Less) when needed
|
||||
- Use CSS custom properties for theming and design systems
|
||||
- Follow mobile-first responsive design principles
|
||||
- Ensure accessibility with semantic HTML and proper ARIA attributes
|
||||
- Consider utility-first frameworks (Tailwind CSS) for rapid development
|
||||
|
||||
### Client-Side Interactivity
|
||||
- Use framework components (React, Vue, Svelte) for interactive elements
|
||||
- Choose the right hydration strategy based on user interaction patterns
|
||||
- Implement state management within framework boundaries
|
||||
- Handle client-side routing carefully to maintain MPA benefits
|
||||
- Use Web Components for framework-agnostic interactivity
|
||||
- Share state between islands using stores or custom events
|
||||
|
||||
### API Routes and SSR
|
||||
- Create API routes in `src/pages/api/` for dynamic functionality
|
||||
- Use proper HTTP methods and status codes
|
||||
- Implement request validation and error handling
|
||||
- Enable SSR mode for dynamic content requirements
|
||||
- Use middleware for authentication and request processing
|
||||
- Handle environment variables securely
|
||||
|
||||
### SEO and Meta Management
|
||||
- Use Astro's built-in SEO components and meta tag management
|
||||
- Implement proper Open Graph and Twitter Card metadata
|
||||
- Generate sitemaps automatically for better search indexing
|
||||
- Use semantic HTML structure for better accessibility and SEO
|
||||
- Implement structured data (JSON-LD) for rich snippets
|
||||
- Optimize page titles and descriptions for search engines
|
||||
|
||||
### Image Optimization
|
||||
- Use Astro's `<Image />` component for automatic optimization
|
||||
- Implement responsive images with proper srcset generation
|
||||
- Use WebP and AVIF formats for modern browsers
|
||||
- Lazy load images below the fold
|
||||
- Provide proper alt text for accessibility
|
||||
- Optimize images at build time for better performance
|
||||
|
||||
### Data Fetching
|
||||
- Fetch data at build time in component frontmatter
|
||||
- Use dynamic imports for conditional data loading
|
||||
- Implement proper error handling for external API calls
|
||||
- Cache expensive operations during build process
|
||||
- Use Astro's built-in fetch with automatic TypeScript inference
|
||||
- Handle loading states and fallbacks appropriately
|
||||
|
||||
### Build & Deployment
|
||||
- Optimize static assets with Astro's built-in optimizations
|
||||
- Configure deployment for static (SSG) or hybrid (SSR) rendering
|
||||
- Use environment variables for configuration management
|
||||
- Enable compression and caching for production builds
|
||||
|
||||
## Key Astro v5.0 Updates
|
||||
|
||||
### Breaking Changes
|
||||
- **ClientRouter**: Use `<ClientRouter />` instead of `<ViewTransitions />`
|
||||
- **TypeScript**: Auto-generated types in `.astro/types.d.ts` (run `astro sync`)
|
||||
- **Content Layer API**: New `glob()` and `file()` loaders for enhanced performance
|
||||
|
||||
### Migration Example
|
||||
```typescript
|
||||
// Modern Content Layer API
|
||||
import { defineCollection, z } from 'astro:content';
|
||||
import { glob } from 'astro/loaders';
|
||||
|
||||
const blog = defineCollection({
|
||||
loader: glob({ pattern: '**/*.md', base: './src/content/blog' }),
|
||||
schema: z.object({ title: z.string(), pubDate: z.date() })
|
||||
});
|
||||
```
|
||||
|
||||
## Implementation Guidelines
|
||||
|
||||
### Development Workflow
|
||||
1. Use `npm create astro@latest` with TypeScript template
|
||||
2. Configure Content Layer API with appropriate loaders
|
||||
3. Set up TypeScript with `astro sync` for type generation
|
||||
4. Create layout components with Islands Architecture
|
||||
5. Implement content pages with SEO and performance optimization
|
||||
|
||||
### Astro-Specific Best Practices
|
||||
- **Islands Architecture**: Server-first with selective hydration using client directives
|
||||
- **Content Layer API**: Use `glob()` and `file()` loaders for scalable content management
|
||||
- **Zero JavaScript**: Default to static rendering, add interactivity only when needed
|
||||
- **View Transitions**: Enable SPA-like navigation with `<ClientRouter />`
|
||||
- **Type Safety**: Leverage auto-generated types from Content Collections
|
||||
- **Performance**: Optimize with built-in image optimization and minimal client bundles
|
||||
@@ -7,7 +7,7 @@ applyTo: '**/*.{clj,cljs,cljc,bb,edn.mdx?}'
|
||||
|
||||
## Code Evaluation Tool usage
|
||||
|
||||
“Use the repl” means to use the **Evaluate Clojure Code** tool from Calva Backseat Driver. It connects you to the the same REPL as the user is connected to via Calva.
|
||||
“Use the repl” means to use the **Evaluate Clojure Code** tool from Calva Backseat Driver. It connects you to the same REPL as the user is connected to via Calva.
|
||||
|
||||
- Always stay inside Calva's REPL instead of launching a second one from the terminal.
|
||||
- If there is no REPL connection, ask the user to connect the REPL instead of trying to start and connect it yourself.
|
||||
@@ -36,12 +36,67 @@ Docstrings belong immediately after the function name and before the argument ve
|
||||
|
||||
- Define functions before they are used—prefer ordering over `declare` except when truly necessary.
|
||||
|
||||
## Interactive Programming (a.k.a. REPL Driven Development)
|
||||
|
||||
### Align Data Structure Elements for Bracket Balancing
|
||||
**Always align multi-line elements vertically in all data structures: vectors, maps, lists, sets, all code (since Clojure code is data). Misalignment causes the bracket balancer to close brackets incorrectly, creating invalid forms.**
|
||||
|
||||
```clojure
|
||||
;; ❌ Wrong - misaligned vector elements
|
||||
(select-keys m [:key-a
|
||||
:key-b
|
||||
:key-c]) ; Misalignment → incorrect ] placement
|
||||
|
||||
;; ✅ Correct - aligned vector elements
|
||||
(select-keys m [:key-a
|
||||
:key-b
|
||||
:key-c]) ; Proper alignment → correct ] placement
|
||||
|
||||
;; ❌ Wrong - misaligned map entries
|
||||
{:name "Alice"
|
||||
:age 30
|
||||
:city "Oslo"} ; Misalignment → incorrect } placement
|
||||
|
||||
;; ✅ Correct - aligned map entries
|
||||
{:name "Alice"
|
||||
:age 30
|
||||
:city "Oslo"} ; Proper alignment → correct } placement
|
||||
```
|
||||
|
||||
**Critical**: The bracket balancer relies on consistent indentation to determine structure.
|
||||
|
||||
### REPL Dependency Management
|
||||
Use `clojure.repl.deps/add-libs` for dynamic dependency loading during REPL sessions.
|
||||
|
||||
```clojure
|
||||
(require '[clojure.repl.deps :refer [add-libs]])
|
||||
(add-libs '{dk.ative/docjure {:mvn/version "1.15.0"}})
|
||||
```
|
||||
|
||||
- Dynamic dependency loading requires Clojure 1.12 or later
|
||||
- Perfect for library exploration and prototyping
|
||||
|
||||
### Checking Clojure Version
|
||||
|
||||
```clojure
|
||||
*clojure-version*
|
||||
;; => {:major 1, :minor 12, :incremental 1, :qualifier nil}
|
||||
```
|
||||
|
||||
### REPL Availability Discipline
|
||||
|
||||
**Never edit code files when the REPL is unavailable.** When REPL evaluation returns errors indicating that the REPL is unavailable, stop immediately and inform the user. Let the user restore REPL before continuing.
|
||||
|
||||
#### Why This Matters
|
||||
- **Interactive Programming requires a working REPL** - You cannot verify behavior without evaluation
|
||||
- **Guessing creates bugs** - Code changes without testing introduce errors
|
||||
|
||||
## Structural Editing and REPL-First Habit
|
||||
- Develop changes in the REPL before touching files.
|
||||
- When editing Clojure files, always use structural editing tools such as **Insert Top Level Form**, **Replace Top Level Form**, **Create Clojure File**, and **Append Code**, and always read their instructions first.
|
||||
|
||||
### Creating New Files
|
||||
- Use the **Create Clojure File** tool, with initial content
|
||||
- Use the **Create Clojure File** tool with initial content
|
||||
- Follow Clojure naming rules: namespaces in kebab-case, file paths in matching snake_case (e.g., `my.project.ns` → `my/project/ns.clj`).
|
||||
|
||||
### Reloading Namespaces
|
||||
@@ -51,22 +106,6 @@ After editing files, reload the edited namespace in the REPL so updated definiti
|
||||
(require 'my.namespace :reload)
|
||||
```
|
||||
|
||||
### Keeping Brackets Balanced
|
||||
If tools or the compiler signal bracket imbalance, stop and ask for help rather than guessing—use the human-input tool.
|
||||
|
||||
## Interactive Programming with REPL
|
||||
|
||||
When evaluating code during development, always show the complete code being evaluated in a code block before using evaluation tools. The code block should start with the appropriate `(in-ns ...)` form and contain the exact code being evaluated, so the human can run the same code in their REPL.
|
||||
|
||||
Example:
|
||||
```clojure
|
||||
(in-ns 'my.namespace)
|
||||
(let [test-data {:name "example"}]
|
||||
(process-data test-data))
|
||||
```
|
||||
|
||||
This applies to all REPL-driven development, whether using Calva, Joyride, or other Clojure evaluation tools.
|
||||
|
||||
## Code Indentation Before Evaluation
|
||||
Consistent indentation is crucial to help the bracket balancer.
|
||||
|
||||
@@ -121,7 +160,7 @@ You can also use "inline def" when showing the user code in the chat, to make it
|
||||
|
||||
## Return values > print side effects
|
||||
|
||||
Prefer using the repl and return values from your evaluations, over printing things to stdout.
|
||||
Prefer using the REPL and return values from your evaluations, over printing things to stdout.
|
||||
|
||||
## Reading from `stdin`
|
||||
- When Clojure code uses `(read-line)`, it will prompt the user through VS Code.
|
||||
@@ -272,9 +311,9 @@ Iterate with real data before editing files.
|
||||
```
|
||||
|
||||
#### Benefits
|
||||
- Verified behaviour before committing changes
|
||||
- Verified behavior before committing changes
|
||||
- Incremental development with immediate feedback
|
||||
- Tests that capture known-good behaviour
|
||||
- Tests that capture known-good behavior
|
||||
- Start new work with failing tests to lock in intent
|
||||
|
||||
### Test Naming and Messaging
|
||||
@@ -307,3 +346,4 @@ Guidelines:
|
||||
## Happy Interactive Programming
|
||||
|
||||
Remember to prefer the REPL in your work. Keep in mind that the user does not see what you evaluate. Nor the results. Communicate with the user in the chat about what you evaluate and what you get back.
|
||||
|
||||
|
||||
229
instructions/langchain-python.instructions.md
Normal file
229
instructions/langchain-python.instructions.md
Normal file
@@ -0,0 +1,229 @@
|
||||
---
|
||||
description: 'Instructions for using LangChain with Python'
|
||||
applyTo: "**/*.py"
|
||||
---
|
||||
|
||||
# LangChain Python Instructions
|
||||
|
||||
These instructions guide GitHub Copilot in generating code and documentation for LangChain applications in Python. Focus on LangChain-specific patterns, APIs, and best practices.
|
||||
|
||||
## Runnable Interface (LangChain-specific)
|
||||
|
||||
LangChain's `Runnable` interface is the foundation for composing and executing chains, chat models, output parsers, retrievers, and LangGraph graphs. It provides a unified API for invoking, batching, streaming, inspecting, and composing components.
|
||||
|
||||
**Key LangChain-specific features:**
|
||||
|
||||
- All major LangChain components (chat models, output parsers, retrievers, graphs) implement the Runnable interface.
|
||||
- Supports synchronous (`invoke`, `batch`, `stream`) and asynchronous (`ainvoke`, `abatch`, `astream`) execution.
|
||||
- Batching (`batch`, `batch_as_completed`) is optimized for parallel API calls; set `max_concurrency` in `RunnableConfig` to control parallelism.
|
||||
- Streaming APIs (`stream`, `astream`, `astream_events`) yield outputs as they are produced, critical for responsive LLM apps.
|
||||
- Input/output types are component-specific (e.g., chat models accept messages, retrievers accept strings, output parsers accept model outputs).
|
||||
- Inspect schemas with `get_input_schema`, `get_output_schema`, and their JSONSchema variants for validation and OpenAPI generation.
|
||||
- Use `with_types` to override inferred input/output types for complex LCEL chains.
|
||||
- Compose Runnables declaratively with LCEL: `chain = prompt | chat_model | output_parser`.
|
||||
- Propagate `RunnableConfig` (tags, metadata, callbacks, concurrency) automatically in Python 3.11+; manually in async code for Python 3.9/3.10.
|
||||
- Create custom runnables with `RunnableLambda` (simple transforms) or `RunnableGenerator` (streaming transforms); avoid subclassing directly.
|
||||
- Configure runtime attributes and alternatives with `configurable_fields` and `configurable_alternatives` for dynamic chains and LangServe deployments.
|
||||
|
||||
**LangChain best practices:**
|
||||
|
||||
- Use batching for parallel API calls to LLMs or retrievers; set `max_concurrency` to avoid rate limits.
|
||||
- Prefer streaming APIs for chat UIs and long outputs.
|
||||
- Always validate input/output schemas for custom chains and deployed endpoints.
|
||||
- Use tags and metadata in `RunnableConfig` for tracing in LangSmith and debugging complex chains.
|
||||
- For custom logic, wrap functions with `RunnableLambda` or `RunnableGenerator` instead of subclassing.
|
||||
- For advanced configuration, expose fields and alternatives via `configurable_fields` and `configurable_alternatives`.
|
||||
|
||||
|
||||
- Use LangChain's chat model integrations for conversational AI:
|
||||
|
||||
- Import from `langchain.chat_models` or `langchain_openai` (e.g., `ChatOpenAI`).
|
||||
- Compose messages using `SystemMessage`, `HumanMessage`, `AIMessage`.
|
||||
- For tool calling, use `bind_tools(tools)` method.
|
||||
- For structured outputs, use `with_structured_output(schema)`.
|
||||
|
||||
Example:
|
||||
```python
|
||||
from langchain_openai import ChatOpenAI
|
||||
from langchain.schema import HumanMessage, SystemMessage
|
||||
|
||||
chat = ChatOpenAI(model="gpt-4", temperature=0)
|
||||
messages = [
|
||||
SystemMessage(content="You are a helpful assistant."),
|
||||
HumanMessage(content="What is LangChain?")
|
||||
]
|
||||
response = chat.invoke(messages)
|
||||
print(response.content)
|
||||
```
|
||||
|
||||
- Compose messages as a list of `SystemMessage`, `HumanMessage`, and optionally `AIMessage` objects.
|
||||
- For RAG, combine chat models with retrievers/vectorstores for context injection.
|
||||
- Use `streaming=True` for real-time token streaming (if supported).
|
||||
- Use `tools` argument for function/tool calling (OpenAI, Anthropic, etc.).
|
||||
- Use `response_format="json"` for structured outputs (OpenAI models).
|
||||
|
||||
Best practices:
|
||||
|
||||
- Always validate model outputs before using them in downstream tasks.
|
||||
- Prefer explicit message types for clarity and reliability.
|
||||
- For Copilot, provide clear, actionable prompts and document expected outputs.
|
||||
|
||||
|
||||
|
||||
- LLM client factory: centralize provider configs (API keys), timeouts, retries, and telemetry. Provide a single place to switch providers or client settings.
|
||||
- Prompt templates: store templates under `prompts/` and load via a safe helper. Keep templates small and testable.
|
||||
- Chains vs Agents: prefer Chains for deterministic pipelines (RAG, summarization). Use Agents when you require planning or dynamic tool selection.
|
||||
- Tools: implement typed adapter interfaces for tools; validate inputs and outputs strictly.
|
||||
- Memory: default to stateless design. When memory is needed, store minimal context and document retention/erasure policies.
|
||||
- Retrievers: build retrieval + rerank pipelines. Keep vectorstore schema stable (id, text, metadata).
|
||||
|
||||
### Patterns
|
||||
|
||||
- Callbacks & tracing: use LangChain callbacks and integrate with LangSmith or your tracing system to capture request/response lifecycle.
|
||||
- Separation of concerns: keep prompt construction, LLM wiring, and business logic separate to simplify testing and reduce accidental prompt changes.
|
||||
|
||||
## Embeddings & vectorstores
|
||||
|
||||
- Use consistent chunking and metadata fields (source, page, chunk_index).
|
||||
- Cache embeddings to avoid repeated cost for unchanged documents.
|
||||
- Local/dev: Chroma or FAISS. Production: managed vector DBs (Pinecone, Qdrant, Milvus, Weaviate) depending on scale and SLAs.
|
||||
|
||||
## Vector stores (LangChain-specific)
|
||||
|
||||
- Use LangChain's vectorstore integrations for semantic search, retrieval-augmented generation (RAG), and document similarity workflows.
|
||||
- Always initialize vectorstores with a supported embedding model (e.g., OpenAIEmbeddings, HuggingFaceEmbeddings).
|
||||
- Prefer official integrations (e.g., Chroma, FAISS, Pinecone, Qdrant, Weaviate) for production; use InMemoryVectorStore for tests and demos.
|
||||
- Store documents as LangChain `Document` objects with `page_content` and `metadata`.
|
||||
- Use `add_documents(documents, ids=...)` to add/update documents. Always provide unique IDs for upserts.
|
||||
- Use `delete(ids=...)` to remove documents by ID.
|
||||
- Use `similarity_search(query, k=4, filter={...})` to retrieve top-k similar documents. Use metadata filters for scoped search.
|
||||
- For RAG, connect your vectorstore to a retriever and chain with an LLM (see LangChain Retriever and RAGChain docs).
|
||||
- For advanced search, use vectorstore-specific options: Pinecone supports hybrid search and metadata filtering; Chroma supports filtering and custom distance metrics.
|
||||
- Always validate the vectorstore integration and API version in your environment; breaking changes are common between LangChain releases.
|
||||
- Example (InMemoryVectorStore):
|
||||
|
||||
```python
|
||||
from langchain_core.vectorstores import InMemoryVectorStore
|
||||
from langchain_openai import OpenAIEmbeddings
|
||||
from langchain_core.documents import Document
|
||||
|
||||
embedding_model = OpenAIEmbeddings()
|
||||
vector_store = InMemoryVectorStore(embedding=embedding_model)
|
||||
|
||||
documents = [Document(page_content="LangChain content", metadata={"source": "doc1"})]
|
||||
vector_store.add_documents(documents=documents, ids=["doc1"])
|
||||
|
||||
results = vector_store.similarity_search("What is RAG?", k=2)
|
||||
for doc in results:
|
||||
print(doc.page_content, doc.metadata)
|
||||
```
|
||||
|
||||
- For production, prefer persistent vectorstores (Chroma, Pinecone, Qdrant, Weaviate) and configure authentication, scaling, and backup as per provider docs.
|
||||
- Reference: https://python.langchain.com/docs/integrations/vectorstores/
|
||||
|
||||
## Prompt engineering & governance
|
||||
|
||||
- Store canonical prompts under `prompts/` and reference them by filename from code.
|
||||
- Write unit tests that assert required placeholders exist and that rendered prompts fit expected patterns (length, variables present).
|
||||
- Maintain a CHANGELOG for prompt and schema changes that affect behavior.
|
||||
|
||||
## Chat models
|
||||
|
||||
LangChain offers a consistent interface for chat models with additional features for monitoring, debugging, and optimization.
|
||||
|
||||
### Integrations
|
||||
|
||||
Integrations are either:
|
||||
|
||||
1. Official: packaged `langchain-<provider>` integrations maintained by the LangChain team or provider.
|
||||
2. Community: contributed integrations (in `langchain-community`).
|
||||
|
||||
Chat models typically follow a naming convention with a `Chat` prefix (e.g., `ChatOpenAI`, `ChatAnthropic`, `ChatOllama`). Models without the `Chat` prefix (or with an `LLM` suffix) often implement the older string-in/string-out interface and are less preferred for modern chat workflows.
|
||||
|
||||
### Interface
|
||||
|
||||
Chat models implement `BaseChatModel` and support the Runnable interface: streaming, async, batching, and more. Many operations accept and return LangChain `messages` (roles like `system`, `user`, `assistant`). See the BaseChatModel API reference for details.
|
||||
|
||||
Key methods include:
|
||||
|
||||
- `invoke(messages, ...)` — send a list of messages and receive a response.
|
||||
- `stream(messages, ...)` — stream partial outputs as tokens arrive.
|
||||
- `batch(inputs, ...)` — batch multiple requests.
|
||||
- `bind_tools(tools)` — attach tool adapters for tool calling.
|
||||
- `with_structured_output(schema)` — helper to request structured responses.
|
||||
|
||||
### Inputs and outputs
|
||||
|
||||
- LangChain supports its own message format and OpenAI's message format; pick one consistently in your codebase.
|
||||
- Messages include a `role` and `content` blocks; content can include structured or multimodal payloads where supported.
|
||||
|
||||
### Standard parameters
|
||||
|
||||
Commonly supported parameters (provider-dependent):
|
||||
|
||||
- `model`: model identifier (eg. `gpt-4o`, `gpt-3.5-turbo`).
|
||||
- `temperature`: randomness control (0.0 deterministic — 1.0 creative).
|
||||
- `timeout`: seconds to wait before canceling.
|
||||
- `max_tokens`: response token limit.
|
||||
- `stop`: stop sequences.
|
||||
- `max_retries`: retry attempts for network/limit failures.
|
||||
- `api_key`, `base_url`: provider auth and endpoint configuration.
|
||||
- `rate_limiter`: optional BaseRateLimiter to space requests and avoid provider quota errors.
|
||||
|
||||
> Note: Not all parameters are implemented by every provider. Always consult the provider integration docs.
|
||||
|
||||
### Tool calling
|
||||
|
||||
Chat models can call tools (APIs, DBs, system adapters). Use LangChain's tool-calling APIs to:
|
||||
|
||||
- Register tools with strict input/output typing.
|
||||
- Observe and log tool call requests and results.
|
||||
- Validate tool outputs before passing them back to the model or executing side effects.
|
||||
|
||||
See the tool-calling guide in the LangChain docs for examples and safe patterns.
|
||||
|
||||
### Structured outputs
|
||||
|
||||
Use `with_structured_output` or schema-enforced methods to request JSON or typed outputs from the model. Structured outputs are essential for reliable extraction and downstream processing (parsers, DB writes, analytics).
|
||||
|
||||
### Multimodality
|
||||
|
||||
Some models support multimodal inputs (images, audio). Check provider docs for supported input types and limitations. Multimodal outputs are rare — treat them as experimental and validate rigorously.
|
||||
|
||||
### Context window
|
||||
|
||||
Models have a finite context window measured in tokens. When designing conversational flows:
|
||||
|
||||
- Keep messages concise and prioritize important context.
|
||||
- Trim old context (summarize or archive) outside the model when it exceeds the window.
|
||||
- Use a retriever + RAG pattern to surface relevant long-form context instead of pasting large documents into the chat.
|
||||
|
||||
## Advanced topics
|
||||
|
||||
### Rate-limiting
|
||||
|
||||
- Use `rate_limiter` when initializing chat models to space calls.
|
||||
- Implement retry with exponential backoff and consider fallback models or degraded modes when throttled.
|
||||
|
||||
### Caching
|
||||
|
||||
- Exact-input caching for conversations is often ineffective. Consider semantic caching (embedding-based) for repeated meaning-level queries.
|
||||
- Semantic caching introduces dependency on embeddings and is not universally suitable.
|
||||
- Cache only where it reduces cost and meets correctness requirements (e.g., FAQ bots).
|
||||
|
||||
## Best practices
|
||||
|
||||
- Use type hints and dataclasses for public APIs.
|
||||
- Validate inputs before calling LLMs or tools.
|
||||
- Load secrets from secret managers; never log secrets or unredacted model outputs.
|
||||
- Deterministic tests: mock LLMs and embedding calls.
|
||||
- Cache embeddings and frequent retrieval results.
|
||||
- Observability: log request_id, model name, latency, and sanitized token counts.
|
||||
- Implement exponential backoff and idempotency for external calls.
|
||||
|
||||
## Security & privacy
|
||||
|
||||
- Treat model outputs as untrusted. Sanitize before executing generated code or system commands.
|
||||
- Validate any user-supplied URLs and inputs to avoid SSRF and injection attacks.
|
||||
- Document data retention and add an API to erase user data on request.
|
||||
- Limit stored PII and encrypt sensitive fields at rest.
|
||||
@@ -1,11 +1,12 @@
|
||||
---
|
||||
applyTo: '**/*.ps1,**/*.psm1'
|
||||
description: 'PowerShell cmdlet and scripting best practices based on Microsoft guidelines'
|
||||
---
|
||||
---
|
||||
|
||||
# PowerShell Cmdlet Development Guidelines
|
||||
|
||||
This guide provides PowerShell-specific instructions to help GitHub Copilot generate idiomatic, safe, and maintainable scripts. It aligns with Microsoft’s PowerShell cmdlet development guidelines.
|
||||
This guide provides PowerShell-specific instructions to help GitHub Copilot generate idiomatic,
|
||||
safe, and maintainable scripts. It aligns with Microsoft’s PowerShell cmdlet development guidelines.
|
||||
|
||||
## Naming Conventions
|
||||
|
||||
@@ -87,19 +88,19 @@ function Set-ResourceConfiguration {
|
||||
param(
|
||||
[Parameter(Mandatory)]
|
||||
[string]$Name,
|
||||
|
||||
|
||||
[Parameter()]
|
||||
[ValidateSet('Dev', 'Test', 'Prod')]
|
||||
[string]$Environment = 'Dev',
|
||||
|
||||
|
||||
[Parameter()]
|
||||
[switch]$Force,
|
||||
|
||||
|
||||
[Parameter()]
|
||||
[ValidateNotNullOrEmpty()]
|
||||
[string[]]$Tags
|
||||
)
|
||||
|
||||
|
||||
process {
|
||||
# Logic here
|
||||
}
|
||||
@@ -150,32 +151,32 @@ function Update-ResourceStatus {
|
||||
)
|
||||
|
||||
begin {
|
||||
Write-Verbose "Starting resource status update process"
|
||||
Write-Verbose 'Starting resource status update process'
|
||||
$timestamp = Get-Date
|
||||
}
|
||||
|
||||
process {
|
||||
# Process each resource individually
|
||||
Write-Verbose "Processing resource: $Name"
|
||||
|
||||
|
||||
$resource = [PSCustomObject]@{
|
||||
Name = $Name
|
||||
Status = $Status
|
||||
Name = $Name
|
||||
Status = $Status
|
||||
LastUpdated = $timestamp
|
||||
UpdatedBy = $env:USERNAME
|
||||
UpdatedBy = $env:USERNAME
|
||||
}
|
||||
|
||||
# Only output if PassThru is specified
|
||||
if ($PassThru) {
|
||||
if ($PassThru.IsPresent) {
|
||||
Write-Output $resource
|
||||
}
|
||||
}
|
||||
|
||||
end {
|
||||
Write-Verbose "Resource status update process completed"
|
||||
Write-Verbose 'Resource status update process completed'
|
||||
}
|
||||
}
|
||||
```
|
||||
```
|
||||
|
||||
## Error Handling and Safety
|
||||
|
||||
@@ -198,6 +199,9 @@ function Update-ResourceStatus {
|
||||
- Return meaningful error messages
|
||||
- Use ErrorVariable when needed
|
||||
- Include proper terminating vs non-terminating error handling
|
||||
- In advanced functions with `[CmdletBinding()]`, prefer `$PSCmdlet.WriteError()` over `Write-Error`
|
||||
- In advanced functions with `[CmdletBinding()]`, prefer `$PSCmdlet.ThrowTerminatingError()` over `throw`
|
||||
- Construct proper ErrorRecord objects with category, target, and exception details
|
||||
|
||||
- **Non-Interactive Design:**
|
||||
- Accept input via parameters
|
||||
@@ -220,7 +224,7 @@ function Remove-UserAccount {
|
||||
)
|
||||
|
||||
begin {
|
||||
Write-Verbose "Starting user account removal process"
|
||||
Write-Verbose 'Starting user account removal process'
|
||||
$ErrorActionPreference = 'Stop'
|
||||
}
|
||||
|
||||
@@ -228,7 +232,13 @@ function Remove-UserAccount {
|
||||
try {
|
||||
# Validation
|
||||
if (-not (Test-UserExists -Username $Username)) {
|
||||
Write-Error "User account '$Username' not found"
|
||||
$errorRecord = [System.Management.Automation.ErrorRecord]::new(
|
||||
[System.Exception]::new("User account '$Username' not found"),
|
||||
'UserNotFound',
|
||||
[System.Management.Automation.ErrorCategory]::ObjectNotFound,
|
||||
$Username
|
||||
)
|
||||
$PSCmdlet.WriteError($errorRecord)
|
||||
return
|
||||
}
|
||||
|
||||
@@ -236,24 +246,32 @@ function Remove-UserAccount {
|
||||
$shouldProcessMessage = "Remove user account '$Username'"
|
||||
if ($Force -or $PSCmdlet.ShouldProcess($Username, $shouldProcessMessage)) {
|
||||
Write-Verbose "Removing user account: $Username"
|
||||
|
||||
|
||||
# Main operation
|
||||
Remove-ADUser -Identity $Username -ErrorAction Stop
|
||||
Write-Warning "User account '$Username' has been removed"
|
||||
}
|
||||
}
|
||||
catch [Microsoft.ActiveDirectory.Management.ADException] {
|
||||
Write-Error "Active Directory error: $_"
|
||||
throw
|
||||
}
|
||||
catch {
|
||||
Write-Error "Unexpected error removing user account: $_"
|
||||
throw
|
||||
} catch [Microsoft.ActiveDirectory.Management.ADException] {
|
||||
$errorRecord = [System.Management.Automation.ErrorRecord]::new(
|
||||
$_.Exception,
|
||||
'ActiveDirectoryError',
|
||||
[System.Management.Automation.ErrorCategory]::NotSpecified,
|
||||
$Username
|
||||
)
|
||||
$PSCmdlet.ThrowTerminatingError($errorRecord)
|
||||
} catch {
|
||||
$errorRecord = [System.Management.Automation.ErrorRecord]::new(
|
||||
$_.Exception,
|
||||
'UnexpectedError',
|
||||
[System.Management.Automation.ErrorCategory]::NotSpecified,
|
||||
$Username
|
||||
)
|
||||
$PSCmdlet.ThrowTerminatingError($errorRecord)
|
||||
}
|
||||
}
|
||||
|
||||
end {
|
||||
Write-Verbose "User account removal process completed"
|
||||
Write-Verbose 'User account removal process completed'
|
||||
}
|
||||
}
|
||||
```
|
||||
@@ -296,8 +314,8 @@ function New-Resource {
|
||||
[CmdletBinding(SupportsShouldProcess = $true, ConfirmImpact = 'Medium')]
|
||||
param(
|
||||
[Parameter(Mandatory = $true,
|
||||
ValueFromPipeline = $true,
|
||||
ValueFromPipelineByPropertyName = $true)]
|
||||
ValueFromPipeline = $true,
|
||||
ValueFromPipelineByPropertyName = $true)]
|
||||
[ValidateNotNullOrEmpty()]
|
||||
[string]$Name,
|
||||
|
||||
@@ -305,29 +323,34 @@ function New-Resource {
|
||||
[ValidateSet('Development', 'Production')]
|
||||
[string]$Environment = 'Development'
|
||||
)
|
||||
|
||||
|
||||
begin {
|
||||
Write-Verbose "Starting resource creation process"
|
||||
Write-Verbose 'Starting resource creation process'
|
||||
}
|
||||
|
||||
|
||||
process {
|
||||
try {
|
||||
if ($PSCmdlet.ShouldProcess($Name, "Create new resource")) {
|
||||
if ($PSCmdlet.ShouldProcess($Name, 'Create new resource')) {
|
||||
# Resource creation logic here
|
||||
Write-Output ([PSCustomObject]@{
|
||||
Name = $Name
|
||||
Environment = $Environment
|
||||
Created = Get-Date
|
||||
})
|
||||
Name = $Name
|
||||
Environment = $Environment
|
||||
Created = Get-Date
|
||||
})
|
||||
}
|
||||
}
|
||||
catch {
|
||||
Write-Error "Failed to create resource: $_"
|
||||
} catch {
|
||||
$errorRecord = [System.Management.Automation.ErrorRecord]::new(
|
||||
$_.Exception,
|
||||
'ResourceCreationFailed',
|
||||
[System.Management.Automation.ErrorCategory]::NotSpecified,
|
||||
$Name
|
||||
)
|
||||
$PSCmdlet.ThrowTerminatingError($errorRecord)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
end {
|
||||
Write-Verbose "Completed resource creation process"
|
||||
Write-Verbose 'Completed resource creation process'
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
161
instructions/svelte.instructions.md
Normal file
161
instructions/svelte.instructions.md
Normal file
@@ -0,0 +1,161 @@
|
||||
---
|
||||
description: 'Svelte 5 and SvelteKit development standards and best practices for component-based user interfaces and full-stack applications'
|
||||
applyTo: '**/*.svelte, **/*.ts, **/*.js, **/*.css, **/*.scss, **/*.json'
|
||||
---
|
||||
|
||||
# Svelte 5 and SvelteKit Development Instructions
|
||||
|
||||
Instructions for building high-quality Svelte 5 and SvelteKit applications with modern runes-based reactivity, TypeScript, and performance optimization.
|
||||
|
||||
## Project Context
|
||||
- Svelte 5.x with runes system ($state, $derived, $effect, $props, $bindable)
|
||||
- SvelteKit for full-stack applications with file-based routing
|
||||
- TypeScript for type safety and better developer experience
|
||||
- Component-scoped styling with CSS custom properties
|
||||
- Progressive enhancement and performance-first approach
|
||||
- Modern build tooling (Vite) with optimizations
|
||||
|
||||
## Development Standards
|
||||
|
||||
### Architecture
|
||||
- Use Svelte 5 runes system for all reactivity instead of legacy stores
|
||||
- Organize components by feature or domain for scalability
|
||||
- Separate presentation components from logic-heavy components
|
||||
- Extract reusable logic into composable functions
|
||||
- Implement proper component composition with slots and snippets
|
||||
- Use SvelteKit's file-based routing with proper load functions
|
||||
|
||||
### TypeScript Integration
|
||||
- Enable strict mode in `tsconfig.json` for maximum type safety
|
||||
- Define interfaces for component props using `$props()` syntax
|
||||
- Type event handlers, refs, and SvelteKit's generated types
|
||||
- Use generic types for reusable components
|
||||
- Leverage `$types.ts` files generated by SvelteKit
|
||||
- Implement proper type checking with `svelte-check`
|
||||
|
||||
### Component Design
|
||||
- Follow single responsibility principle for components
|
||||
- Use `<script lang="ts">` with runes syntax as default
|
||||
- Keep components small and focused on one concern
|
||||
- Implement proper prop validation with TypeScript
|
||||
- Use slots and snippets for flexible composition
|
||||
- Design components to be testable and reusable
|
||||
|
||||
### Svelte 5 Runes System
|
||||
- Use `$state()` for reactive local state management
|
||||
- Implement `$derived()` for computed values and expensive calculations
|
||||
- Use `$effect()` for side effects with proper cleanup
|
||||
- Define component props with `$props()` and destructuring
|
||||
- Use `$bindable()` for two-way data binding between components
|
||||
- Migrate from legacy stores to runes for better performance
|
||||
|
||||
### State Management
|
||||
- Use `$state()` for local component state
|
||||
- Implement context API with `setContext`/`getContext` for shared state
|
||||
- Use SvelteKit stores for global application state when needed
|
||||
- Keep state normalized for complex data structures
|
||||
- Use derived state for computed values
|
||||
- Implement proper state persistence for client-side data
|
||||
|
||||
### SvelteKit Patterns
|
||||
- Use `+page.svelte` for page components with proper SEO
|
||||
- Implement `+layout.svelte` for shared layouts and navigation
|
||||
- Use `+page.server.ts` for server-side data loading and API calls
|
||||
- Implement form actions in `+page.server.ts` for data mutations
|
||||
- Use `+server.ts` for API endpoints and server-side logic
|
||||
- Handle routing with SvelteKit's file-based system
|
||||
|
||||
### Styling
|
||||
- Use component-scoped styles with `<style>` blocks
|
||||
- Implement CSS custom properties for theming and design systems
|
||||
- Use `class:` directive for conditional styling
|
||||
- Follow BEM or utility-first CSS conventions
|
||||
- Implement responsive design with mobile-first approach
|
||||
- Use `:global()` sparingly for truly global styles
|
||||
|
||||
### Performance Optimization
|
||||
- Use keyed `{#each}` blocks for efficient list rendering
|
||||
- Implement lazy loading with dynamic imports and `svelte:component`
|
||||
- Use `$derived()` for expensive computations to avoid unnecessary recalculations
|
||||
- Leverage SvelteKit's automatic code splitting and preloading
|
||||
- Optimize bundle size with tree shaking and proper imports
|
||||
- Profile with Svelte DevTools to identify performance bottlenecks
|
||||
|
||||
### Data Fetching
|
||||
- Use SvelteKit's load functions for server-side and universal data fetching
|
||||
- Implement proper loading, error, and success states
|
||||
- Handle streaming data with promises in server load functions
|
||||
- Use `invalidate()` and `invalidateAll()` for cache management
|
||||
- Implement optimistic updates for better user experience
|
||||
- Handle offline scenarios and network errors gracefully
|
||||
|
||||
### Error Handling
|
||||
- Implement `+error.svelte` pages for route-level error boundaries
|
||||
- Use try/catch blocks in load functions and form actions
|
||||
- Provide meaningful error messages and fallback UI
|
||||
- Log errors appropriately for debugging and monitoring
|
||||
- Handle validation errors in forms with proper user feedback
|
||||
- Use SvelteKit's error and redirect helpers
|
||||
|
||||
### Forms and Validation
|
||||
- Use SvelteKit's form actions for server-side form handling
|
||||
- Implement progressive enhancement with `use:enhance`
|
||||
- Use `bind:value` for controlled form inputs
|
||||
- Validate data both client-side and server-side
|
||||
- Handle file uploads and complex form scenarios
|
||||
- Implement proper accessibility with labels and ARIA attributes
|
||||
|
||||
### Testing
|
||||
- Write unit tests for components using Vitest and Testing Library
|
||||
- Test component behavior, not implementation details
|
||||
- Use Playwright for end-to-end testing of user workflows
|
||||
- Mock SvelteKit's load functions and stores appropriately
|
||||
- Test form actions and API endpoints thoroughly
|
||||
- Implement accessibility testing with axe-core
|
||||
|
||||
### Security
|
||||
- Sanitize user inputs to prevent XSS attacks
|
||||
- Use `@html` directive carefully and validate HTML content
|
||||
- Implement proper CSRF protection with SvelteKit
|
||||
- Validate and sanitize data in load functions and form actions
|
||||
- Use HTTPS for all external API calls and production deployments
|
||||
- Store sensitive data securely with proper session management
|
||||
|
||||
### Accessibility
|
||||
- Use semantic HTML elements and proper heading hierarchy
|
||||
- Implement keyboard navigation for all interactive elements
|
||||
- Provide proper ARIA labels and descriptions
|
||||
- Ensure color contrast meets WCAG guidelines
|
||||
- Test with screen readers and accessibility tools
|
||||
- Implement focus management for dynamic content
|
||||
|
||||
## Implementation Process
|
||||
1. Initialize SvelteKit project with TypeScript and desired adapters
|
||||
2. Set up project structure with proper folder organization
|
||||
3. Define TypeScript interfaces and component props
|
||||
4. Implement core components with Svelte 5 runes
|
||||
5. Add routing, layouts, and navigation with SvelteKit
|
||||
6. Implement data loading and form handling
|
||||
7. Add styling system with custom properties and responsive design
|
||||
8. Implement error handling and loading states
|
||||
9. Add comprehensive testing coverage
|
||||
10. Optimize performance and bundle size
|
||||
11. Ensure accessibility compliance
|
||||
12. Deploy with appropriate SvelteKit adapter
|
||||
|
||||
## Additional Guidelines
|
||||
- Follow Svelte's naming conventions (PascalCase for components, camelCase for functions)
|
||||
- Use ESLint with eslint-plugin-svelte and Prettier for code consistency
|
||||
- Keep dependencies up to date and audit for security vulnerabilities
|
||||
- Document complex components and logic with JSDoc
|
||||
- Use Svelte DevTools for debugging and performance analysis
|
||||
- Implement proper SEO with SvelteKit's meta tags and structured data
|
||||
- Use environment variables for configuration across different deployment stages
|
||||
|
||||
## Common Patterns
|
||||
- Renderless components with slots for flexible UI composition
|
||||
- Custom directives for cross-cutting concerns and DOM manipulation
|
||||
- Snippet-based composition for reusable template logic
|
||||
- Context providers for application-wide state management
|
||||
- Progressive enhancement for forms and interactive features
|
||||
- Server-side rendering with client-side hydration for optimal performance
|
||||
Reference in New Issue
Block a user