Skip to main content
Version: Next 🚧

agent

Conversational AI agent for Vietnamese language tasks using OpenAI or Azure OpenAI.

Usage

from underthesea import agent

response = agent("Xin chào, NLP là gì?")
print(response)
# NLP (Natural Language Processing) là xử lý ngôn ngữ tự nhiên...

Installation

pip install "underthesea[agent]"

Configuration

Environment Variables

export OPENAI_API_KEY="sk-..."
export OPENAI_MODEL="gpt-4o-mini" # optional

Environment Variables Reference

ProviderVariableRequiredDescription
OpenAIOPENAI_API_KEYYesOpenAI API key
OpenAIOPENAI_MODELNoModel name (default: gpt-4o-mini)
AzureAZURE_OPENAI_API_KEYYesAzure OpenAI API key
AzureAZURE_OPENAI_ENDPOINTYesAzure OpenAI endpoint URL
AzureAZURE_OPENAI_DEPLOYMENTNoDeployment name (default: gpt-4o-mini)
AzureAZURE_OPENAI_API_VERSIONNoAPI version (default: 2024-02-01)

Function Signature

def agent(
message: str,
model: str | None = None,
system_prompt: str | None = None,
provider: str | None = None,
api_key: str | None = None,
azure_endpoint: str | None = None,
azure_api_version: str | None = None,
) -> str

Parameters

ParameterTypeDefaultDescription
messagestrUser message to send
modelstrNoneModel/deployment name. Falls back to env var or gpt-4o-mini
system_promptstrNoneCustom system prompt
providerstrNoneProvider: "openai" or "azure". Auto-detected if not specified
api_keystrNoneAPI key. Falls back to environment variable
azure_endpointstrNoneAzure endpoint URL. Falls back to AZURE_OPENAI_ENDPOINT
azure_api_versionstrNoneAzure API version. Falls back to env var or 2024-02-01

Returns

TypeDescription
strAssistant response

Methods

agent.reset()

Clear conversation history.

agent.reset()

agent.history

Get conversation history (read-only copy).

history = agent.history
# [{'role': 'user', 'content': '...'}, {'role': 'assistant', 'content': '...'}]

Examples

Basic Conversation

from underthesea import agent

# First message
response = agent("Xin chào!")
print(response)
# Xin chào! Tôi có thể giúp gì cho bạn?

# Follow-up (history is maintained)
response = agent("NLP là gì?")
print(response)
# NLP (Natural Language Processing) là...

# Check history
print(len(agent.history)) # 4 (2 user + 2 assistant messages)

# Reset conversation
agent.reset()
print(len(agent.history)) # 0

Custom System Prompt

from underthesea import agent

response = agent(
"Chào bạn",
system_prompt="Bạn là trợ lý chuyên về ẩm thực Việt Nam."
)

Custom Model

from underthesea import agent

# Use GPT-4
response = agent("Giải thích machine learning", model="gpt-4")

# Use GPT-4 Turbo
response = agent("Giải thích deep learning", model="gpt-4-turbo")

Azure OpenAI

from underthesea import agent

# Using environment variables (recommended)
# export AZURE_OPENAI_API_KEY="..."
# export AZURE_OPENAI_ENDPOINT="https://xxx.openai.azure.com"
# export AZURE_OPENAI_DEPLOYMENT="my-gpt4"

response = agent("Xin chào")

# Or explicit configuration
response = agent(
"Xin chào",
provider="azure",
api_key="your-azure-key",
azure_endpoint="https://your-resource.openai.azure.com",
model="your-deployment-name"
)

Vietnamese NLP Assistant

from underthesea import agent, word_tokenize, pos_tag

# Use agent to explain NLP concepts
text = "Học máy là gì?"
response = agent(text)
print(response)

# Combine with other underthesea functions
text = "Việt Nam là quốc gia xinh đẹp"
tokens = word_tokenize(text)
tags = pos_tag(text)

# Ask agent to explain the results
response = agent(f"Giải thích kết quả POS tagging: {tags}")
print(response)

LLM Class

For more control, use the LLM class directly:

from underthesea.agent import LLM

# Initialize
llm = LLM(model="gpt-4")

# Chat with custom messages
messages = [
{"role": "system", "content": "You are a Vietnamese language expert."},
{"role": "user", "content": "Explain word segmentation in Vietnamese."}
]
response = llm.chat(messages)
print(response)

# Check provider
print(llm.provider) # 'openai' or 'azure'
print(llm.model) # 'gpt-4'

Agent Class with Tools

Create custom agents with function calling support using OpenAI's tools API.

Basic Usage

from underthesea.agent import Agent, Tool

# Define a tool as a Python function
def get_weather(location: str) -> dict:
"""Get current weather for a location."""
return {"location": location, "temp": 25, "condition": "sunny"}

# Create agent with tools
my_agent = Agent(
name="weather_assistant",
tools=[Tool(get_weather, description="Get weather for a city")],
instruction="You are a helpful weather assistant."
)

# Use the agent - it will automatically call tools when needed
response = my_agent("What's the weather in Hanoi?")
print(response)
# The weather in Hanoi is 25°C and sunny.

# Reset conversation
my_agent.reset()

Agent Constructor

Agent(
name: str,
tools: list[Tool] | None = None,
instruction: str | None = None,
max_iterations: int = 10,
)
ParameterTypeDefaultDescription
namestrAgent name
toolslist[Tool]NoneList of tools available to the agent
instructionstr"You are a helpful assistant."System instruction
max_iterationsint10Maximum tool calling iterations

Tool Class

Wrap Python functions as agent tools:

from underthesea.agent import Tool

def search(query: str, limit: int = 10) -> list:
"""Search for items matching the query."""
return [{"title": f"Result for {query}"}]

tool = Tool(
func=search,
name="web_search", # Optional, defaults to function name
description="Search the web" # Optional, defaults to docstring
)

# Convert to OpenAI format
openai_format = tool.to_openai_tool()

# Execute directly
result = tool(query="python", limit=5)

Tool Constructor

Tool(
func: Callable,
name: str | None = None,
description: str | None = None,
)
ParameterTypeDefaultDescription
funcCallableThe function to wrap
namestrNoneTool name (defaults to function name)
descriptionstrNoneTool description (defaults to docstring)

Supported Parameter Types

The Tool class automatically extracts JSON schema from function signatures:

Python TypeJSON Schema Type
strstring
intinteger
floatnumber
boolboolean
listarray

Multiple Tools Example

from underthesea.agent import Agent, Tool

def get_weather(location: str) -> dict:
"""Get current weather for a location."""
return {"location": location, "temp": 25}

def search_news(query: str) -> str:
"""Search Vietnamese news articles."""
return f"Found articles about: {query}"

def translate_text(text: str, target_lang: str = "en") -> str:
"""Translate Vietnamese text."""
return f"Translated: {text}"

agent = Agent(
name="multi_tool_agent",
tools=[
Tool(get_weather),
Tool(search_news),
Tool(translate_text, description="Translate Vietnamese to other languages"),
],
instruction="You are a helpful Vietnamese assistant with access to weather, news, and translation tools."
)

# The agent decides which tool to use based on the query
response = agent("Thời tiết ở Đà Nẵng thế nào?") # Uses get_weather
response = agent("Tin tức về AI hôm nay") # Uses search_news
response = agent("Dịch 'Xin chào' sang tiếng Anh") # Uses translate_text

Agent without Tools

Agent also works without tools as a simple conversational agent:

from underthesea.agent import Agent

simple_agent = Agent(
name="chatbot",
instruction="You are a friendly Vietnamese chatbot."
)

response = simple_agent("Xin chào!")
print(response)

Default Tools

Pre-built tools similar to LangChain/OpenAI tools for common tasks.

Tool Collections

CollectionToolsDescription
default_tools12 toolsAll default tools
core_tools4 toolsSafe utilities (datetime, calculator, string, json)
web_tools3 toolsWeb operations (search, fetch, wikipedia)
system_tools5 toolsSystem operations (file, shell, python)

Core Tools

ToolDescription
current_datetime_toolGet current date, time, weekday
calculator_toolEvaluate math expressions (supports sqrt, sin, cos, log, pi, e)
string_length_toolCount characters, words, lines in text
json_parse_toolParse JSON strings

Web Tools

ToolDescription
web_search_toolSearch the web using DuckDuckGo (no API key)
fetch_url_toolFetch content from a URL
wikipedia_toolSearch Wikipedia (supports Vietnamese and English)

System Tools

ToolDescription
read_file_toolRead content from a file
write_file_toolWrite content to a file
list_directory_toolList files and directories
shell_toolRun shell commands
python_toolExecute Python code

Using Default Tools

from underthesea.agent import Agent, default_tools

# Create agent with all default tools
my_agent = Agent(
name="assistant",
tools=default_tools,
instruction="You are a helpful assistant with access to various tools."
)

# Agent can now use any tool automatically
my_agent("What time is it?") # Uses current_datetime_tool
my_agent("Calculate sqrt(144) + 10") # Uses calculator_tool
my_agent("Search for Python tutorials") # Uses web_search_tool
my_agent("List files in current dir") # Uses list_directory_tool

Using Specific Tool Collections

from underthesea.agent import Agent, core_tools, web_tools

# Safe agent with only core tools (no system access)
safe_agent = Agent(
name="safe_assistant",
tools=core_tools,
)

# Web-enabled agent
web_agent = Agent(
name="web_assistant",
tools=core_tools + web_tools,
)

Using Tools Directly

from underthesea.agent import calculator_tool, current_datetime_tool, wikipedia_tool

# Call tools directly (without LLM)
result = calculator_tool(expression="2 ** 10")
print(result) # {'expression': '2 ** 10', 'result': 1024}

now = current_datetime_tool()
print(now) # {'datetime': '...', 'date': '...', 'weekday': 'Friday', ...}

wiki = wikipedia_tool(query="Hà Nội", lang="vi")
print(wiki["summary"]) # Wikipedia summary about Hanoi

Notes

  • The agent maintains conversation history across calls
  • Use agent.reset() to start a new conversation
  • Azure OpenAI is preferred when both credentials are available
  • Default system prompt focuses on Vietnamese language and NLP tasks
  • First call may be slower due to client initialization
  • Agent with tools uses OpenAI's function calling API
  • Tools are automatically called when the model decides they are needed
  • max_iterations prevents infinite tool calling loops