Home Backend Development Python Tutorial Create your own Custom LLM Agent Using Open Source Models (llama)

Create your own Custom LLM Agent Using Open Source Models (llama)

Aug 18, 2024 am 06:04 AM

Create your own Custom LLM Agent Using Open Source Models (llama)

In this article, we will learn how to create a custom agent that uses an open source llm (llama3.1) that runs locally on our PC. We will also use Ollama and LangChain.

Outline

  • Install Ollama
  • Pull model
  • Serve model
  • Create a new folder, open it with a code editor
  • Create and activate Virtual environment
  • Install langchain langchain-ollama
  • Build Custom agent with open source model in Python
  • Conclusion

Install Ollama

Follow the instructions based on your OS type in its GitHub README to install Ollama:

https://github.com/ollama/ollama
Copy after login

I am on a Linux-based PC, so I am going to run the following command in my terminal:

curl -fsSL https://ollama.com/install.sh | sh
Copy after login

Pull model

Fetch the available LLM model via the following command:

ollama pull llama3.1
Copy after login

This will download the default tagged version of the model. Typically, the default points to the latest, smallest sized-parameter model. In this case, it will be llama3.1:8b model.

To download another version of the model, you can go to: https://ollama.com/library/llama3.1 and select the version to install, and then run the ollama pull command with the model and its version number. Example: ollama pull llama3.1:70b

On Mac, the models will be downloaded to ~/.ollama/models

On Linux (or WSL), the models will be stored at /usr/share/ollama/.ollama/models

Serve model

Run the following command to start ollama without running the desktop application.

ollama serve
Copy after login

All models are automatically served on localhost:11434

Create a new folder, open it with a code editor

Create a new folder on your computer and then open it with a code editor like VS Code.

Create and activate Virtual environment

Open the terminal. Use the following command to create a virtual environment .venv and activate it:

python3 -m venv .venv
Copy after login
source .venv/bin/activate
Copy after login

Install langchain langchain-ollama

Run the following command to install langchain and langchain-ollama:

pip install -U langchain langchain-ollama
Copy after login

The above command will install or upgrade the LangChain and LangChain-Ollama packages in Python. The -U flag ensures that the latest versions of these packages are installed, replacing any older versions that may already be present.

Build Custom agent with open source model in Python

Create a Python file for example: main.py and add the following code:

from langchain_ollama import ChatOllama
from langchain.agents import tool
from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder
from langchain.agents.format_scratchpad.openai_tools import (
    format_to_openai_tool_messages,
)
from langchain.agents import AgentExecutor
from langchain.agents.output_parsers.openai_tools import OpenAIToolsAgentOutputParser


llm = ChatOllama(
            model="llama3.1",
            temperature=0,
            verbose=True
        )

@tool
def get_word_length(word: str) -> int:
    """Returns the length of a word."""
    return len(word)


tools = [get_word_length]



prompt = ChatPromptTemplate.from_messages(
            [
                (
                    "system",
                    "You are very powerful assistant",
                ),
                ("user", "{input}"),
                MessagesPlaceholder(variable_name="agent_scratchpad"),
            ]
        )

llm_with_tools = llm.bind_tools(tools)

agent = (
    {
        "input": lambda x: x["input"],
        "agent_scratchpad": lambda x: format_to_openai_tool_messages(
            x["intermediate_steps"]
        ),
    }
    | prompt
    | llm_with_tools
    | OpenAIToolsAgentOutputParser()
)

# Create an agent executor by passing in the agent and tools
agent_executor = AgentExecutor(agent=agent, tools=tools, verbose=True)
result = agent_executor.invoke({"input": "How many letters in the word educa"})

if result:
    print(f"[Output] --> {result['output']}")
else:
    print('There are no result..')
Copy after login

The above code snippet sets up a LangChain agent using the ChatOllama model (llama3.1) to process user input and utilize a custom tool that calculates word length. It defines a prompt template for the agent, binds the tool to the language model, and constructs an agent that processes input and formats intermediate steps. Finally, it creates an AgentExecutor to invoke the agent with a specific input. We pass a simple question to ask "How many letters in the word educa" and then we print the output or indicate if no result was found.

When we run, we get the following result:

> Entering new AgentExecutor chain...

Invoking: `get_word_length` with `{'word': 'educa'}`


5The word "educa" has 5 letters.

> Finished chain.
[Output] --> The word "educa" has 5 letters.
Copy after login

You see the agent used the model (llama3.1) to call the tool correctly to get the count of letters in the word.

Conclusion

Thanks for reading.

Check Ollama repo here: https://github.com/ollama/ollama

The above is the detailed content of Create your own Custom LLM Agent Using Open Source Models (llama). For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Python vs. C  : Applications and Use Cases Compared Python vs. C : Applications and Use Cases Compared Apr 12, 2025 am 12:01 AM

Python is suitable for data science, web development and automation tasks, while C is suitable for system programming, game development and embedded systems. Python is known for its simplicity and powerful ecosystem, while C is known for its high performance and underlying control capabilities.

How Much Python Can You Learn in 2 Hours? How Much Python Can You Learn in 2 Hours? Apr 09, 2025 pm 04:33 PM

You can learn the basics of Python within two hours. 1. Learn variables and data types, 2. Master control structures such as if statements and loops, 3. Understand the definition and use of functions. These will help you start writing simple Python programs.

Python: Games, GUIs, and More Python: Games, GUIs, and More Apr 13, 2025 am 12:14 AM

Python excels in gaming and GUI development. 1) Game development uses Pygame, providing drawing, audio and other functions, which are suitable for creating 2D games. 2) GUI development can choose Tkinter or PyQt. Tkinter is simple and easy to use, PyQt has rich functions and is suitable for professional development.

The 2-Hour Python Plan: A Realistic Approach The 2-Hour Python Plan: A Realistic Approach Apr 11, 2025 am 12:04 AM

You can learn basic programming concepts and skills of Python within 2 hours. 1. Learn variables and data types, 2. Master control flow (conditional statements and loops), 3. Understand the definition and use of functions, 4. Quickly get started with Python programming through simple examples and code snippets.

Python: Exploring Its Primary Applications Python: Exploring Its Primary Applications Apr 10, 2025 am 09:41 AM

Python is widely used in the fields of web development, data science, machine learning, automation and scripting. 1) In web development, Django and Flask frameworks simplify the development process. 2) In the fields of data science and machine learning, NumPy, Pandas, Scikit-learn and TensorFlow libraries provide strong support. 3) In terms of automation and scripting, Python is suitable for tasks such as automated testing and system management.

Python vs. C  : Learning Curves and Ease of Use Python vs. C : Learning Curves and Ease of Use Apr 19, 2025 am 12:20 AM

Python is easier to learn and use, while C is more powerful but complex. 1. Python syntax is concise and suitable for beginners. Dynamic typing and automatic memory management make it easy to use, but may cause runtime errors. 2.C provides low-level control and advanced features, suitable for high-performance applications, but has a high learning threshold and requires manual memory and type safety management.

Python and Time: Making the Most of Your Study Time Python and Time: Making the Most of Your Study Time Apr 14, 2025 am 12:02 AM

To maximize the efficiency of learning Python in a limited time, you can use Python's datetime, time, and schedule modules. 1. The datetime module is used to record and plan learning time. 2. The time module helps to set study and rest time. 3. The schedule module automatically arranges weekly learning tasks.

Python: Automation, Scripting, and Task Management Python: Automation, Scripting, and Task Management Apr 16, 2025 am 12:14 AM

Python excels in automation, scripting, and task management. 1) Automation: File backup is realized through standard libraries such as os and shutil. 2) Script writing: Use the psutil library to monitor system resources. 3) Task management: Use the schedule library to schedule tasks. Python's ease of use and rich library support makes it the preferred tool in these areas.

See all articles