Spaces:
Runtime error
Runtime error
File size: 10,815 Bytes
8de92d1 ff1e468 8de92d1 ff1e468 27bba9c 8de92d1 ff1e468 8de92d1 27bba9c ff1e468 8de92d1 ff1e468 8de92d1 ff1e468 8de92d1 ff1e468 8de92d1 ff1e468 8de92d1 ff1e468 8de92d1 ff1e468 8de92d1 ff1e468 8de92d1 ff1e468 8de92d1 ff1e468 8de92d1 ff1e468 8de92d1 27bba9c ff1e468 27bba9c 8de92d1 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 |
"use client";
import { useState, useEffect, useCallback } from "react";
import { Card } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Flag, Clock, Hash, ArrowRight, Bot } from "lucide-react";
import { useInference } from "@/lib/inference";
import { API_BASE } from "@/lib/constants";
type Message = {
role: "user" | "assistant";
content: string;
};
const buildPrompt = (
current: string,
target: string,
path_so_far: string[],
links: string[]
) => {
const formatted_links = links
.map((link, index) => `${index + 1}. ${link}`)
.join("\n");
const path_so_far_str = path_so_far.join(" -> ");
return `You are playing WikiRun, trying to navigate from one Wikipedia article to another using only links.
IMPORTANT: You MUST put your final answer in <answer>NUMBER</answer> tags, where NUMBER is the link number.
For example, if you want to choose link 3, output <answer>3</answer>.
Current article: ${current}
Target article: ${target}
You have ${links.length} link(s) to choose from:
${formatted_links}
Your path so far: ${path_so_far_str}
Think about which link is most likely to lead you toward the target article.
First, analyze each link briefly and how it connects to your goal, then select the most promising one.
Remember to format your final answer by explicitly writing out the xml number tags like this: <answer>NUMBER</answer>`;
};
interface GameComponentProps {
player: "me" | "model";
model?: string;
maxHops: number;
startPage: string;
targetPage: string;
onReset: () => void;
maxTokens: number;
maxLinks: number;
}
export default function GameComponent({
player,
model,
maxHops,
startPage,
targetPage,
onReset,
maxTokens,
maxLinks,
}: GameComponentProps) {
const [currentPage, setCurrentPage] = useState<string>(startPage);
const [currentPageLinks, setCurrentPageLinks] = useState<string[]>([]);
const [linksLoading, setLinksLoading] = useState<boolean>(false);
const [hops, setHops] = useState<number>(0);
const [timeElapsed, setTimeElapsed] = useState<number>(0);
const [visitedNodes, setVisitedNodes] = useState<string[]>([startPage]);
const [gameStatus, setGameStatus] = useState<"playing" | "won" | "lost">(
"playing"
);
const [convo, setConvo] = useState([]);
const { status: modelStatus, partialText, inferenceResult, inference } = useInference({
apiKey:
window.localStorage.getItem("huggingface_access_token") || undefined,
});
const fetchCurrentPageLinks = useCallback(async () => {
setLinksLoading(true);
const response = await fetch(
`${API_BASE}/get_article_with_links/${currentPage}`
);
const data = await response.json();
setCurrentPageLinks(data.links.slice(0, maxLinks));
setLinksLoading(false);
}, [currentPage, maxLinks]);
useEffect(() => {
fetchCurrentPageLinks();
}, [fetchCurrentPageLinks]);
useEffect(() => {
if (gameStatus === "playing") {
const timer = setInterval(() => {
setTimeElapsed((prev) => prev + 1);
}, 1000);
return () => clearInterval(timer);
}
}, [gameStatus]);
// Check win condition
useEffect(() => {
if (currentPage === targetPage) {
setGameStatus("won");
} else if (hops >= maxHops) {
setGameStatus("lost");
}
}, [currentPage, targetPage, hops, maxHops]);
const handleLinkClick = (link: string) => {
if (gameStatus !== "playing") return;
setCurrentPage(link);
setHops((prev) => prev + 1);
setVisitedNodes((prev) => [...prev, link]);
};
const makeModelMove = async () => {
const prompt = buildPrompt(
currentPage,
targetPage,
visitedNodes,
currentPageLinks
);
pushConvo({
role: "user",
content: prompt,
});
const modelResponse = await inference({
model: model,
prompt,
maxTokens: maxTokens,
});
pushConvo({
role: "assistant",
content: modelResponse,
});
console.log("Model response", modelResponse);
const answer = modelResponse.match(/<answer>(.*?)<\/answer>/)?.[1];
if (!answer) {
console.error("No answer found in model response");
return;
}
// try parsing the answer as an integer
const answerInt = parseInt(answer);
if (isNaN(answerInt)) {
console.error("Invalid answer found in model response");
return;
}
if (answerInt < 1 || answerInt > currentPageLinks.length) {
console.error(
"Selected link out of bounds",
answerInt,
"from ",
currentPageLinks.length,
"links"
);
return;
}
const selectedLink = currentPageLinks[answerInt - 1];
console.log(
"Model picked selectedLink",
selectedLink,
"from ",
currentPageLinks
);
handleLinkClick(selectedLink);
};
const handleGiveUp = () => {
setGameStatus("lost");
};
const formatTime = (seconds: number) => {
const mins = Math.floor(seconds / 60);
const secs = seconds % 60;
return `${mins}:${secs < 10 ? "0" : ""}${secs}`;
};
const pushConvo = (message: Message) => {
setConvo((prev) => [...prev, message]);
};
return (
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
<Card className="p-4 flex col-span-2">
<h2 className="text-xl font-bold">Game Status</h2>
<div className="grid grid-cols-4 gap-4 mb-4">
<div className="bg-muted/30 p-3 rounded-md">
<div className="flex items-center gap-2 text-sm font-medium text-muted-foreground mb-1">
<ArrowRight className="h-4 w-4" /> Current
</div>
<div className="font-medium">{currentPage}</div>
</div>
<div className="bg-muted/30 p-3 rounded-md">
<div className="flex items-center gap-2 text-sm font-medium text-muted-foreground mb-1">
<Flag className="h-4 w-4" /> Target
</div>
<div className="font-medium">{targetPage}</div>
</div>
<div className="bg-muted/30 p-3 rounded-md">
<div className="flex items-center gap-2 text-sm font-medium text-muted-foreground mb-1">
<Hash className="h-4 w-4" /> Hops
</div>
<div className="font-medium">
{hops} / {maxHops}
</div>
</div>
<div className="bg-muted/30 p-3 rounded-md">
<div className="flex items-center gap-2 text-sm font-medium text-muted-foreground mb-1">
<Clock className="h-4 w-4" /> Time
</div>
<div className="font-medium">{formatTime(timeElapsed)}</div>
</div>
</div>
{player === "model" && (
<div className="mb-4 bg-blue-50 border border-blue-200 rounded-md p-3">
<div className="flex items-center gap-2">
<Bot className="h-4 w-4 text-blue-500" />
<span className="font-medium text-blue-700">
{model} {modelStatus === "thinking" ? "is thinking..." : "is playing"}
</span>
</div>
</div>
)}
</Card>
{/* Left pane - Current page and available links */}
<Card className="p-4 flex flex-col">
<h2 className="text-xl font-bold">Available Links</h2>
<div className="flex justify-between items-center mb-4">
{gameStatus !== "playing" && (
<Button onClick={onReset} variant="outline">
New Game
</Button>
)}
</div>
{/* Available links */}
{gameStatus === "playing" && (
<>
<div className="grid grid-cols-2 sm:grid-cols-3 gap-2 mb-4 overflow-y-auto max-h-[200px]">
{currentPageLinks
.sort((a, b) => a.localeCompare(b))
.map((link) => (
<Button
key={link}
variant="outline"
size="sm"
className="justify-start overflow-hidden text-ellipsis whitespace-nowrap"
onClick={() => handleLinkClick(link)}
disabled={player === "model" || modelStatus === "thinking"}
>
{link}
</Button>
))}
</div>
{player === "model" && (
<Button
onClick={makeModelMove}
disabled={modelStatus === "thinking" || linksLoading}
>
Make Move
</Button>
)}
</>
)}
{player === "model" && modelStatus === "thinking" && gameStatus === "playing" && (
<div className="flex items-center gap-2 text-sm animate-pulse mb-4">
<Bot className="h-4 w-4" />
<span>{model} is thinking...</span>
</div>
)}
{gameStatus === "playing" && player === "me" && (
<Button
onClick={handleGiveUp}
variant="destructive"
className="mt-auto"
>
Give Up
</Button>
)}
{gameStatus === "won" && (
<div className="bg-green-100 text-green-800 p-4 rounded-md mt-auto">
<h3 className="font-bold">
{player === "model" ? `${model} won!` : "You won!"}
</h3>
<p>
{player === "model" ? "It" : "You"} reached {targetPage} in {hops}{" "}
hops.
</p>
</div>
)}
{gameStatus === "lost" && (
<div className="bg-red-100 text-red-800 p-4 rounded-md mt-auto">
<h3 className="font-bold">Game Over</h3>
<p>
{player === "model" ? `${model} didn't` : "You didn't"} reach{" "}
{targetPage} within {maxHops} hops.
</p>
</div>
)}
</Card>
<Card className="p-4 flex flex-col max-h-[500px] overflow-y-auto">
<h2 className="text-xl font-bold">LLM Reasoning</h2>
{
convo.map((message, index) => (
<div key={index}>
<p>{message.role}</p>
<p>{message.content}</p>
<hr />
</div>
))
}
{ modelStatus === "thinking" && (
<div className="flex items-center gap-2 text-sm animate-pulse mb-4">
<Bot className="h-4 w-4" />
<p>{partialText}</p>
</div>
)}
</Card>
{/* <Card className="p-4 flex flex-col max-h-[500px] overflow-y-auto">
<iframe
src={`https://simple.wikipedia.org/wiki/${currentPage.replace(
/\s+/g,
"_"
)}`}
className="w-full h-full"
/>
</Card> */}
</div>
);
}
|