alpha

Sets LangChain Python coding rules for Copilot: the Runnable interface, LCEL composition, streaming, batching, retrieval, agents and security practices.
description: 'Instructions for using LangChain with Python'
applyTo: "**/*.py"
These instructions guide GitHub Copilot in generating code and documentation for LangChain applications in Python. Focus on LangChain-specific patterns, APIs, and best practices.
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:
invoke, batch, stream) and asynchronous (ainvoke, abatch, astream) execution.batch, batch_as_completed) is optimized for parallel API calls; set max_concurrency in RunnableConfig to control parallelism.stream, astream, astream_events) yield outputs as they are produced, critical for responsive LLM apps.get_input_schema, get_output_schema, and their JSONSchema variants for validation and OpenAPI generation.with_types to override inferred input/output types for complex LCEL chains.chain = prompt | chat_model | output_parser.RunnableConfig (tags, metadata, callbacks, concurrency) automatically in Python 3.11+; manually in async code for Python 3.9/3.10.RunnableLambda (simple transforms) or RunnableGenerator (streaming transforms); avoid subclassing directly.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:
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)
SystemMessage, HumanMessage, and optionally AIMessage objects.streaming=True for real-time token streaming (if supported).tools argument for function/tool calling (OpenAI, Anthropic, etc.).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).
Document objects with page_content and metadata.add_documents(documents, ids=...) to add/update documents. Always provide unique IDs for upserts.delete(ids=...) to remove documents by ID.similarity_search(query, k=4, filter={...}) to retrieve top-k similar documents. Use metadata filters for scoped search.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)
prompts/ and reference them by filename from code.LangChain offers a consistent interface for chat models with additional features for monitoring, debugging, and optimization.
Integrations are either:
langchain-<provider> integrations maintained by the LangChain team or provider.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.
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.role and content blocks; content can include structured or multimodal payloads where supported.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.
Chat models can call tools (APIs, DBs, system adapters). Use LangChain's tool-calling APIs to:
See the tool-calling guide in the LangChain docs for examples and safe patterns.
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).
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.
Models have a finite context window measured in tokens. When designing conversational flows:
rate_limiter when initializing chat models to space calls.set_llm_cache(...) from langchain_core.globals; exact-match backends include InMemoryCache, SQLiteCache, RedisCache, and UpstashRedisCache (serverless Redis over HTTP, with optional ttl), and RedisSemanticCache is an embedding-based option.© GitHub, Inc. · MIT · source · posted by @OpenSourceBuffGuy on promptparty.com


Adobe Illustrator Integrations
Helps an AI agent build, debug and document Adobe Illustrator integrations: CEP panels, C++ plug-ins, MCP servers and OS scripts that run ExtendScript.
agent-skill, adobe-illustrator, javascript, cpp, mcp, powershell, bash, macos, windows, documentation, developer-tools, best-practices, long-form, advanced, for-developers, for-designers, debugging, tool-use, workflow-automation, step-by-step-guide

Writes balanced employee performance reviews with specific achievements, constructive development areas, SMART goals and talking points for the review conversation.
system-prompt, act-as, performance-reviews, human-resources, leadership, goal-setting, for-managers, for-recruiters, xml-tags, structured-output, report, guardrails, empathetic, formal, critique, workplace, action-items, template

Photographs a faceted ruby-glass perfume bottle floating in mist with rose petals and crystal shards for a luxury fragrance ad, specified as JSON.
image-prompt, json-prompt, structured-output, photorealistic, cinematic, product-photography, advertising, luxury, dramatic-lighting, studio-lighting, bokeh, macro, moody, vertical-format, text-rendering, still-life, jewelry, branding, packaging-design, for-photographers, for-marketers, for-designers, gpt-image, dark-fantasy, flowers, perfume
Loading reviews…
Loading comments…