Skip to content

Commit e75320a

Browse files
committed
fix[api]: config file parsing changed to singleton
1 parent b1e1273 commit e75320a

File tree

15 files changed

+281
-153
lines changed

15 files changed

+281
-153
lines changed

api/config.json.sample

+1-1
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,7 @@
3131
"model": "gpt-4o-mini",
3232
"api_key": "",
3333
"extra_params": {
34-
"host": "localhost:5000",
34+
"host": "",
3535
"models": ""
3636
}
3737
},

api/hello_copy/__init__.py

+17
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
from fastapi import APIRouter
2+
3+
from src.auth.routers import auth_router
4+
from src.user.routers import user_router
5+
from src.agent.routers import agent_router
6+
from src.project.routers import project_router
7+
from src.workspace.routers import workspace_router
8+
from src.conversation.routers import playground_conversation_router
9+
10+
api_router = APIRouter()
11+
api_router.include_router(auth_router.router, tags=["Auth"])
12+
api_router.include_router(user_router.router, tags=["User"])
13+
api_router.include_router(workspace_router.router, tags=["Workspace"])
14+
api_router.include_router(project_router.router, tags=["Project"])
15+
api_router.include_router(agent_router.router, tags=["Agent"])
16+
api_router.include_router(
17+
playground_conversation_router.router, tags=["Conversation"])

api/hello_copy/main.py

+101
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,101 @@
1+
import os
2+
import sentry_sdk
3+
4+
from dotenv import load_dotenv
5+
from fastapi.responses import JSONResponse
6+
from fastapi.openapi.utils import get_openapi
7+
from scalar_fastapi.scalar_fastapi import Layout
8+
from fastapi.middleware.cors import CORSMiddleware
9+
from scalar_fastapi import get_scalar_api_reference
10+
from fastapi import FastAPI, Request, HTTPException, status
11+
12+
from src import api_router
13+
from src.db.models import init_db
14+
from src.share.logging import Logging
15+
16+
load_dotenv()
17+
_logger = Logging().get_logger()
18+
19+
if os.environ.get("SENTRY_DSN"):
20+
# Initialize Sentry with your DSN
21+
sentry_sdk.init(
22+
dsn=os.environ.get("SENTRY_DSN"),
23+
# Add data like request headers and IP for users,
24+
# see https://docs.sentry.io/platforms/python/data-management/data-collected/ for more info
25+
send_default_pii=True,
26+
# Set traces_sample_rate to 1.0 to capture 100%
27+
# of transactions for tracing.
28+
traces_sample_rate=1.0,
29+
_experiments={
30+
# Set continuous_profiling_auto_start to True
31+
# to automatically start the profiler on when
32+
# possible.
33+
"continuous_profiling_auto_start": True,
34+
},
35+
)
36+
37+
app = FastAPI()
38+
39+
app.add_middleware(
40+
CORSMiddleware,
41+
allow_origins=["*"],
42+
allow_credentials=True,
43+
allow_methods=["*"],
44+
allow_headers=["*"],
45+
)
46+
47+
48+
# Global handler for all exceptions
49+
@app.exception_handler(Exception)
50+
async def global_exception_handler(request: Request, exc: Exception):
51+
52+
# Send the exception to Sentry
53+
if os.environ.get("SENTRY_DSN"):
54+
sentry_sdk.capture_exception(exc)
55+
56+
# You can customize the response based on the exception type
57+
if isinstance(exc, HTTPException):
58+
_logger.error(
59+
f"[{request.method}] {request.url} - {exc.status_code} - {exc.detail}")
60+
return JSONResponse(
61+
status_code=exc.status_code,
62+
content={"detail": exc.detail},
63+
)
64+
65+
# For any other exceptions, return a 500 error
66+
return JSONResponse(
67+
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
68+
content={"detail": "Internal server error"},
69+
)
70+
71+
72+
@app.get("/api-doc", include_in_schema=False)
73+
async def scalar_html():
74+
return get_scalar_api_reference(
75+
openapi_url=app.openapi_url,
76+
title="Pattern-Core API",
77+
hide_models=True,
78+
layout=Layout.MODERN
79+
)
80+
81+
82+
def custom_openapi():
83+
if app.openapi_schema:
84+
return app.openapi_schema
85+
86+
openapi_schema = get_openapi(
87+
title="Pattern-Core API",
88+
version="1.0.0",
89+
description="Pattern Core API Documentation for creating user, workspace, project, tool, and conversation.",
90+
routes=app.routes,
91+
)
92+
93+
app.openapi_schema = openapi_schema
94+
return app.openapi_schema
95+
96+
97+
app.openapi = custom_openapi
98+
99+
app.include_router(api_router)
100+
101+
init_db()

api/src/agent/services/agent_service.py

+7-16
Original file line numberDiff line numberDiff line change
@@ -1,23 +1,13 @@
1-
import os
21
import json
32
import asyncio
43

5-
from typing import List
6-
from langchain import hub
7-
from pydantic import BaseModel, Field
8-
from langchain_ollama import ChatOllama
9-
from langchain_openai import ChatOpenAI
10-
from langchain.agents import create_react_agent
11-
from langchain_core.prompts import ChatPromptTemplate
4+
from langchain.agents import AgentExecutor
125
from langchain.callbacks.base import BaseCallbackHandler
13-
from langchain_core.callbacks import StdOutCallbackHandler
146
from langchain_core.runnables.history import RunnableWithMessageHistory
15-
from langchain.agents import (AgentExecutor,
16-
create_openai_functions_agent,
17-
create_tool_calling_agent)
187

19-
from src.util.configuration import parse_config
20-
from src.agentflow.utils.shared_tools import init_llm, init_agent
8+
from src.util.configuration import Config
9+
from src.agentflow.utils.enum import AgentType
10+
from src.agentflow.utils.shared_tools import init_llm, init_agent, init_prompt
2111

2212

2313
class StreamingCallbackHandler(BaseCallbackHandler):
@@ -57,15 +47,16 @@ def __init__(self, sub_agents, memory=None, streaming: bool = True):
5747
if streaming:
5848
self.streaming_handler = StreamingCallbackHandler()
5949

60-
config = parse_config("config.json")
50+
config = Config.get_config()
6151

6252
self.llm = init_llm(service=config["llm"]["provider"],
6353
model_name=config["llm"]["model"],
6454
api_key=config["llm"]["api_key"],
6555
stream=streaming,
6656
callbacks=[self.streaming_handler] if self.streaming else None)
6757

68-
self.prompt = hub.pull("pattern-agent/pattern-agent")
58+
self.prompt = init_prompt(self.llm, AgentType.ROUTER_AGENT)
59+
6960
self.agent = init_agent(self.llm, self.sub_agents, self.prompt)
7061

7162
if streaming:

api/src/agentflow/agents/ether_scan_agent.py

+14-16
Original file line numberDiff line numberDiff line change
@@ -1,18 +1,15 @@
11
import os
22

3-
from langchain import hub
43
from langchain.tools import tool
5-
from langchain_ollama import ChatOllama
6-
from langchain_openai import ChatOpenAI
7-
from langchain.agents import (
8-
AgentExecutor,
9-
create_openai_functions_agent,
10-
create_tool_calling_agent)
4+
from langchain.agents import AgentExecutor
5+
from langchain_community.callbacks.manager import get_openai_callback
116

12-
from src.util.configuration import parse_config
7+
from src.util.configuration import Config
8+
from src.agentflow.utils.enum import AgentType
139
from src.agentflow.utils.tools_index import get_all_tools
14-
from src.agentflow.utils.shared_tools import init_llm, init_agent
15-
from src.agentflow.utils.shared_tools import handle_exceptions, timeout
10+
from src.agentflow.utils.shared_tools import handle_exceptions
11+
from src.agentflow.utils.shared_tools import init_llm, init_agent, init_prompt
12+
1613

1714
@tool
1815
@handle_exceptions
@@ -36,24 +33,25 @@ def etherscan_agent(query: str):
3633
Returns:
3734
str: Response containing the requested Ethereum blockchain information
3835
"""
39-
config = parse_config("config.json")
36+
config = Config.get_config()
4037

4138
llm = init_llm(service=config["llm"]["provider"],
42-
model_name=config["llm"]["model"],
43-
api_key=config["llm"]["api_key"],
44-
stream=False)
39+
model_name=config["llm"]["model"],
40+
api_key=config["llm"]["api_key"],
41+
stream=False)
4542

4643
tools = get_all_tools(tools_path="ether_scan_tools")
4744

48-
prompt = hub.pull("pattern-agent/eth-agent")
45+
prompt = init_prompt(llm, AgentType.BLOCKCHAIN_AGENT)
4946

5047
agent = init_agent(llm, tools, prompt)
5148

5249
agent_executor = AgentExecutor(
5350
agent=agent,
5451
tools=tools,
5552
return_intermediate_steps=True,
56-
verbose=True)
53+
verbose=True,
54+
stream_runnable=False)
5755

5856
response = agent_executor.invoke({"input": query})
5957

api/src/agentflow/agents/goldrush_agent.py

+7-14
Original file line numberDiff line numberDiff line change
@@ -1,18 +1,11 @@
1-
import os
2-
3-
from langchain import hub
41
from langchain.tools import tool
5-
from langchain_ollama import ChatOllama
6-
from langchain_openai import ChatOpenAI
7-
from langchain.agents import (
8-
AgentExecutor,
9-
create_openai_functions_agent,
10-
create_tool_calling_agent)
2+
from langchain.agents import AgentExecutor
113

12-
from src.util.configuration import parse_config
4+
from src.util.configuration import Config
5+
from src.agentflow.utils.enum import AgentType
136
from src.agentflow.utils.tools_index import get_all_tools
14-
from src.agentflow.utils.shared_tools import init_llm, init_agent
15-
from src.agentflow.utils.shared_tools import handle_exceptions, timeout
7+
from src.agentflow.utils.shared_tools import handle_exceptions
8+
from src.agentflow.utils.shared_tools import init_llm, init_agent, init_prompt
169

1710
@tool
1811
@handle_exceptions
@@ -34,7 +27,7 @@ def goldrush_agent(query: str):
3427
Returns:
3528
str: Response containing the requested Ethereum blockchain information
3629
"""
37-
config = parse_config("config.json")
30+
config = Config.get_config()
3831

3932
llm = init_llm(service=config["llm"]["provider"],
4033
model_name=config["llm"]["model"],
@@ -43,7 +36,7 @@ def goldrush_agent(query: str):
4336

4437
tools = get_all_tools(tools_path="goldrush_tools")
4538

46-
prompt = hub.pull("pattern-agent/eth-agent")
39+
prompt = init_prompt(llm, AgentType.BLOCKCHAIN_AGENT)
4740

4841
agent = init_agent(llm, tools, prompt)
4942

api/src/agentflow/providers/ether_scan_tools.py

+4-7
Original file line numberDiff line numberDiff line change
@@ -9,15 +9,12 @@
99
from typing import List, Any, Optional, Dict
1010

1111
from src.agentflow.utils.shared_tools import handle_exceptions
12-
from src.util.configuration import parse_config, get_service_config
12+
from src.util.configuration import Config
1313

1414

15-
def _get_config() -> dict:
16-
return parse_config("config.json")
17-
18-
_config = _get_config()
19-
_eth_rpc_config = get_service_config(_config, "eth_rpc")
20-
_ether_scan_config = get_service_config(_config, "etherscan")
15+
_config = Config.get_config()
16+
_eth_rpc_config = Config.get_service_config(_config, "eth_rpc")
17+
_ether_scan_config = Config.get_service_config(_config, "etherscan")
2118

2219

2320
@handle_exceptions

api/src/agentflow/providers/goldrush_tools.py

+3-7
Original file line numberDiff line numberDiff line change
@@ -6,15 +6,11 @@
66
from typing import Any, Dict, List, Optional
77

88
from src.agentflow.utils.shared_tools import handle_exceptions
9-
from src.util.configuration import parse_config, get_service_config
9+
from src.util.configuration import Config
1010

1111

12-
def _get_config() -> dict:
13-
return parse_config("config.json")
14-
15-
16-
_config = _get_config()
17-
_goldrush_config = get_service_config(_config, "goldrush")
12+
_config = Config.get_config()
13+
_goldrush_config = Config.get_service_config(_config, "goldrush")
1814

1915

2016
def _call_goldrush_api(url: str, params: Optional[Dict[str, Any]] = None) -> Dict:

api/src/agentflow/providers/moralis_tools.py

+2
Original file line numberDiff line numberDiff line change
@@ -86,3 +86,5 @@ def get_contract_transactions(contract_address: str) -> List[Dict[str, Any]]:
8686
})
8787

8888
return decoded_transactions[:20]
89+
90+

api/src/agentflow/utils/enum.py

+27
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
from enum import Enum
2+
from langchain import hub
3+
4+
5+
class AgentType(Enum):
6+
"""
7+
Enum for agent types.
8+
9+
ROUTER_AGENT: Router agent.
10+
SUB_AGENT: Sub agent.
11+
"""
12+
ROUTER_AGENT = "router_agent"
13+
BLOCKCHAIN_AGENT = "blockchain_agent"
14+
REACT_AGENT = "react_agent"
15+
16+
17+
class Prompt():
18+
"""
19+
Registry for prompts.
20+
21+
BLOCKCHAIN_AGENT: Prompt for the blockchain agent.
22+
ROUTER_AGENT: Prompt for the router agent.
23+
REACT_AGENT: Prompt for the react agent.
24+
"""
25+
BLOCKCHAIN_AGENT = hub.pull("pattern-agent/eth-agent")
26+
ROUTER_AGENT = hub.pull("pattern-agent/pattern-agent")
27+
REACT_AGENT = hub.pull("hwchase17/react")

0 commit comments

Comments
 (0)