repositories
loading repo index
repositories
loading repo index
repository
loading code, commits, and activity
public Clawd ADK gateway launch mirror
stars
latest
clone command
git clone gitlawb://did:key:z6Mkq5mY...iFZ5/my-project-publ...git clone gitlawb://did:key:z6Mkq5mY.../my-project-publ...2fa351d6docs: add automaton and perps launch sources16d ago| #1 | --- |
| #2 | title: Langchain |
| #3 | --- |
| #4 | |
| #5 | Build a personalized Travel Agent AI using LangChain for conversation flow and Mem0 for memory retention. This integration enables context-aware and efficient travel planning experiences. |
| #6 | |
| #7 | ## Overview |
| #8 | |
| #9 | In this guide, we'll create a Travel Agent AI that: |
| #10 | 1. Uses LangChain to manage conversation flow |
| #11 | 2. Leverages Mem0 to store and retrieve relevant information from past interactions |
| #12 | 3. Provides personalized travel recommendations based on user history |
| #13 | |
| #14 | ## Setup and Configuration |
| #15 | |
| #16 | Install necessary libraries: |
| #17 | |
| #18 | ```bash |
| #19 | pip install langchain langchain_openai mem0ai python-dotenv |
| #20 | ``` |
| #21 | |
| #22 | Import required modules and set up configurations: |
| #23 | |
| #24 | <Note>Remember to get the Mem0 API key from [Mem0 Platform](https://app.mem0.ai).</Note> |
| #25 | |
| #26 | ```python |
| #27 | import os |
| #28 | from typing import List, Dict |
| #29 | from langchain_openai import ChatOpenAI |
| #30 | from langchain_core.messages import SystemMessage, HumanMessage, AIMessage |
| #31 | from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder |
| #32 | from mem0 import MemoryClient |
| #33 | from dotenv import load_dotenv |
| #34 | |
| #35 | load_dotenv() |
| #36 | |
| #37 | # Configuration |
| #38 | # os.environ["OPENAI_API_KEY"] = "your-openai-api-key" |
| #39 | # os.environ["MEM0_API_KEY"] = "your-mem0-api-key" |
| #40 | |
| #41 | # Initialize LangChain and Mem0 |
| #42 | llm = ChatOpenAI(model="gpt-4.1-nano-2025-04-14") |
| #43 | mem0 = MemoryClient() |
| #44 | ``` |
| #45 | |
| #46 | ## Create Prompt Template |
| #47 | |
| #48 | Set up the conversation prompt template: |
| #49 | |
| #50 | ```python |
| #51 | prompt = ChatPromptTemplate.from_messages([ |
| #52 | SystemMessage(content="""You are a helpful travel agent AI. Use the provided context to personalize your responses and remember user preferences and past interactions. |
| #53 | Provide travel recommendations, itinerary suggestions, and answer questions about destinations. |
| #54 | If you don't have specific information, you can make general suggestions based on common travel knowledge."""), |
| #55 | MessagesPlaceholder(variable_name="context"), |
| #56 | HumanMessage(content="{input}") |
| #57 | ]) |
| #58 | ``` |
| #59 | |
| #60 | ## Define Helper Functions |
| #61 | |
| #62 | Create functions to handle context retrieval, response generation, and addition to Mem0: |
| #63 | |
| #64 | ```python |
| #65 | def retrieve_context(query: str, user_id: str) -> List[Dict]: |
| #66 | """Retrieve relevant context from Mem0""" |
| #67 | try: |
| #68 | memories = mem0.search(query, user_id=user_id) |
| #69 | memory_list = memories['results'] |
| #70 | |
| #71 | serialized_memories = ' '.join([mem["memory"] for mem in memory_list]) |
| #72 | context = [ |
| #73 | { |
| #74 | "role": "system", |
| #75 | "content": f"Relevant information: {serialized_memories}" |
| #76 | }, |
| #77 | { |
| #78 | "role": "user", |
| #79 | "content": query |
| #80 | } |
| #81 | ] |
| #82 | return context |
| #83 | except Exception as e: |
| #84 | print(f"Error retrieving memories: {e}") |
| #85 | # Return empty context if there's an error |
| #86 | return [{"role": "user", "content": query}] |
| #87 | |
| #88 | def generate_response(input: str, context: List[Dict]) -> str: |
| #89 | """Generate a response using the language model""" |
| #90 | chain = prompt | llm |
| #91 | response = chain.invoke({ |
| #92 | "context": context, |
| #93 | "input": input |
| #94 | }) |
| #95 | return response.content |
| #96 | |
| #97 | def save_interaction(user_id: str, user_input: str, assistant_response: str): |
| #98 | """Save the interaction to Mem0""" |
| #99 | try: |
| #100 | interaction = [ |
| #101 | { |
| #102 | "role": "user", |
| #103 | "content": user_input |
| #104 | }, |
| #105 | { |
| #106 | "role": "assistant", |
| #107 | "content": assistant_response |
| #108 | } |
| #109 | ] |
| #110 | result = mem0.add(interaction, user_id=user_id) |
| #111 | print(f"Memory saved successfully: {len(result.get('results', []))} memories added") |
| #112 | except Exception as e: |
| #113 | print(f"Error saving interaction: {e}") |
| #114 | ``` |
| #115 | |
| #116 | ## Create Chat Turn Function |
| #117 | |
| #118 | Implement the main function to manage a single turn of conversation: |
| #119 | |
| #120 | ```python |
| #121 | def chat_turn(user_input: str, user_id: str) -> str: |
| #122 | # Retrieve context |
| #123 | context = retrieve_context(user_input, user_id) |
| #124 | |
| #125 | # Generate response |
| #126 | response = generate_response(user_input, context) |
| #127 | |
| #128 | # Save interaction |
| #129 | save_interaction(user_id, user_input, response) |
| #130 | |
| #131 | return response |
| #132 | ``` |
| #133 | |
| #134 | ## Main Interaction Loop |
| #135 | |
| #136 | Set up the main program loop for user interaction: |
| #137 | |
| #138 | ```python |
| #139 | if __name__ == "__main__": |
| #140 | print("Welcome to your personal Travel Agent Planner! How can I assist you with your travel plans today?") |
| #141 | user_id = "alice" |
| #142 | |
| #143 | while True: |
| #144 | user_input = input("You: ") |
| #145 | if user_input.lower() in ['quit', 'exit', 'bye']: |
| #146 | print("Travel Agent: Thank you for using our travel planning service. Have a great trip!") |
| #147 | break |
| #148 | |
| #149 | response = chat_turn(user_input, user_id) |
| #150 | print(f"Travel Agent: {response}") |
| #151 | ``` |
| #152 | |
| #153 | ## Key Features |
| #154 | |
| #155 | 1. **Memory Integration**: Uses Mem0 to store and retrieve relevant information from past interactions. |
| #156 | 2. **Personalization**: Provides context-aware responses based on user history and preferences. |
| #157 | 3. **Flexible Architecture**: LangChain structure allows for easy expansion of the conversation flow. |
| #158 | 4. **Continuous Learning**: Each interaction is stored, improving future responses. |
| #159 | |
| #160 | ## Conclusion |
| #161 | |
| #162 | By integrating LangChain with Mem0, you can build a personalized Travel Agent AI that can maintain context across interactions and provide tailored travel recommendations and assistance. |
| #163 | |
| #164 | <CardGroup cols={2}> |
| #165 | <Card title="LangGraph Integration" icon="diagram-project" href="/integrations/langgraph"> |
| #166 | Build stateful agents with LangGraph and Mem0 |
| #167 | </Card> |
| #168 | <Card title="LangChain Tools" icon="wrench" href="/integrations/langchain-tools"> |
| #169 | Use Mem0 as LangChain tools for agent workflows |
| #170 | </Card> |
| #171 | </CardGroup> |
| #172 | |
| #173 | |
| #174 |