|
| 1 | +"""Quick script to send a few throwaway traces to LangSmith. |
| 2 | +
|
| 3 | +Usage: |
| 4 | + export LANGSMITH_API_KEY=... # required |
| 5 | + export LANGSMITH_TRACING=true # recommended |
| 6 | + python python-sdk/examples/langsmith/dump_traces_langsmith.py |
| 7 | +
|
| 8 | +Notes: |
| 9 | +- This does not require any external model keys. It logs a few synthetic |
| 10 | + traced function calls, and optionally a tiny LangGraph flow if available. |
| 11 | +""" |
| 12 | + |
| 13 | +import asyncio |
| 14 | +import os |
| 15 | +from typing import Any, Dict, List |
| 16 | +import importlib |
| 17 | + |
| 18 | + |
| 19 | +def _ensure_env_defaults() -> None: |
| 20 | + # Prefer modern env vars; fall back maintained for compatibility. |
| 21 | + if os.environ.get("LANGSMITH_TRACING") is None: |
| 22 | + os.environ["LANGSMITH_TRACING"] = "true" |
| 23 | + # Project name helps organize traces in the LangSmith UI |
| 24 | + os.environ.setdefault("LANGCHAIN_PROJECT", "ep-langgraph-examples") |
| 25 | + |
| 26 | + |
| 27 | +def _log_synthetic_traces() -> None: |
| 28 | + traceable = None |
| 29 | + try: |
| 30 | + mod = importlib.import_module("langsmith") |
| 31 | + traceable = getattr(mod, "traceable", None) |
| 32 | + except ImportError: |
| 33 | + pass |
| 34 | + if traceable is None: |
| 35 | + print("LangSmith not installed; skipping @traceable demo. `pip install langsmith`.") |
| 36 | + return |
| 37 | + |
| 38 | + @traceable(name="toy_pipeline") |
| 39 | + def toy_pipeline(user_input: str) -> Dict[str, Any]: |
| 40 | + reversed_text = user_input[::-1] |
| 41 | + upper_text = reversed_text.upper() |
| 42 | + return {"result": upper_text, "len": len(upper_text)} |
| 43 | + |
| 44 | + print("Emitting synthetic traces via @traceable...") |
| 45 | + toy_pipeline("hello langsmith") |
| 46 | + toy_pipeline("trace number two") |
| 47 | + toy_pipeline("final short run") |
| 48 | + |
| 49 | + |
| 50 | +async def _maybe_run_tiny_langgraph() -> None: |
| 51 | + """Optionally run a tiny LangGraph flow to log a couple of runs. |
| 52 | +
|
| 53 | + This avoids any external LLM providers by using a pure-Python node. |
| 54 | + """ |
| 55 | + try: |
| 56 | + graph_mod = importlib.import_module("langgraph.graph") |
| 57 | + msg_mod = importlib.import_module("langgraph.graph.message") |
| 58 | + lc_msgs = importlib.import_module("langchain_core.messages") |
| 59 | + te_mod = importlib.import_module("typing_extensions") |
| 60 | + except ImportError: |
| 61 | + print("LangGraph/LangChain not installed; skipping tiny graph demo. `pip install langgraph langchain-core`.") |
| 62 | + return |
| 63 | + |
| 64 | + END = getattr(graph_mod, "END") |
| 65 | + StateGraph = getattr(graph_mod, "StateGraph") |
| 66 | + add_messages = getattr(msg_mod, "add_messages") |
| 67 | + AIMessage = getattr(lc_msgs, "AIMessage") |
| 68 | + BaseMessage = getattr(lc_msgs, "BaseMessage") |
| 69 | + HumanMessage = getattr(lc_msgs, "HumanMessage") |
| 70 | + Annotated = getattr(te_mod, "Annotated") |
| 71 | + TypedDict = getattr(te_mod, "TypedDict") |
| 72 | + |
| 73 | + class State(TypedDict): # type: ignore[misc] |
| 74 | + messages: Annotated[List[BaseMessage], add_messages] # type: ignore[index] |
| 75 | + |
| 76 | + async def echo_node(state: State, **_: Any) -> Dict[str, Any]: |
| 77 | + messages: List[BaseMessage] = state.get("messages", []) |
| 78 | + last_user = next((m for m in reversed(messages) if isinstance(m, HumanMessage)), None) |
| 79 | + content = getattr(last_user, "content", "") |
| 80 | + reply = AIMessage(content=f"Echo: {content}") |
| 81 | + return {"messages": [reply]} |
| 82 | + |
| 83 | + graph = StateGraph(State) |
| 84 | + graph.add_node("echo", echo_node) |
| 85 | + graph.set_entry_point("echo") |
| 86 | + graph.add_edge("echo", END) |
| 87 | + app = graph.compile() |
| 88 | + |
| 89 | + print("Emitting a couple LangGraph runs...") |
| 90 | + await app.ainvoke({"messages": [HumanMessage(content="hi there")]}) |
| 91 | + await app.ainvoke({"messages": [HumanMessage(content="how are you?")]}) |
| 92 | + |
| 93 | + |
| 94 | +def main() -> None: |
| 95 | + _ensure_env_defaults() |
| 96 | + |
| 97 | + if not os.getenv("LANGSMITH_API_KEY") and not os.getenv("LANGCHAIN_API_KEY"): |
| 98 | + print("Missing LangSmith API key. Set LANGSMITH_API_KEY (or LANGCHAIN_API_KEY) and rerun.") |
| 99 | + return |
| 100 | + |
| 101 | + _log_synthetic_traces() |
| 102 | + |
| 103 | + try: |
| 104 | + asyncio.run(_maybe_run_tiny_langgraph()) |
| 105 | + except RuntimeError: |
| 106 | + # Fallback for event loop already running (e.g. in notebooks) |
| 107 | + loop = asyncio.get_event_loop() |
| 108 | + loop.create_task(_maybe_run_tiny_langgraph()) |
| 109 | + loop.run_until_complete(asyncio.sleep(0.1)) |
| 110 | + |
| 111 | + print("Done. Visit LangSmith to see your new traces.") |
| 112 | + |
| 113 | + |
| 114 | +if __name__ == "__main__": |
| 115 | + main() |
0 commit comments