Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions acp/ollama_weather_service/Dockerfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
FROM python:3.11-slim-bookworm
ARG RELEASE_VERSION="main"
COPY --from=ghcr.io/astral-sh/uv:0.6.16 /uv /bin/
WORKDIR /app
COPY . .
RUN uv sync --no-cache --locked --link-mode copy
ENV PRODUCTION_MODE=True \
RELEASE_VERSION=${RELEASE_VERSION}
CMD ["uv", "run", "--no-sync", "server"]
31 changes: 31 additions & 0 deletions acp/ollama_weather_service/pyproject.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
[project]
name = "ollama-weather-service"
version = "0.0.1"
description = "Simple ollama-based Langgraph agent with MCP tool calling."
authors = [
{ name = "Paolo Dettori" }
]
readme = "README.md"
license = { text = "Apache" }
requires-python = ">=3.11"
dependencies = [
"acp-sdk>=0.8.1",
"langgraph>=0.2.55",
"langchain-community>=0.3.9",
"tavily-python>=0.5.0",
"langchain-ollama>=0.2.1",
"duckduckgo-search~=7.5.5",
"beautifulsoup4>=4.13.3",
"langchain-openai>=0.3.7",
"openinference-instrumentation-langchain>=0.1.36",
"pydantic-settings>=2.8.1",
"langchain-mcp-adapters>=0.0.10",
]

[project.scripts]
server = "ollama_weather_service.agent:run"


[build-system]
requires = ["hatchling"]
build-backend = "hatchling.build"
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
.venv
Empty file.
100 changes: 100 additions & 0 deletions acp/ollama_weather_service/src/ollama_weather_service/agent.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
import os
from textwrap import dedent
from typing import AsyncIterator

from acp_sdk import Metadata, Message, Link, LinkType, MessagePart
from acp_sdk.server import Server
from openinference.instrumentation.langchain import LangChainInstrumentor
from pydantic import AnyUrl
from langchain_core.messages import HumanMessage

from ollama_weather_service.graph import get_graph, get_mcpclient


LangChainInstrumentor().instrument()

server = Server()


@server.agent(
metadata=Metadata(
programming_language="Python",
license="Apache 2.0",
framework="LangGraph",
links=[
Link(
type=LinkType.SOURCE_CODE,
url=AnyUrl(
f"https://github.com/i-am-bee/beeai-platform/blob/{os.getenv('RELEASE_VERSION', 'main')}"
"/agents/community/ollama-weather-service"
),
)
],
documentation=dedent(
"""\
This agent provides a simple weather infor assistant.

## Input Parameters
- **prompt** (string) – the city for which you want to know weather info.

## Key Features
- **MCP Tool Calling** – uses a MCP tool to get weather info.
""",
),
use_cases=[
"**Weather Assistant** – Personalized assistant for weather info.",
],
env=[
{"name": "LLM_MODEL", "description": "Model to use from the specified OpenAI-compatible API."},
{"name": "LLM_API_BASE", "description": "Base URL for OpenAI-compatible API endpoint"},
{"name": "LLM_API_KEY", "description": "API key for OpenAI-compatible API endpoint"},
{"name": "MCP_URL", "description": "MCP Server URL for the weather tool"},
],
ui={"type": "hands-off", "user_greeting": "Ask me about the weather"},
examples={
"cli": [
{
"command": 'beeai run ollama_weather_service "what is the weather in NY?"',
"description": "Running a Weather Query",
"processing_steps": [
"Calls the weather MCP tool to get the weather info"
"Parses results and return it",
],
}
]
},
)
)
async def ollama_weather_service(input: list[Message]) -> AsyncIterator:
"""
The agent allows to retrieve weather info through a natural language conversatinal interface
"""
messages = [HumanMessage(content=input[-1].parts[-1].content)]
input = {"messages": messages}
print(f"{input}")
try:
output = None
async with get_mcpclient() as mcpclient:
graph = await get_graph(mcpclient)
async for event in graph.astream(input, stream_mode="updates"):
yield {
"message": "\n".join(
f"🚶‍♂️{key}: {str(value)[:100] + '...' if len(str(value)) > 100 else str(value)}"
for key, value in event.items()
)
+ "\n"
}
output = event
print(event)
output = output.get("assistant", {}).get("messages")
yield MessagePart(content=str(output))
except Exception as e:
raise Exception(f"An error occurred while running the graph: {e}")


def run():
server.run(host=os.getenv("HOST", "127.0.0.1"), port=int(os.getenv("PORT", 8000)))


if __name__ == "__main__":
run()
48 changes: 48 additions & 0 deletions acp/ollama_weather_service/src/ollama_weather_service/graph.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
from langgraph.graph import StateGraph, MessagesState, START
from langchain_mcp_adapters.client import MultiServerMCPClient
from langchain_core.messages import SystemMessage
from langgraph.prebuilt import tools_condition, ToolNode
from langchain_ollama import ChatOllama
import os

def get_mcpclient():
return MultiServerMCPClient({
"math": {
"url": os.getenv("MCP_URL", "http://localhost:8000/sse"),
"transport": "sse",
}
}
)

async def get_graph(client) -> StateGraph:

llm = ChatOllama(
model="llama3.1",
openai_api_key="http://localhost:11434/v1",
openai_api_base="dummy",
temperature=0,
)
llm_with_tools = llm.bind_tools(client.get_tools())

# System message
sys_msg = SystemMessage(content="You are a helpful assistant tasked with providing weather information. You must use the provided tools to complete your task.")

# Node
def assistant(state: MessagesState):
return {"messages": [llm_with_tools.invoke([sys_msg] + state["messages"])]}

# Build graph
builder = StateGraph(MessagesState)
builder.add_node("assistant", assistant)
builder.add_node("tools", ToolNode(client.get_tools()))
builder.add_edge(START, "assistant")
builder.add_conditional_edges(
"assistant",
tools_condition,
)
builder.add_edge("tools", "assistant")

# Compile graph
graph = builder.compile()
return graph

Loading