-
Notifications
You must be signed in to change notification settings - Fork 18
Feat/enrich rowlimit session #234
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Changes from 2 commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,39 @@ | ||
| #!/bin/bash | ||
| # Auto-reload dev runner for lang2sql-bot. | ||
| # Watches src/ for .py changes and restarts the bot automatically. | ||
|
|
||
| set -a | ||
| source "$(dirname "$0")/.env" | ||
| set +a | ||
|
|
||
| REF=$(mktemp) | ||
|
|
||
| restart_bot() { | ||
| if [ -n "$BOT_PID" ] && kill -0 "$BOT_PID" 2>/dev/null; then | ||
| echo "[watch] stopping PID $BOT_PID..." | ||
| kill "$BOT_PID" | ||
| wait "$BOT_PID" 2>/dev/null | ||
| fi | ||
| echo "[watch] starting bot..." | ||
| .venv/bin/lang2sql-bot & | ||
| BOT_PID=$! | ||
| touch "$REF" | ||
| echo "[watch] PID $BOT_PID" | ||
| } | ||
|
|
||
| trap 'kill $BOT_PID 2>/dev/null; rm -f $REF; exit' INT TERM | ||
|
|
||
| restart_bot | ||
|
|
||
| while true; do | ||
| sleep 2 | ||
| if find src/ -name "*.py" -newer "$REF" | grep -q .; then | ||
| CHANGED=$(find src/ -name "*.py" -newer "$REF" | head -3 | tr '\n' ' ') | ||
| echo "[watch] changed: $CHANGED" | ||
| restart_bot | ||
| elif ! kill -0 "$BOT_PID" 2>/dev/null; then | ||
| echo "[watch] bot crashed, restarting in 2s..." | ||
| sleep 2 | ||
| restart_bot | ||
| fi | ||
| done |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -11,8 +11,10 @@ | |
|
|
||
| from __future__ import annotations | ||
|
|
||
| import asyncio | ||
| import json | ||
| import os | ||
| import re | ||
| import urllib.error | ||
| import urllib.request | ||
| from typing import Any, Sequence | ||
|
|
@@ -27,15 +29,16 @@ class OpenAILLM: | |
|
|
||
| def __init__( | ||
| self, | ||
| model: str = "gpt-4.1-mini", | ||
| model: str = "gpt-4o-mini", | ||
|
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 🔎 (question) 기본 모델이 |
||
| api_key: str | None = None, | ||
| *, | ||
| base_url: str = _DEFAULT_URL, | ||
| timeout: float = 60.0, | ||
| ) -> None: | ||
| self.model = model | ||
| # Resolve lazily-ish: read env now, but tolerate absence until complete(). | ||
| self._api_key = api_key if api_key is not None else os.environ.get("OPENAI_API_KEY") | ||
| raw_key = api_key if api_key is not None else os.environ.get("OPENAI_API_KEY") | ||
| self._api_key = raw_key.strip() if raw_key else raw_key | ||
| self._base_url = base_url | ||
| self._timeout = timeout | ||
|
|
||
|
|
@@ -54,7 +57,7 @@ async def complete( | |
| if tools: | ||
| payload["tools"] = [_encode_tool(t) for t in tools] | ||
|
|
||
| raw = self._post(payload) | ||
| raw = await asyncio.to_thread(self._post, payload) | ||
| return _decode_completion(raw) | ||
|
|
||
| def _post(self, payload: dict[str, Any]) -> dict[str, Any]: | ||
|
|
@@ -83,11 +86,19 @@ def _post(self, payload: dict[str, Any]) -> dict[str, Any]: | |
| raise RuntimeError(f"OpenAI returned non-JSON response: {text[:200]!r}") from exc | ||
|
|
||
|
|
||
| def _strip_thinking(text: str) -> str: | ||
| return re.sub(r"<think>.*?</think>", "", text, flags=re.DOTALL).strip() | ||
|
|
||
|
|
||
| def _encode_message(m: Message) -> dict[str, Any]: | ||
| """Core :class:`Message` → an OpenAI chat message dict.""" | ||
| out: dict[str, Any] = {"role": m.role.value} | ||
| # OpenAI wants content present (may be null when only tool_calls are set). | ||
| out["content"] = m.content or None | ||
| # OpenAI allows null content only when tool_calls are present. | ||
| # For plain assistant messages (after session compress), force empty string. | ||
| if m.role == Role.ASSISTANT and not m.tool_calls: | ||
| out["content"] = m.content or "" | ||
| else: | ||
| out["content"] = m.content or None | ||
| if m.role == Role.TOOL: | ||
| out["tool_call_id"] = m.tool_call_id | ||
| if m.name: | ||
|
|
@@ -141,7 +152,7 @@ def _decode_completion(raw: dict[str, Any]) -> Completion: | |
| ) | ||
|
|
||
| return Completion( | ||
| content=msg.get("content") or "", | ||
| content=_strip_thinking(msg.get("content") or ""), | ||
| tool_calls=tool_calls, | ||
| finish_reason=choice.get("finish_reason"), | ||
| ) | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -22,6 +22,7 @@ | |
| from ...adapters.db.dsn_builder import assemble | ||
| from ...core.identity import Identity | ||
| from ...core.ports.frontend import OutboundMessage | ||
| from ...core.types import Role | ||
| from ...harness.loop import agent_loop | ||
| from ...tenancy.concierge import ContextConcierge | ||
| from .render import render_answer | ||
|
|
@@ -41,9 +42,34 @@ async def query(self, identity: Identity, text: str) -> OutboundMessage: | |
| thread/DM continues the conversation (tiebreaker #4). | ||
| """ | ||
| ctx = await self._concierge.build_context(identity, user_text=text) | ||
| pre_loop_len = len(ctx.session.history()) | ||
| answer = await agent_loop(ctx, text) | ||
|
|
||
| history = ctx.session.history() | ||
| current_turn = history[pre_loop_len:] | ||
|
|
||
| sql_queries = [ | ||
|
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. ❓ (question) 여기서 현재 턴의 |
||
| tc.arguments["sql"] | ||
| for msg in current_turn | ||
| if msg.role == Role.ASSISTANT and msg.tool_calls | ||
| for tc in msg.tool_calls | ||
| if tc.name == "run_sql" and "sql" in tc.arguments | ||
| ] | ||
| sql_results = [ | ||
| msg.content | ||
| for msg in current_turn | ||
| if msg.role == Role.TOOL and msg.name == "run_sql" and msg.content | ||
| ] | ||
|
|
||
| ctx.session.compress() | ||
| await self._concierge.store.save(identity.session_key(), ctx.session) | ||
| return render_answer(answer) | ||
|
|
||
| suffix = "" | ||
| if sql_queries: | ||
| suffix += "\n\n**SQL:**\n```sql\n" + "\n\n".join(sql_queries) + "\n```" | ||
| if sql_results: | ||
| suffix += "\n\n**결과:**\n```\n" + "\n\n".join(sql_results) + "\n```" | ||
| return render_answer(answer + suffix) | ||
|
|
||
| async def define_metric( | ||
| self, | ||
|
|
@@ -149,6 +175,14 @@ async def register_db_for_guild( | |
| ) | ||
| ) | ||
|
|
||
| async def enrich(self, identity: Identity, table: str = "", clear: bool = False) -> OutboundMessage: | ||
| """Run EnrichSchema tool: sample DB columns and LLM-infer descriptions.""" | ||
| ctx = await self._concierge.build_context(identity) | ||
| result = await ctx.tools.dispatch( | ||
| "enrich_schema", {"table": table, "clear": clear}, ctx, "cmd:enrich" | ||
| ) | ||
| return OutboundMessage(text=result.content) | ||
|
|
||
| async def connect(self, identity: Identity, dsn: str) -> OutboundMessage: | ||
| """V1 stub: stash a DB DSN keyed by guild/DM in the concierge kv store. | ||
|
|
||
|
|
||
Uh oh!
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
♻️ (suggestion) 테이블 목록 조회마다 풀을 비우는데, 매번
dispose()는 비용이 좀 있어요. enrich 직후처럼 스키마가 바뀌는 시점에만 무효화하는 방향은 어떨까요?