Building Your First Morph App

As your first AI app using Morph, we will create a chat app using Langchain.

If the Morph CLI setup is not complete, please refer to the Installation Documentation to install the CLI.

This tutorial requires an OpenAI API key. To obtain an API key, please visit the OpenAI website.

1

Initialize the Project

Run the following command in the terminal to create a new project.

morph new chat-app
2

Install Packages

To use Langchain, run the following command to install the package.

pip install langchain langchain-openai
3

Create chat.py

Create a chat.py file in the src/python directory.

src/python/chat.py
  import morph
  from morph import MorphGlobalContext
  from morph_lib.stream import stream_chat
  from langchain_openai import ChatOpenAI
  from langchain_core.messages import HumanMessage

  @morph.func
  def langchain_chat(context: MorphGlobalContext):
    llm = ChatOpenAI(model="gpt-4o")
    messages = [HumanMessage(context.vars["prompt"])]
    for token in llm.stream(messages):
      yield stream_chat(token.content)
4

Edit index.mdx

Edit index.mdx to use the Python function created earlier.

src/pages/index.mdx
# 🦜🔗 Langchain Chat

<Chat postData="langchain_chat" height={300} />
5

Add API key to .env

Add your OpenAI API key to the .env file.

.env
OPENAI_API_KEY=your_api_key
6

Start the Local Server

Run the following command in the terminal to start the development server.

morph serve

Access localhost:8080 to open the app.

Here is all the code needed to build a simple chat app. That’s it!