LangChain OpenTutorial
  • 🦜️🔗 The LangChain Open Tutorial for Everyone
  • 01-Basic
    • Getting Started on Windows
    • 02-Getting-Started-Mac
    • OpenAI API Key Generation and Testing Guide
    • LangSmith Tracking Setup
    • Using the OpenAI API (GPT-4o Multimodal)
    • Basic Example: Prompt+Model+OutputParser
    • LCEL Interface
    • Runnable
  • 02-Prompt
    • Prompt Template
    • Few-Shot Templates
    • LangChain Hub
    • Personal Prompts for LangChain
    • Prompt Caching
  • 03-OutputParser
    • PydanticOutputParser
    • PydanticOutputParser
    • CommaSeparatedListOutputParser
    • Structured Output Parser
    • JsonOutputParser
    • PandasDataFrameOutputParser
    • DatetimeOutputParser
    • EnumOutputParser
    • Output Fixing Parser
  • 04-Model
    • Using Various LLM Models
    • Chat Models
    • Caching
    • Caching VLLM
    • Model Serialization
    • Check Token Usage
    • Google Generative AI
    • Huggingface Endpoints
    • HuggingFace Local
    • HuggingFace Pipeline
    • ChatOllama
    • GPT4ALL
    • Video Q&A LLM (Gemini)
  • 05-Memory
    • ConversationBufferMemory
    • ConversationBufferWindowMemory
    • ConversationTokenBufferMemory
    • ConversationEntityMemory
    • ConversationKGMemory
    • ConversationSummaryMemory
    • VectorStoreRetrieverMemory
    • LCEL (Remembering Conversation History): Adding Memory
    • Memory Using SQLite
    • Conversation With History
  • 06-DocumentLoader
    • Document & Document Loader
    • PDF Loader
    • WebBaseLoader
    • CSV Loader
    • Excel File Loading in LangChain
    • Microsoft Word(doc, docx) With Langchain
    • Microsoft PowerPoint
    • TXT Loader
    • JSON
    • Arxiv Loader
    • UpstageDocumentParseLoader
    • LlamaParse
    • HWP (Hangeul) Loader
  • 07-TextSplitter
    • Character Text Splitter
    • 02. RecursiveCharacterTextSplitter
    • Text Splitting Methods in NLP
    • TokenTextSplitter
    • SemanticChunker
    • Split code with Langchain
    • MarkdownHeaderTextSplitter
    • HTMLHeaderTextSplitter
    • RecursiveJsonSplitter
  • 08-Embedding
    • OpenAI Embeddings
    • CacheBackedEmbeddings
    • HuggingFace Embeddings
    • Upstage
    • Ollama Embeddings With Langchain
    • LlamaCpp Embeddings With Langchain
    • GPT4ALL
    • Multimodal Embeddings With Langchain
  • 09-VectorStore
    • Vector Stores
    • Chroma
    • Faiss
    • Pinecone
    • Qdrant
    • Elasticsearch
    • MongoDB Atlas
    • PGVector
    • Neo4j
    • Weaviate
    • Faiss
    • {VectorStore Name}
  • 10-Retriever
    • VectorStore-backed Retriever
    • Contextual Compression Retriever
    • Ensemble Retriever
    • Long Context Reorder
    • Parent Document Retriever
    • MultiQueryRetriever
    • MultiVectorRetriever
    • Self-querying
    • TimeWeightedVectorStoreRetriever
    • TimeWeightedVectorStoreRetriever
    • Kiwi BM25 Retriever
    • Ensemble Retriever with Convex Combination (CC)
  • 11-Reranker
    • Cross Encoder Reranker
    • JinaReranker
    • FlashRank Reranker
  • 12-RAG
    • Understanding the basic structure of RAG
    • RAG Basic WebBaseLoader
    • Exploring RAG in LangChain
    • RAPTOR: Recursive Abstractive Processing for Tree-Organized Retrieval
    • Conversation-With-History
    • Translation
    • Multi Modal RAG
  • 13-LangChain-Expression-Language
    • RunnablePassthrough
    • Inspect Runnables
    • RunnableLambda
    • Routing
    • Runnable Parallel
    • Configure-Runtime-Chain-Components
    • Creating Runnable objects with chain decorator
    • RunnableWithMessageHistory
    • Generator
    • Binding
    • Fallbacks
    • RunnableRetry
    • WithListeners
    • How to stream runnables
  • 14-Chains
    • Summarization
    • SQL
    • Structured Output Chain
    • StructuredDataChat
  • 15-Agent
    • Tools
    • Bind Tools
    • Tool Calling Agent
    • Tool Calling Agent with More LLM Models
    • Iteration-human-in-the-loop
    • Agentic RAG
    • CSV/Excel Analysis Agent
    • Agent-with-Toolkits-File-Management
    • Make Report Using RAG, Web searching, Image generation Agent
    • TwoAgentDebateWithTools
    • React Agent
  • 16-Evaluations
    • Generate synthetic test dataset (with RAGAS)
    • Evaluation using RAGAS
    • HF-Upload
    • LangSmith-Dataset
    • LLM-as-Judge
    • Embedding-based Evaluator(embedding_distance)
    • LangSmith Custom LLM Evaluation
    • Heuristic Evaluation
    • Compare experiment evaluations
    • Summary Evaluators
    • Groundedness Evaluation
    • Pairwise Evaluation
    • LangSmith Repeat Evaluation
    • LangSmith Online Evaluation
    • LangFuse Online Evaluation
  • 17-LangGraph
    • 01-Core-Features
      • Understanding Common Python Syntax Used in LangGraph
      • Title
      • Building a Basic Chatbot with LangGraph
      • Building an Agent with LangGraph
      • Agent with Memory
      • LangGraph Streaming Outputs
      • Human-in-the-loop
      • LangGraph Manual State Update
      • Asking Humans for Help: Customizing State in LangGraph
      • DeleteMessages
      • DeleteMessages
      • LangGraph ToolNode
      • LangGraph ToolNode
      • Branch Creation for Parallel Node Execution
      • Conversation Summaries with LangGraph
      • Conversation Summaries with LangGraph
      • LangGrpah Subgraph
      • How to transform the input and output of a subgraph
      • LangGraph Streaming Mode
      • Errors
      • A Long-Term Memory Agent
    • 02-Structures
      • LangGraph-Building-Graphs
      • Naive RAG
      • Add Groundedness Check
      • Adding a Web Search Module
      • LangGraph-Add-Query-Rewrite
      • Agentic RAG
      • Adaptive RAG
      • Multi-Agent Structures (1)
      • Multi Agent Structures (2)
    • 03-Use-Cases
      • LangGraph Agent Simulation
      • Meta Prompt Generator based on User Requirements
      • CRAG: Corrective RAG
      • Plan-and-Execute
      • Multi Agent Collaboration Network
      • Multi Agent Collaboration Network
      • Multi-Agent Supervisor
      • 08-LangGraph-Hierarchical-Multi-Agent-Teams
      • 08-LangGraph-Hierarchical-Multi-Agent-Teams
      • SQL-Agent
      • 10-LangGraph-Research-Assistant
      • LangGraph Code Assistant
      • Deploy on LangGraph Cloud
      • Tree of Thoughts (ToT)
      • Ollama Deep Researcher (Deepseek-R1)
      • Functional API
      • Reflection in LangGraph
  • 19-Cookbook
    • 01-SQL
      • TextToSQL
      • SpeechToSQL
    • 02-RecommendationSystem
      • ResumeRecommendationReview
    • 03-GraphDB
      • Movie QA System with Graph Database
      • 05-TitanicQASystem
      • Real-Time GraphRAG QA
    • 04-GraphRAG
      • Academic Search System
      • Academic QA System with GraphRAG
    • 05-AIMemoryManagementSystem
      • ConversationMemoryManagementSystem
    • 06-Multimodal
      • Multimodal RAG
      • Shopping QnA
    • 07-Agent
      • 14-MoARAG
      • CoT Based Smart Web Search
      • 16-MultiAgentShoppingMallSystem
      • Agent-Based Dynamic Slot Filling
      • Code Debugging System
      • New Employee Onboarding Chatbot
      • 20-LangGraphStudio-MultiAgent
      • Multi-Agent Scheduler System
    • 08-Serving
      • FastAPI Serving
      • Sending Requests to Remote Graph Server
      • Building a Agent API with LangServe: Integrating Currency Exchange and Trip Planning
    • 08-SyntheticDataset
      • Synthetic Dataset Generation using RAG
    • 09-Monitoring
      • Langfuse Selfhosting
Powered by GitBook
On this page
  • Overview
  • Table of Contents
  • References
  • Environment Setup
  • LangServe
  • Implementing a Travel Planning Agent
  • Implementing a Currency exchange agent
  • Testing in the LangServe Playground
  1. 19-Cookbook
  2. 08-Serving

Building a Agent API with LangServe: Integrating Currency Exchange and Trip Planning

PreviousSending Requests to Remote Graph ServerNext08-SyntheticDataset

Last updated 7 days ago

  • Author:

  • Peer Review:

  • Proofread :

  • This is a part of

Overview

This tutorial guides you through creating a Agent API using LangServe, enabling you to build intelligent and dynamic applications. You'll learn how to leverage LangChain agents and deploy them as production-ready APIs with ease. Discover how to define tools, orchestrate agent workflows, and expose them via a simple and scalable REST interface.

Table of Contents

References


Environment Setup

[Note]

  • langchain-opentutorial is a package that provides a set of easy-to-use environment setup, useful functions and utilities for tutorials.

%%capture --no-stderr
%pip install langchain-opentutorial sse_starlette uvicorn
    [notice] A new release of pip is available: 24.3.1 -> 25.0.1
    [notice] To update, run: python.exe -m pip install --upgrade pip
# Install required packages
from langchain_opentutorial import package

package.install(
    [   "langchain_openai",
        "langserve",
        "sse_starlette",
        "uvicorn"
    ],
    verbose=False,
    upgrade=False,
)

You can alternatively set API keys in .env file and load it.

[Note] This is not necessary if you've already set API keys in previous steps.

# Set environment variables
from langchain_opentutorial import set_env

set_env(
    {
        "OPENAI_API_KEY": "",
        "FREECURRENCY_API_KEY": ""
    }
)
Environment variables have been set successfully.

LangServe

LangServe is a tool that allows you to easily deploy LangChain runnables and chains as REST APIs. It integrates with FastAPI and uses Pydantic for data validation.

Implementing a Travel Planning Agent

This section demonstrates how to implement a travel planning agent. This agent suggests customized travel plans based on the user's travel requirements.

from langchain.agents import AgentExecutor, create_openai_functions_agent
from langchain_openai import ChatOpenAI
from langchain.prompts import ChatPromptTemplate, MessagesPlaceholder
from langchain.tools import tool
from langserve import add_routes
from fastapi import FastAPI
from typing import List, Optional
from pydantic import BaseModel, Field

# Define input/output models
class TravelPlanRequest(BaseModel):
    """Travel planning request structure"""
    destination: str = Field(..., description="City or country to visit")
    duration: int = Field(..., description="Number of days for the trip")
    interests: List[str] = Field(
        default_factory=list,
        description="List of interests (e.g., ['food', 'culture', 'history'])"
    )

class TravelPlanResponse(BaseModel):
    """Travel planning response structure"""
    itinerary: List[str]
    recommendations: List[str]
    estimated_budget: str

@tool
def get_travel_suggestions(destination: str, duration: int, interests: str) -> str:
    """Generates travel suggestions based on the destination, duration, and interests."""
    # In a real implementation, you might use a travel API or database
    return f"Here's a {duration}-day itinerary for {destination} focusing on {interests}..."

llm = ChatOpenAI(model="gpt-4.0")
prompt = ChatPromptTemplate.from_messages([
    ("system", "You are a helpful travel planning assistant."),
    ("human", "Plan a trip to {destination} for {duration} days with interests in {interests}"),
    MessagesPlaceholder(variable_name="agent_scratchpad")
])
tools = [get_travel_suggestions]

agent = create_openai_functions_agent(llm, tools, prompt)
travel_executor = AgentExecutor(agent=agent, tools=tools, verbose=True)

app = FastAPI()
add_routes(
    app,
    travel_executor,
    path="/travel-planner",
    input_type=TravelPlanRequest,
    output_type=TravelPlanResponse
)

Implementing a Currency exchange agent

This section shows how to implement a currency exchange agent. This agent performs currency conversions using real-time exchange rate information.

import os
import requests
from pydantic import BaseModel, Field, field_validator
from typing import Optional
from datetime import datetime

class CurrencyExchangeRequest(BaseModel):
    """Currency exchange request structure"""
    amount: float = Field(..., description="Amount to convert")
    from_currency: str = Field(..., description="Source currency code (e.g., USD)")
    to_currency: str = Field(..., description="Target currency code (e.g., EUR)")

    @field_validator('amount')
    def amount_must_be_positive(cls, v):
        if v <= 0:
            raise ValueError('Amount must be positive')
        return v

    @field_validator('from_currency', 'to_currency')
    def currency_must_be_valid(cls, v):
        if len(v) != 3:
            raise ValueError('Currency code must be 3 characters')
        return v.upper()

class CurrencyExchangeResponse(BaseModel):
    """Currency exchange response structure"""
    converted_amount: float
    exchange_rate: float
    timestamp: str
    from_currency: str
    to_currency: str

API_KEY = os.getenv("FREECURRENCY_API_KEY")

@tool
def get_exchange_rate(from_currency: str, to_currency: str) -> float:
    """Gets the current exchange rate between two currencies."""
    url = f"https://api.freecurrencyapi.com/v1/latest"
    params = {
        "apikey": API_KEY,
        "base_currency": from_currency,
        "currencies": to_currency
    }
    response = requests.get(url, params=params)
    data = response.json()
    return data['data'][to_currency]

llm = ChatOpenAI(model="gpt-4.0")
prompt = ChatPromptTemplate.from_messages([
    ("system", "You are a helpful currency exchange assistant."),
    ("human", "Convert {amount} {from_currency} to {to_currency}"),
    MessagesPlaceholder(variable_name="agent_scratchpad")
])
tools = [get_exchange_rate]

agent = create_openai_functions_agent(llm, tools, prompt)
currency_executor = AgentExecutor(agent=agent, tools=tools, verbose=True)

add_routes(
    app,
    currency_executor,
    path="/currency-exchange",
    input_type=CurrencyExchangeRequest,
    output_type=CurrencyExchangeResponse
)

Testing in the LangServe Playground

LangServe provides a playground for easily testing the implemented agents. This allows you to directly verify and debug the API's behavior.

import nest_asyncio
import uvicorn

nest_asyncio.apply()

uvicorn.run(app)
INFO:     Started server process [25888]
    INFO:     Waiting for application startup.
    INFO:     Application startup complete.
    INFO:     Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
     __          ___      .__   __.   _______      _______. _______ .______     ____    ____  _______
    |  |        /   \     |  \ |  |  /  _____|    /       ||   ____||   _  \    \   \  /   / |   ____|
    |  |       /  ^  \    |   \|  | |  |  __     |   (----`|  |__   |  |_)  |    \   \/   /  |  |__
    |  |      /  /_\  \   |  . `  | |  | |_ |     \   \    |   __|  |      /      \      /   |   __|
    |  `----./  _____  \  |  |\   | |  |__| | .----)   |   |  |____ |  |\  \----.  \    /    |  |____
    |_______/__/     \__\ |__| \__|  \______| |_______/    |_______|| _| `._____|   \__/     |_______|
    
LANGSERVE: Playground for chain "/currency-exchange/" is live at:
LANGSERVE:  │
LANGSERVE:  └──> /currency-exchange/playground/
LANGSERVE:
LANGSERVE: Playground for chain "/travel-planner/" is live at:
LANGSERVE:  │
LANGSERVE:  └──> /travel-planner/playground/
LANGSERVE:
LANGSERVE: See all available routes at /docs/

Set up the environment. You may refer to for more details.

You can checkout the for more details.

LangServe
FreecurrencyAPI
Environment Setup
langchain-opentutorial
Hwayoung Cha
JaeJun Shim
LangChain Open Tutorial
Overview
Environement Setup
LangServe
Implementing a Travel Planning Agent
Implementing a Currency exchange agent
Testing in the LangServe Playground