|
| 1 | +import json |
| 2 | +from typing import AsyncIterator, Dict, Callable, Optional |
| 3 | +import uuid |
| 4 | +from langchain.agents import AgentExecutor |
| 5 | +from data_class import ChatData, Message |
| 6 | +from langchain.agents.format_scratchpad.openai_tools import ( |
| 7 | + format_to_openai_tool_messages, |
| 8 | +) |
| 9 | +from langchain_core.messages import AIMessage, FunctionMessage, HumanMessage |
| 10 | +from langchain.agents.output_parsers.openai_tools import OpenAIToolsAgentOutputParser |
| 11 | +from langchain.prompts import PromptTemplate, MessagesPlaceholder |
| 12 | +from langchain_core.utils.function_calling import convert_to_openai_tool |
| 13 | +from langchain_core.prompts import ChatPromptTemplate |
| 14 | +from langchain.utilities.tavily_search import TavilySearchAPIWrapper |
| 15 | +from langchain.tools.tavily_search import TavilySearchResults |
| 16 | +from langchain_openai import ChatOpenAI |
| 17 | +from uilts.env import get_env_variable |
| 18 | + |
| 19 | +OPEN_API_KEY = get_env_variable("OPENAI_API_KEY") |
| 20 | +TAVILY_API_KEY = get_env_variable("TAVILY_API_KEY") |
| 21 | + |
| 22 | +class AgentBuilder: |
| 23 | + |
| 24 | + def __init__( |
| 25 | + self, |
| 26 | + prompt: str, |
| 27 | + tools: Dict[str, Callable], |
| 28 | + enable_tavily: Optional[bool] = True, |
| 29 | + temperature: Optional[int] = 0.2, |
| 30 | + max_tokens: Optional[int] = 1500 |
| 31 | + ): |
| 32 | + """ |
| 33 | + @class `Builde AgentExecutor based on tools and prompt` |
| 34 | + @param prompt: str |
| 35 | + @param tools: Dict[str, Callable] |
| 36 | + @param enable_tavily: Optional[bool] If set True, enables the Tavily tool |
| 37 | + @param temperature: Optional[int] |
| 38 | + @param max_tokens: Optional[int] |
| 39 | + """ |
| 40 | + self.prompt = prompt |
| 41 | + self.tools = tools |
| 42 | + self.enable_tavily = enable_tavily |
| 43 | + self.temperature = temperature |
| 44 | + self.max_tokens = max_tokens |
| 45 | + self.agent_executor = self._create_agent_with_tools() |
| 46 | + |
| 47 | + def init_tavily_tools(self): |
| 48 | + # init Tavily |
| 49 | + search = TavilySearchAPIWrapper() |
| 50 | + tavily_tool = TavilySearchResults(api_wrapper=search) |
| 51 | + return [tavily_tool] |
| 52 | + |
| 53 | + def _create_agent_with_tools(self) -> AgentExecutor: |
| 54 | + llm = ChatOpenAI(model="gpt-4-1106-preview", temperature=self.temperature, streaming=True, max_tokens=self.max_tokens, openai_api_key=OPEN_API_KEY) |
| 55 | + |
| 56 | + tools = self.init_tavily_tools() if self.enable_tavily else [] |
| 57 | + for tool in self.tools.values(): |
| 58 | + tools.append(tool) |
| 59 | + |
| 60 | + if tools: |
| 61 | + llm_with_tools = llm.bind( |
| 62 | + tools=[convert_to_openai_tool(tool) for tool in tools] |
| 63 | + ) |
| 64 | + else: |
| 65 | + llm_with_tools = llm |
| 66 | + |
| 67 | + self.prompt = self.get_prompt() |
| 68 | + agent = ( |
| 69 | + { |
| 70 | + "input": lambda x: x["input"], |
| 71 | + "agent_scratchpad": lambda x: format_to_openai_tool_messages( |
| 72 | + x["intermediate_steps"] |
| 73 | + ), |
| 74 | + "chat_history": lambda x: x["chat_history"], |
| 75 | + } |
| 76 | + | self.prompt |
| 77 | + | llm_with_tools |
| 78 | + | OpenAIToolsAgentOutputParser() |
| 79 | + ) |
| 80 | + |
| 81 | + return AgentExecutor(agent=agent, tools=tools, verbose=True, handle_parsing_errors=True, max_iterations=5) |
| 82 | + |
| 83 | + def get_prompt(self): |
| 84 | + return ChatPromptTemplate.from_messages( |
| 85 | + [ |
| 86 | + ("system", self.prompt), |
| 87 | + MessagesPlaceholder(variable_name="chat_history"), |
| 88 | + ("user", "{input}"), |
| 89 | + MessagesPlaceholder(variable_name="agent_scratchpad"), |
| 90 | + ] |
| 91 | + ) |
| 92 | + |
| 93 | + @staticmethod |
| 94 | + def chat_history_transform(messages: list[Message]): |
| 95 | + transformed_messages = [] |
| 96 | + for message in messages: |
| 97 | + print('message', message) |
| 98 | + if message.role == "user": |
| 99 | + transformed_messages.append(HumanMessage(content=message.content)) |
| 100 | + elif message.role == "assistant": |
| 101 | + transformed_messages.append(AIMessage(content=message.content)) |
| 102 | + else: |
| 103 | + transformed_messages.append(FunctionMessage(content=message.content)) |
| 104 | + return transformed_messages |
| 105 | + |
| 106 | + async def run_chat(self, input_data: ChatData) -> AsyncIterator[str]: |
| 107 | + try: |
| 108 | + messages = input_data.messages |
| 109 | + print(self.chat_history_transform(messages)) |
| 110 | + |
| 111 | + async for event in self.agent_executor.astream_events( |
| 112 | + { |
| 113 | + "input": messages[len(messages) - 1].content, |
| 114 | + "chat_history": self.chat_history_transform(messages), |
| 115 | + }, |
| 116 | + version="v1", |
| 117 | + ): |
| 118 | + kind = event["event"] |
| 119 | + if kind == "on_chain_start": |
| 120 | + if ( |
| 121 | + event["name"] == "agent" |
| 122 | + ): |
| 123 | + print( |
| 124 | + f"Starting agent: {event['name']} " |
| 125 | + f"with input: {event['data'].get('input')}" |
| 126 | + ) |
| 127 | + elif kind == "on_chain_end": |
| 128 | + if ( |
| 129 | + event["name"] == "agent" |
| 130 | + ): |
| 131 | + print ( |
| 132 | + f"Done agent: {event['name']} " |
| 133 | + f"with output: {event['data'].get('output')['output']}" |
| 134 | + ) |
| 135 | + if kind == "on_chat_model_stream": |
| 136 | + uid = str(uuid.uuid4()) |
| 137 | + content = event["data"]["chunk"].content |
| 138 | + if content: |
| 139 | + yield f"{content}" |
| 140 | + elif kind == "on_tool_start": |
| 141 | + children_value = event["data"].get("input", {}) |
| 142 | + json_output = json.dumps({ |
| 143 | + "type": "tool", |
| 144 | + "id": uid, |
| 145 | + "extra": { |
| 146 | + "source": f"已调用工具: {event['name']}", |
| 147 | + "pluginName": "GitHub", |
| 148 | + "data": json.dumps(children_value, ensure_ascii=False), |
| 149 | + "status": "loading" |
| 150 | + } |
| 151 | + }, ensure_ascii=False) |
| 152 | + |
| 153 | + yield f"<TOOL>{json_output}\n" |
| 154 | + elif kind == "on_tool_end": |
| 155 | + children_value = event["data"].get("output", {}) |
| 156 | + json_output = json.dumps({ |
| 157 | + "type": "tool", |
| 158 | + "id": uid, |
| 159 | + "extra": { |
| 160 | + "source": f"已调用工具: {event['name']}", |
| 161 | + "pluginName": "GitHub", |
| 162 | + "data": children_value, |
| 163 | + "status": "success" |
| 164 | + }, |
| 165 | + }, ensure_ascii=False) |
| 166 | + yield f"<TOOL>{json_output}\n<ANSWER>" |
| 167 | + except Exception as e: |
| 168 | + yield f"data: {str(e)}\n" |
| 169 | + |
| 170 | + |
0 commit comments