sasukeUchiha123 commited on
Commit
8986207
Β·
verified Β·
1 Parent(s): a14ad5f

Upload agent/backends/qwen_vllm.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. agent/backends/qwen_vllm.py +200 -0
agent/backends/qwen_vllm.py ADDED
@@ -0,0 +1,200 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """QwenVLLMBackend β€” drives Qwen via a self-hosted vLLM-on-MI300X endpoint.
2
+
3
+ This is the "all AMD silicon" path: Qwen runs on the same MI300X that's
4
+ auditing the user's workload, served by vLLM behind an OpenAI-compatible
5
+ ``/v1/chat/completions`` endpoint. We talk to it with the standard ``openai``
6
+ SDK pointed at a custom ``base_url``.
7
+
8
+ Stand it up with the lablab tutorial recipe β€” TL;DR:
9
+
10
+ docker run -d --name qwen-vllm \\
11
+ --device=/dev/kfd --device=/dev/dri --group-add video \\
12
+ --ipc=host --shm-size=16g \\
13
+ -p 8000:8000 \\
14
+ -v $HF_HOME:/root/.cache/huggingface \\
15
+ rocm/vllm:latest \\
16
+ --model Qwen/Qwen2.5-7B-Instruct \\
17
+ --dtype bfloat16 \\
18
+ --max-model-len 8192 \\
19
+ --enable-auto-tool-choice \\
20
+ --tool-call-parser hermes
21
+
22
+ The ``--enable-auto-tool-choice --tool-call-parser hermes`` flags are the
23
+ ones that matter β€” Qwen2.5 uses Hermes-format tool tags and vLLM needs to
24
+ parse them into the OpenAI ``tool_calls`` shape on the way out.
25
+
26
+ Configuration (env vars):
27
+ GOBLIN_QWEN_VLLM_URL Base URL ending in /v1. Default http://localhost:8000/v1.
28
+ GOBLIN_QWEN_VLLM_MODEL Served model id. Default Qwen/Qwen2.5-7B-Instruct.
29
+ GOBLIN_QWEN_VLLM_KEY Optional auth header. vLLM ignores it by default;
30
+ useful if you put nginx/Caddy in front with auth.
31
+ """
32
+
33
+ from __future__ import annotations
34
+
35
+ import json
36
+ import os
37
+ from typing import Any
38
+
39
+ from agent.backends.base import AgentTurn, Backend, ToolCall
40
+
41
+ DEFAULT_URL = "http://localhost:8000/v1"
42
+ DEFAULT_MODEL = "Qwen/Qwen2.5-7B-Instruct"
43
+ DEFAULT_API_KEY = "EMPTY"
44
+ DEFAULT_MAX_TOKENS = 2048
45
+
46
+
47
+ class QwenVLLMBackend(Backend):
48
+ """OpenAI-compatible client pointed at a self-hosted vLLM endpoint.
49
+
50
+ Same OpenAI conversation shape ``QwenHFBackend`` uses β€” the only
51
+ difference is the transport: we hit a URL we control instead of HF's
52
+ Inference Providers router. That means tool-call latency drops to
53
+ in-cluster network (good) and we burn MI300X cycles instead of HF
54
+ credits (also good β€” it's what the AMD credits are for).
55
+ """
56
+
57
+ name = "qwen-vllm"
58
+
59
+ def __init__(
60
+ self,
61
+ system_prompt: str,
62
+ model: str | None = None,
63
+ base_url: str | None = None,
64
+ api_key: str | None = None,
65
+ max_tokens: int = DEFAULT_MAX_TOKENS,
66
+ ) -> None:
67
+ self._system = system_prompt
68
+ self._model = model or os.environ.get("GOBLIN_QWEN_VLLM_MODEL", DEFAULT_MODEL)
69
+ self._base_url = base_url or os.environ.get(
70
+ "GOBLIN_QWEN_VLLM_URL", DEFAULT_URL
71
+ )
72
+ self._api_key = api_key or os.environ.get(
73
+ "GOBLIN_QWEN_VLLM_KEY", DEFAULT_API_KEY
74
+ )
75
+ self._max_tokens = max_tokens
76
+ self._client = self._build_client()
77
+ # System message at head of conversation (OpenAI shape).
78
+ self._conversation: list[dict[str, Any]] = [
79
+ {"role": "system", "content": system_prompt}
80
+ ]
81
+
82
+ def _build_client(self) -> Any:
83
+ # Lazy import β€” pulls openai SDK only when this backend is selected.
84
+ try:
85
+ from openai import AsyncOpenAI
86
+ except ImportError as exc:
87
+ raise RuntimeError(
88
+ "QwenVLLMBackend requires the 'openai' package. "
89
+ "Install with `pip install openai>=1.30` (or `pip install -e \".[dev]\"` "
90
+ "for the full dev extras)."
91
+ ) from exc
92
+ return AsyncOpenAI(base_url=self._base_url, api_key=self._api_key)
93
+
94
+ # ------------------------------------------------------------------
95
+ # Backend API
96
+ # ------------------------------------------------------------------
97
+
98
+ def add_user_message(self, content: str) -> None:
99
+ self._conversation.append({"role": "user", "content": content})
100
+
101
+ def add_tool_result(
102
+ self,
103
+ tool_call_id: str,
104
+ name: str, # noqa: ARG002 β€” OpenAI shape correlates by tool_call_id only
105
+ content: str,
106
+ is_error: bool,
107
+ ) -> None:
108
+ if is_error and not content.startswith("ERROR:"):
109
+ content = f"ERROR: {content}"
110
+ self._conversation.append(
111
+ {
112
+ "role": "tool",
113
+ "tool_call_id": tool_call_id,
114
+ "content": content,
115
+ }
116
+ )
117
+
118
+ async def next_turn(self, tool_schemas: list[dict[str, Any]]) -> AgentTurn:
119
+ oai_tools = _to_openai_tools(tool_schemas)
120
+
121
+ response = await self._client.chat.completions.create(
122
+ model=self._model,
123
+ messages=self._conversation,
124
+ tools=oai_tools,
125
+ max_tokens=self._max_tokens,
126
+ tool_choice="auto",
127
+ )
128
+
129
+ choice = response.choices[0]
130
+ msg = choice.message
131
+ text = (msg.content or "").strip()
132
+
133
+ # Echo the assistant turn back so the next request carries any
134
+ # pending tool_calls forward (vLLM enforces this in strict mode).
135
+ echoed: dict[str, Any] = {"role": "assistant", "content": msg.content or ""}
136
+ if msg.tool_calls:
137
+ echoed["tool_calls"] = [
138
+ {
139
+ "id": tc.id,
140
+ "type": "function",
141
+ "function": {
142
+ "name": tc.function.name,
143
+ "arguments": tc.function.arguments or "{}",
144
+ },
145
+ }
146
+ for tc in msg.tool_calls
147
+ ]
148
+ self._conversation.append(echoed)
149
+
150
+ text_blocks = [text] if text else []
151
+ tool_calls: list[ToolCall] = []
152
+ for tc in msg.tool_calls or []:
153
+ try:
154
+ args = json.loads(tc.function.arguments) if tc.function.arguments else {}
155
+ except (TypeError, json.JSONDecodeError):
156
+ args = {}
157
+ tool_calls.append(
158
+ ToolCall(id=tc.id, name=tc.function.name, input=args)
159
+ )
160
+
161
+ return AgentTurn(
162
+ text_blocks=text_blocks,
163
+ tool_calls=tool_calls,
164
+ stop_reason=_normalize_finish_reason(choice.finish_reason),
165
+ )
166
+
167
+
168
+ def _to_openai_tools(tool_schemas: list[dict[str, Any]]) -> list[dict[str, Any]]:
169
+ """Translate the codebase's neutral tool schema (the ``tool_schemas()``
170
+ shape with ``name``/``description``/``input_schema``) into OpenAI's
171
+ ``{type: function, function: {...}}`` shape that vLLM consumes.
172
+
173
+ Same translation as ``qwen_hf._to_openai_tools`` β€” kept duplicated rather
174
+ than shared because the two backends are independently importable and we
175
+ don't want one to drag in the other's dependencies.
176
+ """
177
+ return [
178
+ {
179
+ "type": "function",
180
+ "function": {
181
+ "name": s["name"],
182
+ "description": s.get("description", ""),
183
+ "parameters": (
184
+ s.get("input_schema") or {"type": "object", "properties": {}}
185
+ ),
186
+ },
187
+ }
188
+ for s in tool_schemas
189
+ ]
190
+
191
+
192
+ def _normalize_finish_reason(reason: str | None) -> str:
193
+ """Map OpenAI finish_reason to our neutral set."""
194
+ if reason == "stop":
195
+ return "end_turn"
196
+ if reason == "tool_calls":
197
+ return "tool_use"
198
+ if reason == "length":
199
+ return "max_tokens"
200
+ return reason or "other"