LangChain Integration
LangChain Integration
Section titled “LangChain Integration”UniCraft provides seamless integration with LangChain, allowing you to use multiple AI providers through LangChain’s unified interface.
Overview
Section titled “Overview”LangChain is a powerful framework for building applications with Large Language Models (LLMs). UniCraft’s LangChain integration provides:
- Multi-Provider Support: Access multiple AI providers through one interface
- Smart Routing: Automatically choose the best model for your task
- Cost Optimization: Reduce costs through intelligent model selection
- Enhanced Reliability: Built-in failover and redundancy
- LangChain Compatibility: Works with existing LangChain code
Installation
Section titled “Installation”Install Dependencies
Section titled “Install Dependencies”# Install LangChain and UniCraftpip install langchain unicraft-langchain
# Or install specific componentspip install langchain-openai langchain-anthropic unicraft-langchainEnvironment Setup
Section titled “Environment Setup”# Set environment variablesexport UNICRAFT_API_KEY="your-unicraft-api-key"export OPENAI_API_KEY="your-openai-api-key"export ANTHROPIC_API_KEY="your-anthropic-api-key"Quick Start
Section titled “Quick Start”1. Basic Usage
Section titled “1. Basic Usage”from langchain.llms import UniCraftfrom langchain.chat_models import ChatUniCraft
# Initialize UniCraft LLMllm = UniCraft( api_key="your-unicraft-api-key", model="auto", # Smart routing temperature=0.7)
# Use with LangChainresponse = llm("Hello, world!")print(response)2. Chat Models
Section titled “2. Chat Models”from langchain.chat_models import ChatUniCraftfrom langchain.schema import HumanMessage, SystemMessage
# Initialize chat modelchat = ChatUniCraft( api_key="your-unicraft-api-key", model="auto", temperature=0.7)
# Create messagesmessages = [ SystemMessage(content="You are a helpful assistant."), HumanMessage(content="Hello, world!")]
# Get responseresponse = chat(messages)print(response.content)Advanced Configuration
Section titled “Advanced Configuration”1. Smart Routing
Section titled “1. Smart Routing”from langchain.llms import UniCraft
# Configure smart routingllm = UniCraft( api_key="your-unicraft-api-key", model="auto", routing_strategy="cost_optimized", max_cost_per_request=0.01, quality_threshold=0.8)
response = llm("Analyze this data...")2. Provider Selection
Section titled “2. Provider Selection”# Specify preferred providersllm = UniCraft( api_key="your-unicraft-api-key", model="auto", providers=["openai", "anthropic"], fallback_providers=["google"])
response = llm("Generate content...")3. Cost Optimization
Section titled “3. Cost Optimization”# Set cost limitsllm = UniCraft( api_key="your-unicraft-api-key", model="auto", max_cost_per_request=0.05, daily_cost_limit=100.00, cost_optimization=True)
response = llm("Write a summary...")LangChain Components
Section titled “LangChain Components”1. LLMs
Section titled “1. LLMs”from langchain.llms import UniCraft
# Basic LLMllm = UniCraft( api_key="your-unicraft-api-key", model="auto")
# With custom parametersllm = UniCraft( api_key="your-unicraft-api-key", model="auto", temperature=0.7, max_tokens=1000, top_p=0.9)2. Chat Models
Section titled “2. Chat Models”from langchain.chat_models import ChatUniCraftfrom langchain.schema import HumanMessage, SystemMessage, AIMessage
# Chat modelchat = ChatUniCraft( api_key="your-unicraft-api-key", model="auto")
# Conversationmessages = [ SystemMessage(content="You are a helpful assistant."), HumanMessage(content="What is the capital of France?"), AIMessage(content="The capital of France is Paris."), HumanMessage(content="What is the population of Paris?")]
response = chat(messages)print(response.content)3. Embeddings
Section titled “3. Embeddings”from langchain.embeddings import UniCraftEmbeddings
# Embeddingsembeddings = UniCraftEmbeddings( api_key="your-unicraft-api-key", model="auto")
# Generate embeddingstext = "This is a sample text for embedding."embedding = embeddings.embed_query(text)print(embedding)Chains and Agents
Section titled “Chains and Agents”1. Simple Chains
Section titled “1. Simple Chains”from langchain.chains import LLMChainfrom langchain.prompts import PromptTemplate
# Create prompt templatetemplate = "Question: {question}\nAnswer:"prompt = PromptTemplate(template=template, input_variables=["question"])
# Create chainllm = UniCraft(api_key="your-unicraft-api-key", model="auto")chain = LLMChain(llm=llm, prompt=prompt)
# Run chainresponse = chain.run(question="What is the capital of France?")print(response)2. Sequential Chains
Section titled “2. Sequential Chains”from langchain.chains import SimpleSequentialChain
# First chainfirst_prompt = PromptTemplate( input_variables=["product"], template="What is the best name for a company that makes {product}?")first_chain = LLMChain(llm=llm, prompt=first_prompt)
# Second chainsecond_prompt = PromptTemplate( input_variables=["company_name"], template="Write a catchphrase for {company_name}")second_chain = LLMChain(llm=llm, prompt=second_prompt)
# Sequential chainoverall_chain = SimpleSequentialChain( chains=[first_chain, second_chain], verbose=True)
response = overall_chain.run("sustainable energy products")print(response)3. Agents
Section titled “3. Agents”from langchain.agents import initialize_agent, Toolfrom langchain.tools import DuckDuckGoSearchRun
# Define toolssearch = DuckDuckGoSearchRun()tools = [ Tool( name="Search", func=search.run, description="Useful for searching the internet for current information" )]
# Initialize agentllm = UniCraft(api_key="your-unicraft-api-key", model="auto")agent = initialize_agent( tools=tools, llm=llm, agent="zero-shot-react-description", verbose=True)
# Run agentresponse = agent.run("What is the current weather in Paris?")print(response)Memory and Conversation
Section titled “Memory and Conversation”1. Conversation Buffer
Section titled “1. Conversation Buffer”from langchain.memory import ConversationBufferMemoryfrom langchain.chains import ConversationChain
# Initialize memorymemory = ConversationBufferMemory()
# Create conversation chainllm = UniCraft(api_key="your-unicraft-api-key", model="auto")conversation = ConversationChain( llm=llm, memory=memory, verbose=True)
# Have conversationresponse1 = conversation.predict(input="Hi, my name is Alice")response2 = conversation.predict(input="What's my name?")print(response2) # Should remember the name2. Conversation Summary
Section titled “2. Conversation Summary”from langchain.memory import ConversationSummaryMemoryfrom langchain.chains import ConversationChain
# Initialize summary memorymemory = ConversationSummaryMemory(llm=llm)
# Create conversation chainconversation = ConversationChain( llm=llm, memory=memory, verbose=True)
# Long conversationfor i in range(10): response = conversation.predict(input=f"Tell me about topic {i}") print(f"Response {i}: {response}")Document Processing
Section titled “Document Processing”1. Document Loaders
Section titled “1. Document Loaders”from langchain.document_loaders import TextLoaderfrom langchain.text_splitter import CharacterTextSplitterfrom langchain.vectorstores import FAISSfrom langchain.chains import RetrievalQA
# Load documentloader = TextLoader("document.txt")documents = loader.load()
# Split texttext_splitter = CharacterTextSplitter(chunk_size=1000, chunk_overlap=0)texts = text_splitter.split_documents(documents)
# Create embeddingsembeddings = UniCraftEmbeddings(api_key="your-unicraft-api-key")vectorstore = FAISS.from_documents(texts, embeddings)
# Create QA chainllm = UniCraft(api_key="your-unicraft-api-key", model="auto")qa = RetrievalQA.from_chain_type( llm=llm, chain_type="stuff", retriever=vectorstore.as_retriever())
# Ask questionsresponse = qa.run("What is this document about?")print(response)2. Document Summarization
Section titled “2. Document Summarization”from langchain.chains import MapReduceDocumentsChain, ReduceDocumentsChainfrom langchain.chains.combine_documents.stuff import StuffDocumentsChainfrom langchain.chains.llm import LLMChain
# Map chainmap_template = "Summarize this text: {docs}"map_prompt = PromptTemplate.from_template(map_template)map_chain = LLMChain(llm=llm, prompt=map_prompt)
# Reduce chainreduce_template = "Combine these summaries: {docs}"reduce_prompt = PromptTemplate.from_template(reduce_template)reduce_chain = LLMChain(llm=llm, prompt=reduce_prompt)
# Combine chainscombine_documents_chain = StuffDocumentsChain( llm_chain=reduce_chain, document_variable_name="docs")reduce_documents_chain = ReduceDocumentsChain( combine_documents_chain=combine_documents_chain, collapse_documents_chain=combine_documents_chain, token_max=4000)map_reduce_chain = MapReduceDocumentsChain( llm_chain=map_chain, reduce_documents_chain=reduce_documents_chain, document_variable_name="docs", return_intermediate_steps=False)
# Summarize documentsummary = map_reduce_chain.run(documents)print(summary)Custom Tools and Functions
Section titled “Custom Tools and Functions”1. Custom Tool
Section titled “1. Custom Tool”from langchain.tools import BaseToolfrom typing import Optional, Typefrom pydantic import BaseModel, Field
class CalculatorInput(BaseModel): expression: str = Field(description="Mathematical expression to evaluate")
class CalculatorTool(BaseTool): name = "calculator" description = "Useful for performing mathematical calculations" args_schema: Type[BaseModel] = CalculatorInput
def _run(self, expression: str) -> str: try: result = eval(expression) return str(result) except Exception as e: return f"Error: {str(e)}"
# Use custom toolcalculator = CalculatorTool()result = calculator.run("2 + 2")print(result) # Output: 42. Function Calling
Section titled “2. Function Calling”from langchain.tools import tool
@tooldef get_weather(city: str) -> str: """Get the current weather for a city.""" # Mock weather data weather_data = { "paris": "Sunny, 22°C", "london": "Cloudy, 18°C", "tokyo": "Rainy, 25°C" } return weather_data.get(city.lower(), "Weather data not available")
# Use in agenttools = [get_weather]llm = UniCraft(api_key="your-unicraft-api-key", model="auto")agent = initialize_agent( tools=tools, llm=llm, agent="zero-shot-react-description", verbose=True)
response = agent.run("What's the weather like in Paris?")print(response)Performance Optimization
Section titled “Performance Optimization”1. Caching
Section titled “1. Caching”from langchain.cache import InMemoryCachefrom langchain.globals import set_llm_cache
# Enable cachingset_llm_cache(InMemoryCache())
# First call (will be cached)llm = UniCraft(api_key="your-unicraft-api-key", model="auto")response1 = llm("What is the capital of France?")
# Second call (will use cache)response2 = llm("What is the capital of France?")2. Batch Processing
Section titled “2. Batch Processing”# Process multiple inputs at onceinputs = [ "What is the capital of France?", "What is the capital of Germany?", "What is the capital of Italy?"]
responses = llm.batch(inputs)for i, response in enumerate(responses): print(f"Question {i+1}: {response}")3. Streaming
Section titled “3. Streaming”# Stream responsesfor chunk in llm.stream("Tell me a story"): print(chunk, end="", flush=True)Error Handling
Section titled “Error Handling”1. Retry Logic
Section titled “1. Retry Logic”from langchain.llms import UniCraftfrom langchain.callbacks.manager import CallbackManagerForLLMRunfrom typing import Optional, List, Any
class RetryUniCraft(UniCraft): def _call( self, prompt: str, stop: Optional[List[str]] = None, run_manager: Optional[CallbackManagerForLLMRun] = None, **kwargs: Any, ) -> str: max_retries = 3 for attempt in range(max_retries): try: return super()._call(prompt, stop, run_manager, **kwargs) except Exception as e: if attempt == max_retries - 1: raise e print(f"Attempt {attempt + 1} failed: {e}") time.sleep(2 ** attempt) # Exponential backoff
# Use retry LLMllm = RetryUniCraft(api_key="your-unicraft-api-key", model="auto")response = llm("Hello, world!")2. Fallback Handling
Section titled “2. Fallback Handling”from langchain.llms import UniCraftfrom langchain.llms.fallback import FallbackLLM
# Primary LLMprimary_llm = UniCraft( api_key="your-unicraft-api-key", model="auto")
# Fallback LLMfallback_llm = UniCraft( api_key="your-unicraft-api-key", model="gpt-3.5-turbo" # Specific model as fallback)
# Create fallback chainllm = FallbackLLM( primary_llm=primary_llm, fallback_llm=fallback_llm)
response = llm("Hello, world!")Best Practices
Section titled “Best Practices”1. Model Selection
Section titled “1. Model Selection”- Use “auto” for most cases to leverage smart routing
- Specify models only when you need specific capabilities
- Consider cost vs. quality trade-offs
2. Error Handling
Section titled “2. Error Handling”- Implement retry logic for transient failures
- Use fallback models for critical applications
- Monitor and log errors
3. Performance
Section titled “3. Performance”- Use caching for repeated requests
- Implement batch processing for multiple inputs
- Monitor response times and costs
4. Security
Section titled “4. Security”- Store API keys securely
- Validate input data
- Monitor for unusual activity
Troubleshooting
Section titled “Troubleshooting”Common Issues
Section titled “Common Issues”-
Authentication Errors
- Check API key configuration
- Verify environment variables
- Test connection
-
Model Not Available
- Check provider configuration
- Use “auto” for smart routing
- Verify model availability
-
Rate Limiting
- Implement retry logic
- Use multiple providers
- Monitor usage
-
High Costs
- Use cost-optimized routing
- Set cost limits
- Monitor spending
Debug Tips
Section titled “Debug Tips”- Enable verbose mode for debugging
- Use logging to track requests
- Test with simple prompts first
- Check UniCraft dashboard for usage
Support
Section titled “Support”For support with LangChain integration:
- Documentation: UniCraft Docs
- LangChain Docs: LangChain Documentation
- Community: UniCraft Community
- Support: support@unicraft.com
Next Steps
Section titled “Next Steps”After setting up LangChain integration:
- Test Components: Test LLMs, chat models, and embeddings
- Build Chains: Create simple and complex chains
- Implement Agents: Build intelligent agents with tools
- Optimize Performance: Implement caching and batch processing
- Monitor Usage: Set up monitoring and cost tracking